text:
---
layout: post
title: "Project in May"
description: ""
category: remarks
tags: []
---

{% include JB/setup %}
###from “I don’t care about performance, I just want it to work” to “thousands of people could be playing simultaneously, how do I scale?”

##Project in May

###using HTML template to generate pages
- Like using [EJS](http://embeddedjs.com/), but it is just too simple to use, not recommeded by `single page web application p207`
- using handlerbar.js(mustache.js), it cost about 120k, but with [hogan.js](http://twitter.github.io/hogan.js/), it only cost 2.5k
- last very popular way is to use jadeJs, which is defaultly embedded into node.js, also be supported natively by webstorm

###Markdown is a good language to simply write something
- markdown file is the most used text file in github,  which has a suffix of `md`
- [Wikipedia](http://zh.wikipedia.org/wiki/Markdown) and [Github](https://help.github.com/articles/markdown-basics) have clear explanation, plus there are quick introduction [here](http://jianshu.io/p/q81RER)

###Connect to MongoDB
- It is very convenient to connect to it in Heroku's control panel
- Use Robomongo to access to it, here is a good [tutorial](http://scotch.io/quick-tips/mongodb/connecting-to-mongodb-using-robomongo).
- There is `_v` in mongodb database, which means version key [explanation](http://aaronheckmann.tumblr.com/post/48943525537/mongoose-v3-part-1-versioning)
	The version key is only incremented after operations that could cause a conflict, modifying array positions. Other updates won't increment it.

###Build Express module to support Auth
- Mainly according to the tutorial [here](http://scotch.io/tutorials/javascript/easy-node-authentication-setup-and-local)
- Where I need to install body-parser from `npm install`, but here is a [article](http://andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html) says it may be create too much temp files.
- Maybe you should not use body-parser anymore due to [safty reason](http://stackoverflow.com/questions/20228203/how-to-get-post-fields-in-express-without-using-bodyparser-middleware)
- express-flash:define a flash message and render it without redirecting the request, require session and cookie-parser, which is just a flash show the info add to the screen, like formerlly you hide something and then it occurs, one difference in express4.0 is req.flash() (just use sessions: req.session.messages = `['foo']` or similar).  I have thought about useing socket.io instead, but actually this flash use messages stored in `session`
- bcrypt-nodejs [API](https://www.npmjs.org/package/bcrypt-nodejs).bcrypt是一个跨平台的文件加密工具。由它加密的文件可在所有支持的操作系统和处理器上进行转移。它的口令必须是8至56个字符，并将在内部被转化为448位的密钥。然而，所提供的所有字符都具有十分重要的意义。密码越强大，您的数据就越安全。

###Passport Js
**authentication and authorization**
authentication 仅仅是认证是本人  authorization 是授权可以做本人做的任何事

- 一旦认证成功，session将被建立，cookie将保存在客户端
- Each subsequent request will not contain credentials, but rather the unique cookie that identifies the session. In order to support login sessions, Passport will `serialize` and `deserialize` user instances to and from the session.之后的请求将都不会被要求认证，而是直接利用保存在客户端的cookie来确认身份，为了支持session，服务器端需要serialize and deserialize某些特定信息来确认是那一个用户（已认证成功的），‘’
	- passport.serializeUser(function(user, done) {
	  done(null, user.id);
	});

	passport.deserializeUser(function(id, done) {
	  User.findById(id, function(err, user) {
	    done(err, user);
	  });
	});

When Passport authenticates a request, it parses the credentials contained in the request. It then invokes the verify callback with those credentials as arguments, in this case username and password. If the credentials are valid, the verify callback invokes done to supply Passport with the user that authenticated.
	return done(null, user);

Here is a great [stackoverflow answer](http://stackoverflow.com/questions/15711127/express-passport-node-js-error-handling) on error handling. It explains how to use done() and how to be more specific with your handling of a route.

#####some problems:
[how to signup with detailed information??](http://stackoverflow.com/questions/11784233/using-passportjs-how-does-one-pass-additional-form-fields-to-the-local-authenti)

[how to make html as response without the index.html on the link path??](http://expressjs.com/api.html#app.engine)

	app.get('/', function(req,res) {
	  res.sendfile('public/index.html');
	});

###process.nextTick()
	On the next loop around the event loop call this callback. This is not a simple alias to setTimeout(fn, 0), it's much more efficient
，process.nextTick()的意思就是定义出一个动作，并且让这个动作在下一个事件轮询的时间点上执行。防止了一些情况下因为时间顺序导致的一些动作已经执行完，下面的被忽略的情况，[这里](http://www.cnblogs.com/lengyuhong/archive/2013/03/31/2987745.html)的例子很好

###Express.render and sender

###Use Handlebars as html template in Express
- use `npm install handlerbars --save` to install it
- use `npm install consolidate --save` to install consolidate, where in express official API doc has recommended.

	Some template engines do not follow this convention, the consolidate.js library was created to map all of node's popular template engines to follow this convention, thus allowing them to work seemlessly within Express.

then in our server.js

	var engines = require('consolidate');
	app.set('view engine', 'html')
	app.engine('html', engines.handlebars, function(err, html) {
	    if (err) throw err;
	    console.log("successful load handlebars engine");
	});
	//or direct use
	//app.engine('html', engines.handlebars);

here is a good [tutorial](http://expressjs-book.com/forums/topic/how-to-use-alternative-non-jade-template-engines-with-express/)
###How to use key value map in javascript
No standard method available. You need to iterate and you can create a simple helper:

	Object.prototype.getKeyByValue = function( value ) {
	    for( var prop in this ) {
	        if( this.hasOwnProperty( prop ) ) {
	             if( this[ prop ] === value )
	                 return prop;
	        }
	    }
	}

	var test = {
	   key1: 42,
	   key2: 'foo'
	};

	test.getKeyByValue( 42 );  // returns 'key1'

One word of caution: Even if the above works, its generally a bad idea to extend any host or native object's .prototype. I did it here because it fits the issue very well. Anyway, you should probably use this function outside the .prototype and pass the object into it instead.

Another way is illustrate in this basic [article](http://mckoss.com/jscript/object.htm)

	var associativeArray = {};
	associativeArray["one"] = "First";
	associativeArray["two"] = "Second";
	associativeArray["three"] = "Third";

###Express Page 404 Error Handling

basically

	app.use(function(req, res, next){
	  res.status(404);

	  // respond with html page
	  if (req.accepts('html')) {
	    res.render('404', { url: req.url });
	    return;
	  }

	  // respond with json
	  if (req.accepts('json')) {
	    res.send({ error: 'Not found' });
	    return;
	  }

	  // default to plain-text. send()
	  res.type('txt').send('Not found');
	});

For more detail on 500 and so on see [here](https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js)

###My questions about
[comparison bewteen HTTP protocal and web socket](http://stackoverflow.com/questions/23642778/http-post-and-socket-io)

###Express req.locals
Response local variables are scoped to the request, thus only available to the view(s) rendered during that request / response cycle, if any. Otherwise this API is identical to app.locals.

This object is useful for exposing request-level information such as the request pathname, authenticated user, user settings etcetera.

	app.use(function(req, res, next){
	  res.locals.user = req.user;
	  res.locals.authenticated = ! req.user.anonymous;
	  next();
	});

###Ligth box & Fancy box
use light box for some simple modal (min 9kb)
while fancy box is suitable for image gallery because it could use mouse wheel to wheel over the pictures.(min 23kb)
Here we may use [leanModal](http://leanmodal.finelysliced.com.au/) totally instead of lightbox, coz it is only 1kb :)

###JavaScript understanding

###Funtion overloading
	for(var prop in obj){
		obj[prop] = i //set the key value property pari for "prop: i"
	}

Check if a argument is offered by
If(parameter === undefined)

arguments used for present all the input variable of a function.

It is a array, which is using by arguments[i]

####hasOwnProperty()

Which could be used for check the property in the object, but not the prototyped property.

###The difference between setInterval() and setTimeout() is large.
Should remember to use these two method to make asynchronous loading and heavy processing.

The HTML5 attribute async and defer only affect to asychronous downloading

But not affect to the asynchronous loading

###Full page animation fullpage.js
	Overwriting [fullPage](https://github.com/alvarotrigo/fullPage.js).js tooltip color

	.fullPage-tooltip{
		color: #AAA;
	}
	#fullPage-nav span, .fullPage-slidesNav span{
		border-color: #AAA;
	}
	#fullPage-nav li .active span, .fullPage-slidesNav .active span{
		background: #AAA;
	}

here is CSS way to hidden scrollbar

	.outer{
	    position: absolute;
	    bottom: 0;
	    top:0;
	    width: 100%;
	    overflow: hidden;
	}
	.inner{
	    width: 100%;
	    height: 100%;
	    padding-right: 15px;
	    overflow: scroll;
	}
see examples on [jsfiddle](http://jsfiddle.net/uB6Dg/1/) here

###URI.JS
learn it maybe for the further use
=======
But not affect to the asynchronous loading,

###Difference between slice and substring
Notes on substring():

If start equals stop, it returns an empty string.
If stop is omitted, it extracts characters to the end of the string.
If start > stop, then substring will swap those 2 arguments.
If either argument is greater than the string's length, either argument will use the string's length.
If either argument is less than 0 or is NaN, it is treated as if it were 0.
Notes on slice():

If start equals stop, it returns an empty string, exactly like substring().
If stop is omitted, slice extracts chars to the end of the string, exactly like substring().
If start > stop, slice() will NOT swap the 2 arguments.
If either argument is greater than the string's length, either argument will use the string's length, exactly like substring().
If start is negative, slice() will set char from the end of string, exactly like substr() in Firefox. This behavior is observed in both Firefox and IE.
If stop is negative, slice() will set stop to: (string.length – 1) – Math.abs(stop) (original value).

In short, that is
-slice和substring在正确使用的情况下用法相同
-substring 会自动转换错误的前后顺序，会自动调整超出的范围，slice也会调整，但是遇到`负数`的情况，会有特殊处理。即从后往前数。

===
###Mongoose
- The Validator only works on saving progress, one problem is that you won't know it is a internal database problem or a validation problem
- Mongoose offer many ways for dealing with the [find](http://mongoosejs.com/docs/api.html#model_Model.find) method, like findOneAndRemove, findOneAndUpdate, here is the example
- testing date method

		Path.find({ start: /stuttgart/i }, 'date', function (err, docs) {
			var myDate =  new Date();
			docs = myDate;
			console.log('time is'+docs.getTime()
			+ 'day is' +docs.toDateString());
		});

expiring property could be set as:

		// expire in 24 hours
		new Schema({ createdAt: { type: Date, expires: 60*60*24 }});

		// expire in 24 hours
		new Schema({ createdAt: { type: Date, expires: '24h' }});

		// expire in 1.5 hours
		new Schema({ createdAt: { type: Date, expires: '1.5h' }});

		// expire in 7 days
		var schema = new Schema({ createdAt: Date });
		schema.path('createdAt').expires('7d');

###Socket.io
####broadcasting
how to update certain client or all client? how to handle socket parameter? `io.sockets.emit` or `io.emit` may add something like `of('/zugzug')`.

		// socket is the *current* socket of the client that just connected
		socket.emit('users_count', clients);

		//Instead, you want to emit to all sockets
		io.emit('users_count', clients);//

		//sends a message to everyone except the socket that starts it
		socket.broadcast.emit('users_count', clients);

####find certain client
setting a map for the online sockets with certain id, if need to send message to it. first check the map, and then send to that client

		//add
		chatterMap [user_map._id] = socket;

		//check
                if (!chatterMap[result_map._id]) {
                    signIn(io, result_map, socket);
                }

		//find
		if (chatterMap.hasOwnProperty(message.dest_id)) {
		chatterMap[message.dest_id].emit('updatechat', message) ;//where the socket save
		}

		//delete
		delete chatterMap[user_id];

		//add some property to it
		 socket.user_id = result_map._id;

#### disconnect listener

client side: socket.disconnect();
server side : socket.on('disconnect', function(){})

what about connect???

####important change for express
when you introduce server, must change the
		app.listen(8080);
to this
		server.listen(8080);

###Autosave with user input
Main idea is to save the information according to the keyboard event of jquery, to the local cookies.
- [Simple implementation](http://www.fayland.org/journal/AutoSave.html)
- with [Sisyphus.js](http://sisyphus-js.herokuapp.com/)


text:
Some Zshell Functions
=====================

This repository contains some simple zshell functions that have made my life a
little bit easier. They might help you too.

Usage
-----

To use, just add the functions you want in your zshell to your `.zshrc` like so:

    source path/to/repo/scriptname.sh

autostart-tmux.sh
-----------------

Starts tmux, if it is not already started.

push-ssh-key.sh
---------------

Adds a function to your shell to easily push your ssh key to a remote server.
Usage:

    push-ssh-key user@host

start-ssh-agent.sh
------------------

Starts the ssh-agent if it is not running already.

license: MIT

repository: jaapz/zsh-scripts

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: jaapz/zsh-scripts


text:
# Privacy evaluation framework for synthetic data publishing
A practical framework to evaluate the privacy-utility tradeoff of synthetic data publishing

Based on "Synthetic Data - Anonymisation Groundhog Day, Theresa Stadler, Bristena Oprisanu, and Carmela Troncoso, [arXiv](https://arxiv.org/abs/2011.07018), 2020"

# Attack models
The module `attack_models` so far includes

A privacy adversary to test for privacy gain with respect to linkage attacks modelled as a membership inference attack `MIAAttackClassifier`.

A simple attribute inference attack `AttributeInferenceAttack` that aims to infer a target's sensitive value given partial knowledge about the target record

# Generative models
The module `generative_models` so far includes:
- `IndependentHistogram`: An independent histogram model adapted from [Data Responsibly's DataSynthesiser](https://github.com/DataResponsibly/DataSynthesizer)
- `BayesianNet`: A generative model based on a Bayesian Network adapted from [Data Responsibly's DataSynthesiser](https://github.com/DataResponsibly/DataSynthesizer)
- `PrivBayes`: A differentially private version of the BayesianNet model adapted from [Data Responsibly's DataSynthesiser](https://github.com/DataResponsibly/DataSynthesizer)
- `CTGAN`: A conditional tabular generative adversarial network that integrates the CTGAN model from [CTGAN](https://github.com/sdv-dev/CTGAN)
- `PATE-GAN`: A differentially private generative adversarial network adapted from its original implementation by the [MLforHealth Lab](https://bitbucket.org/mvdschaar/mlforhealthlabpub/src/82d7f91d46db54d256ff4fc920d513499ddd2ab8/alg/pategan/)

# Setup

## Docker Distribution

For your convenience, Synthetic Data is also distributed as a ready-to-use Docker image containing Python 3.9 and CUDA 11.4.2, along with all dependencies required by Synthetic Data, including jupyter notebook to visualise and analyse the results.

**Note:** This distribution includes CUDA binaries, before downloading the image, ensure to read [its EULA](https://docs.nvidia.com/cuda/eula/index.html) and to agree to its terms.

Pull the image and run a container (and bind a volume where you want to save the data):

```
docker pull springepfl/synthetic-data:latest
docker run -it --rm -v "$(pwd)/output:/output" -p 8888:8888 springepfl/synthetic-data
```

The Synthetic Data directory is placed at the root directory of the container.
```
cd /synthetic_data_release
```

You should now be able to run the examples without encountering any problems, and you should be able to visualize the results with Jupyter by running
```
jupyter notebook --allow-root --ip=<IP_ADDRESS>
```

and opening the notebook with your favourite web browser at the url `http://<IP_ADDRESS>:8888/?token=<authentication token>`.

## Direct Installation

### Requirements
The framework and its building blocks have been developed and tested under Python 3.9 .

We recommend to create a virtual environment for installing all dependencies and running the code
```
python3 -m venv pyvenv3
source pyvenv3/bin/activate
pip install numpy==1.19.5 && pip install -r requirements.txt
```

Note: Some people encountered problems due to the API of Numpy having changed between versions, to ensure all dependencies are compiled against the same Numpy version, it needs to be installed first.

### Dependencies
The `CTGAN` model depends on a fork of the original model training algorithm that can be found here
[CTGAN-SPRING](https://github.com/spring-epfl/CTGAN.git)

To install the correct version clone the repository above and run
```
cd CTGAN
make install
```

Add the path to this directory to your python path. You can also add this line
in your shell configuration file (e.g., `~/.bashrc`) to load it automatically.
```bash
# Execute this in the CTGAN folder, otherwise replace `pwd` with the actual path
export PYTHONPATH=$PYTHONPATH:`pwd`
```

To test your installation try to run
```
import ctgan
```
from within your virtualenv `python`

# Example runs
To run a privacy evaluation with respect to the privacy concern of linkability you can run

```
python3 linkage_cli.py -D data/texas -RC tests/linkage/runconfig.json -O tests/linkage
```

The results file produced after successfully running the script will be written to `tests/linkage` and can be parsed with the function `load_results_linkage` provided in `utils/analyse_results.py`.
A jupyter notebook to visualise and analyse the results is included at `notebooks/Analyse Results.ipynb`.

To run a privacy evaluation with respect to the privacy concern of inference you can run

```
python3 inference_cli.py -D data/texas -RC tests/inference/runconfig.json -O tests/inference
```

The results file produced after successfully running the script can be parsed with the function `load_results_inference` provided in `utils/analyse_results.py`.
A jupyter notebook to visualise and analyse the results is included at `notebooks/Analyse Results.ipynb`.

To run a utility evaluation with respect to a simple classification task as utility function run

```
python3 utility_cli.py -D data/texas -RC tests/utility/runconfig.json -O tests/utility
```

The results file produced after successfully running the script can be parsed with the function `load_results_utility` provided in `utils/analyse_results.py`.

gha_language: Python

gha_license_id: NOASSERTION


text:
project_path: /web/_project.yaml
book_path: /web/shows/_book.yaml
description: Also how do you do TODO?

{# wf_updated_on: 2019-10-18 #}
{# wf_published_on: 2019-10-18 #}
{# wf_podcast_audio: https://storage.googleapis.com/http-203-podcast/episode-25.mp3 #}
{# wf_podcast_duration: 01:00:28 #}
{# wf_podcast_fileSize: 38066136 #}
{# wf_podcast_subtitle: Also how do you do TODO? #}
{# wf_featured_image: /web/shows/http203/podcast/images/surma-and-jake-2.jpg #}
{# wf_blink_components: Blink>CSS #}

# Stability, TODOs, and the HTTP 203 census {: .page-title }

In this episode we chat about:

* Unfortunate family trips.
* Surma becomes a manager.
* What color personality are you?
* Grid vs flexbox.
* Fixing layout instability.
* [What it's like to read the Hull Daily Mail](https://www.youtube.com/watch?v=uPnEZd6wCtk).
* [Fixing image aspect ratios, the easy way](https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/GePU9T8UpEc).
* [CSS counters](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Lists_and_Counters/Using_CSS_counters).
* [Font loading API](https://developer.mozilla.org/en-US/docs/Web/API/CSS_Font_Loading_API).
* [Font style matcher](https://meowni.ca/font-style-matcher/).
* CSS grid [`auto-fit` vs `auto-fill`](https://css-tricks.com/auto-sizing-columns-css-grid-auto-fill-vs-auto-fit/).
* The HTTP 203 census report.
* How to do TODO.
* UK vs US language issues.
* Jake's nephew aces awkward social situations.
* Surma can't hear stuff.
* [FollowUpThen](https://www.followupthen.com/).
* [Jake's IDB library](https://github.com/jakearchibald/idb/).

  rss_feed
  Subscribe

<audio style="width: 100%" src="https://storage.googleapis.com/http-203-podcast/episode-25.mp3"
controls preload="none"></audio>

repository: rachelandrew/WebFundamentals

repo_name: rachelandrew/WebFundamentals


text:
## Install

If you don't have [docker](https://docs.docker.com/get-docker) installed,
install Redis and start server

```
% sudo apt-get install -y redis-server

or

% brew install redis
% brew services start redis
```

Install with `pip`

```
% pip3 install chloop
```

> Optionally install ipython with `pip3 install ipython` to enable `:ipython`
> colon command on a GetCharLoop instance. Also `pip3 install pdbpp` for an
> improved debug experience when using `:pdb` colon command.

## Usage

The `GetCharLoop` class is provided by the `chloop` package. Calling an
**instance** of this class starts a REPL session, which the user can end by
pressing `Ctrl` + `d` or `Ctrl` + `c`.

> See the **Example** section below.

The **first** character you type at the REPL prompt is significant.

#### The colon

Hitting the `:` key at the prompt will allow you to enter a command and any
arguments you need to pass to that command.

- `:docstrings` to view docstrings of methods defined on the class
- `:errors` to view colon commands that raised exceptions
- `:history` view colon commands issued
- `:pdb` to start a pdb session (debugging/inspection)
- `:ipython` to start ipython shell
- `:shortcuts` to view hotkey shortcuts

Any methods added to your sub-class of `GetCharLoop` are callable as **colon
commands**, as long as they do not start with an underscore (`_`). Methods
should **only accept `*args`**, if anything.

For any methods/commands that should not be logged to the history, append the
method name to the end of the `self._DONT_LOG_CMDS` list.

#### The dash

Hitting the `-` key at the prompt will allow you to type a note.

#### The question mark

Hitting the `?` key at the prompt will display the class docstring(s) and the
startup message.

#### Other keys

Hitting any other key at the prompt will do one of the following:

- call a **registered shortcut function** bound to the key (use `:shortcuts`
  command to see what is available)
- display the character and its integer ordinal

A hotkey can be bound to any callable object that accepts no arguments.

> Use `functools.partial` (if necessary) to create a callable accepting no
> arguments.

Adding hotkeys (simple)

- call the `_add_hotkey` method on your instance of `GetCharLoop` (or sub-class)
  with the following args
    - `ch`: character hotkey
    - `func`: callable object that accepts no arguments
    - `help_string`: a string containing short help text for hotkey

Adding hotkeys (when using callables on `self`)

- call the `self._chfunc_dict_update` method in the `__init__` method of your
  subclass with a list of tuples or a dict.
    - the keys of the dict (or first items in list of tuples) are the hotkey
      characters
    - the values of the dict (or second items in list of tuples) are 2-item
      tuples
        - 1st item is a **callable** that accepts no arguments
        - 2nd item is a short help string

        > Note: when passing a dict, the items will be inserted in the
        > alphabetical order of  the help string.

## Basic example

```
% python3 -c 'from chloop import GetCharLoop; GetCharLoop()()'

> :docstrings
======================================================================
Loop forever, receiving character input from user and performing actions

    - ^d or ^c to break the loop
    - ':' to enter a command (and any arguments)
        - the name of the command should be monkeypatched on the GetCharLoop
          instance, or be a defined method on a GetCharLoop sub-class
        - the function bound to `:command` should accept `*args` only
    - '-' to receive an input line from user (a note)
    - '?' to show the class docstring(s) and the startup message

.:: docstrings ::.
Print/return the docstrings of methods defined on this class

.:: errors ::.
Print/return any colon commands that raised exceptions (w/ traceback)

.:: history ::.
Print/return colon commands used

.:: ipython ::.
Start ipython shell. To continue back to the input loop, use 'ctrl + d'

.:: pdb ::.
Start pdb (debugger). To continue back to the input loop, use 'c'

.:: shortcuts ::.
Print/return any hotkey shortcuts defined on this class

> :pdb
[10] > /tmp/ch/venv/lib/python3.5/site-packages/chloop/__init__.py(90)__call__()
-> continue
(Pdb++) l
 85                     cmd = user_input.split()[0]
 86                     args = user_input.split()[1:]
 87
 88                     if cmd == 'pdb':
 89                         import pdb; pdb.set_trace()
 90  ->                     continue
 91
 92                     if cmd == 'ipython':
 93                         from IPython import embed; embed()
 94                         continue
 95
(Pdb++) self._collection
Collection('chloop-log', 'default', index_fields='cmd,status,error_type', json_fields='args,value')
(Pdb++) self._collection.keyspace
[]
(Pdb++) c

> :ipython
Python 3.5.1+ (default, Mar 30 2016, 22:46:26)
Type "copyright", "credits" or "license" for more information.

IPython 5.2.2 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: self._collection
Out[1]: Collection('chloop-log', 'default', index_fields='cmd,status,error_type', json_fields='args,value')

In [2]: self.shortcuts
Out[2]: <bound method GetCharLoop.shortcuts of <chloop.GetCharLoop object at 0x7f9f8ff5f5f8>>

In [3]: self.docstrings
Out[3]: <bound method GetCharLoop.docstrings of <chloop.GetCharLoop object at 0x7f9f8ff5f5f8>>

In [4]:
Do you really want to exit ([y]/n)? y

> :shortcuts

> - there are no shortcuts defined by default

>
```

## Sub-class example

- Import `GetCharLoop` and sub-class it
- Initialize the sub-class and call it

> Save the following to `mine.py`

```
from functools import partial
from chloop import GetCharLoop

class Mine(GetCharLoop):
    """A sub-class of GetCharLoop"""
    def __init__(self, *args, **kwargs):
        # Process any extra/custom kwargs here and set some attributes
        self._mything = kwargs.pop('mything', 'some default value')

        super(Mine, self).__init__(*args, **kwargs)

        # Add some single-key shorcuts that call methods on `self`
        self._chfunc_dict_update([
            ('h', (self.history,
                  'display recent command history')),
            ('e', (self.errors,
                  'display recent errors')),
        ])

    def somefunc(self, *args):
        """Joins the args passed to it into a string"""
        args_as_one = ' '.join(args)
        print(repr(args_as_one))
        return args_as_one

    def lame(self):
        """raise exception"""
        return 1/0

if __name__ == '__main__':
    m = Mine(prompt='\nmyprompt> ')
    m._add_hotkey('a', lambda: print('hello'), 'say hello')
    m()
```

#### Interact with the REPL

> Assuming the above code is in a file called `mine.py`

```
% python mine.py

myprompt> :somefunc here are some args
u'here are some args'

myprompt> :shortcuts
'e' -- display recent errors
'h' -- display recent command history
'a' -- say hello

myprompt> a
hello

myprompt> :lame
======================================================================
Traceback (most recent call last):
  File "/home/ken/chloop/chloop/__init__.py", line 232, in __call__
    value = cmd_func()
  File "main.py", line 33, in lame
    return 1/0
ZeroDivisionError: integer division or modulo by zero

cmd: u'lame'
args: []

myprompt> :pdb
...

myprompt> e
(errors output)

myprompt> - here is a note

myprompt> - here is another note

myprompt>
```

repository: kenjyco/chloop

repo_name: kenjyco/chloop


text:
---
layout: default
---

# 1996-08-07 - Re: PGP public key servers are NOT useful!

## Header Data

From: "Perry E. Metzger"<EMAIL_ADDRESS>To<EMAIL_ADDRESS>Message Hash: eea5609817b264fe9b3dabb1868aa7c63ef1a28a7bf4982f7c3fd0376d2d5fb4

Message ID<EMAIL_ADDRESS>Reply To<EMAIL_ADDRESS>UTC Datetime: 1996-08-07 23:44:08 UTC

Raw Date: Thu, 8 Aug 1996 07:44:08 +0800

## Raw message

```
{% raw  %}From: "Perry E. Metzger"<EMAIL_ADDRESS>Date: Thu, 8 Aug 1996 07:44:08 +0800
To<EMAIL_ADDRESS>Subject: Re: PGP public key servers are NOT useful!
In-Reply-To<EMAIL_ADDRESS>Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

John Anonymous MacDonald writes:
> The problem with the PGP public key servers is that
> one has absolutely no control over what gets uploaded there in one's
> own name.

Thats why people are supposed to use the web of trust to check the
keys. You claim to make your key available by finger. How do you know
that Mallet isn't switching the bits as they go down the wire to your
correspondants? The only way to verify a key is to check known good
signatures on it. Because of this, no security is needed on key
storage facilities per se -- you aren't supposed to trust keys without
signatures.

Geesh. I thought this was obvious. I guess not.

Perry

{% endraw %}
```

## Thread

+ Return to [August 1996](/archive/1996/08)

+ Return to "[Amnesia Anonymous Remailer <amnesia@chardos.connix.com>](/authors/amnesia_anonymous_remailer_amnesia_at_chardos_connix_com_)"
+ Return to "["David E. Smith" <dsmith@prairienet.org>](/authors/david_e_smith_dsmith_at_prairienet_org_)"
+ Return to "[John Anonymous MacDonald <remailer@cypherpunks.ca>](/authors/john_anonymous_macdonald_remailer_at_cypherpunks_ca_)"
+ Return to "["Perry E. Metzger" <perry@piermont.com>](/authors/perry_e_metzger_perry_at_piermont_com_)"

+ 1996-08-06 (Tue, 6 Aug 1996 08:34:08 +0800) - [PGP public key servers are useful! [noise?]](/archive/1996/08/33aa774136a2ed4278badfea239b5202127f29745e4d08dead7352ea6ace2236) - _"David E. Smith"<EMAIL_ADDRESS>  + 1996-08-06 (Tue, 6 Aug 1996 16:16:43 +0800) - [PGP public key servers are NOT useful!](/archive/1996/08/7a06525860fb49155e8eddd09f285bd296f0e77ce4fd50bf7431a9ff1c4a58c1) - _John Anonymous MacDonald<EMAIL_ADDRESS>    + 1996-08-07 (Thu, 8 Aug 1996 07:44:08 +0800) - Re: PGP public key servers are NOT useful! - _"Perry E. Metzger"<EMAIL_ADDRESS>      + 1996-08-08 (Thu, 8 Aug 1996 15:47:15 +0800) - [Re: PGP public key servers are NOT useful!](/archive/1996/08/3b5c879246ac3cbd9c0967ce8a6fc92f90455194e1b0ab13c7fea31d7b67e4ab) - _Amnesia Anonymous Remailer<EMAIL_ADDRESS>

gha_license_id: MIT


text:
# another_cart
Yet another implementation for shopping cart, really simple and easy to use.

## Installation
* Add `gem "kart"` to Gemfile
* Run `bundle install`

## Usage
**Make sure to create [User] and [Product] model beforehand**
* `rails generate cart [User] [Product]`\
example: `rails g cart Member Book` will create a cart contains books selected by a member.
* `rails db:migrate`
these files created by this command are self-explanatory.
* insert `selecting :product` to [User] and `selected_by :user` to [Product].

## Export methods
* `selecting_products`: list of products are selected by current user
* `show_cart`: list of product id and quantity in cart of current user
* `add_to_cart (Product)`: add 1 product to cart
* `remove_from_cart (Product)`: remove 1 product from cart
* `remove_all_from_cart`: remove all products from cart (when checking out successfully)
* `add_multiple_to_cart (Product,number)`: add multiple products to cart

## Handling exception
* **Kart::UserNotDefined**: insert `selected_by` into Product model
* **Kart::ProductNotDefined**: insert `selecting` into User model
* **Kart::ItemNotFound**: item need to be added to cart before removed

gha_language: Ruby


text:
# Athan Times webhook implementation in Python

This is a really simple webhook implementation that gets Api.ai classification JSON (i.e. a JSON output of Api.ai /query endpoint) and returns a fulfillment response.

This services uses https://aladhan.com/prayer-times-api to get the prayer times.


text:
## Practice Quiz: Reading & Writing CSV Files
* **Total points: 5**
* **Score: 80% (?)**

### Question 1

We're working with a list of flowers and some information about each one. The create_file function writes this information to a CSV file. The contents_of_file function reads this file into records and returns the information in a nicely formatted block. Fill in the gaps of the contents_of_file function to turn the data in the CSV file into a dictionary using DictReader.

```
import os
import csv

# Create a file with data in it
def create_file(filename):
  with open(filename, "w") as file:
    file.write("name,color,type\n")
    file.write("carnation,pink,annual\n")
    file.write("daffodil,yellow,perennial\n")
    file.write("iris,blue,perennial\n")
    file.write("poinsettia,red,perennial\n")
    file.write("sunflower,yellow,annual\n")

# Read the file contents and format the information about each row
def contents_of_file(filename):
  return_string = ""

  # Call the function to create the file
  create_file(filename)

  # Open the file
  with open(filename) as file:
    # Read the rows of the file into a dictionary
    reader = csv.DictReader(file)
    # Process each item of the dictionary
    for row in reader:
      return_string += "a {} {} is {}\n".format(row["color"], row["name"], row["type"])
  return return_string

#Call the function
print(contents_of_file("flowers.csv"))
```

**Note**

This question throws:
> Incorrect\
Something went wrong! Contact Coursera Support about this question!

Output:
```
a pink carnation is annual
a yellow daffodil is perennial
a blue iris is perennial
a red poinsettia is perennial
a yellow sunflower is annual
```

### Question 2

Using the CSV file of flowers again, fill in the gaps of the contents_of_file function to process the data without turning it into a dictionary. How do you skip over the header record with the field names?

```
import os
import csv

# Create a file with data in it
def create_file(filename):
  with open(filename, "w") as file:
    file.write("name,color,type\n")
    file.write("carnation,pink,annual\n")
    file.write("daffodil,yellow,perennial\n")
    file.write("iris,blue,perennial\n")
    file.write("poinsettia,red,perennial\n")
    file.write("sunflower,yellow,annual\n")

# Read the file contents and format the information about each row
def contents_of_file(filename):
  return_string = ""

  # Call the function to create the file
  create_file(filename)

  # Open the file
  with open(filename, "r") as file:
    # Read the rows of the file
    rows = csv.reader(file)
    # Process each row
    for row in list(rows)[1:]:
      name, color, types = row
      # Format the return string for data rows only
      return_string += "a {} {} is {}\n".format(color, name, types)
  return return_string

#Call the function
print(contents_of_file("flowers.csv"))
```

Output:

```
a pink carnation is annual
a yellow daffodil is perennial
a blue iris is perennial
a red poinsettia is perennial
a yellow sunflower is annual
```

### Question 3

In order to use the writerows() function of DictWriter() to write a list of dictionaries to each line of a CSV file, what steps should we take? (Check all that apply)

* **Create an instance of the DictWriter() class**
* **Write the fieldnames parameter into the first row using writeheader()**
* **Open the csv file using with open**
* Import the OS module

> We have to create a DictWriter() object instance to work with, and pass to it the fieldnames parameter defined as a list of keys.

> The non-optional fieldnames parameter list values should be written to the first row.

> The CSV file has to be open before we can write to it.

### Question 4

Which of the following is true about unpacking values into variables when reading rows of a CSV file? (Check all that apply)

* **We need the same amount of variables as there are columns of data in the CSV**
* **Rows can be read using both csv.reader and csv.DictReader**
* **An instance of the reader class must be created first**
* The CSV file does not have to be explicitly opened

> We need to have the exact same amount of variables on the left side of the equals sign as the length of the sequence on the right side when unpacking rows into individual variables.

> Although they read the CSV rows into different datatypes, both csv.reader or csv.DictReader can be used to parse CSV files.

> We have to create an instance of the reader class we are using before we can parse the CSV file.

### Question 5

If we are analyzing a file's contents to correctly structure its data, what action are we performing on the file?

* Writing
* Appending
* **Parsing**
* Reading

> Parsing a file means analyzing its contents to correctly structure the data. As long as we know what the data is, we can organize it in a way our script can use effectively.

branch_name: refs/heads/main


text:
## DRAFT

# What is [nodecpp](http://bit.ly/Y3qP1R)?

This project is an attempt to manifest learnings from node.js, Ruby on Rails,
Python, and other frameworks into a new framework targeting C++11.

*TODO*: Discuss the pros and cons related to "coding by convention"
experienced by Ruby on Rails folks, and PHP folks, etc...

## Idea
Nodecpp is a cross-platform event-based application model for C++11. The
platform's fundamental design component is asynchronicity through continuations
via C++11 lambdas. For example:

	/* setup a server to dynamically return GET requests from an alternate host */
	http_get_route("/", [](const http_request_ptr_t &req, const http_response_ptr_t &response) {
		http_get("http://example.com/proxy/dest", 80 /*port*/, [=](const http_client_response_t &res) {
			response->set_response(200, "OK", res.fields["Content-type"]);
			response->send(res.body);
			response->end();
		});
	});

The deliverable of this project will be a set of portable source code for use
for free as a base for new application development.  Along with this base, we
should be able to provide a set of components to accomplish basic tasks, like
accepting HTTP connections, connecting to file-shares, or starting multi-cast
IP transmissions. Longer term, we might aspire to building a responsive and
cancellable client-side graphical UI or rendering framework.

Threading and compute thoughts are around using thread pools for task dispatch,
but maintaining the main thread event loop for handling continuation after compute.

This project will rely on contributors like you. If you'd like to be involved,
please [get in touch](http://bit.ly/wbbradley-github).

*TODO*: discuss promises, futures, etc...

*TODO*: discuss how a framework in C++11 can equally (or better) address the
goals of the the ["coding by
convention"](http://en.wikipedia.org/wiki/Convention_over_configuration) folks.

*TODO*: discuss the bar for success when it comes to "ease of development."
Meaning, is there a way to know when/if we've created a platform that is more
efficient in terms of developer time than other application development
platforms?

*TODO*: discuss feelings of texty people coming from Ruby/Python around string
manipulation and whether C++11 syntax is or is not deep enough to address text
manipulation ease-of-use issues.

*TODO*: look into hooks for easy calls to/from other languages.

*TODO*: target non-goals, like having a [REPL](http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop).

## Phase 1 - Proof of concept
In order to prove that this idea can scale, the first project should enable
serving static files from a front-end server at roughly the same benchmark
performance characterstics as high-speed servers such as nginx, and node.js.
(*TODO*: identify goal benchmarks.)

### HTTP Client
* Issuing requests
* Redirection handling
* Simple APIs
	* GET
	* POST

### HTTP Server
* Listening
* Parsing Request Headers
* Routing
	* Dispatch via the routes table to the appropriate app-defined callback
	* Enable middleware / Next() continuations
* http\_respond\_t design/impl
	* Simple Content-length
	* Chunking
	* Redirects
	* Errors API
* Keep-alive for multi-requests

### SSL integration (https)

### File I/O
* Basic read
* Basic write
* Open memory-mapped
* File enumeration
* Directory/File change notification
* Create directory
* Create file
* stat, etc...
* Flush

### JSON
* DOM
* Streaming

### Timers

### Express-like features
* Static file serving

## Later Phases
### Database connect
* RDBMS
	* MySQL
	* Postgres
* NoSQL
	* MongoDB
	* Redis
	* ...
* ORM

### IPC
* Pipes
* Shared memory
* Spawning processes

### Clustering

### Compute
* Compute tasks
* Task pool
* GPU compute integration

### WebSocket Server
* Upgrading from HTTP connections
* Investigate proper callback API design

### HTML parsing
* streaming templates

### MVC Framework

### XML
* DOM
* Streaming

### ...

# Build Instructions

* Install [md2pdf](https://github.com/joequery/md2pdf)

From within the nodepp directory:

`make`

--
[Will Bradley](http://github.com/wbbradley)

repository: mbeloshitsky/nodecpp

repo_name: mbeloshitsky/nodecpp


text:
# Learn Redis with Laravel 5.8

A repository for learning redis and integrate with laravel, this is repository for learning not for production

## Getting Started

1. ``run redis server``
2. ``run laravel app``

### Prerequisites

- Read this [basic redis command](https://github.com/arifsetyo21/cheat-sheet-s/blob/master/Redis%20Tutorial%20for%20Beginner/README.md)

### Step-by-Step

#### Episode 1
   Installing PRedis which is php library for connection and query in redis, written in PHP.
#### Episode 2
   Installing PhpRedis which is php library for php interact to redis, written in C, as result, if we use this library performance be better than PRedis.
#### Episode 3
   in this episode, we will try to add key and value to redis server, create counter page view with sorted set data type, and create order popular page views.

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE) file for details

## Acknowledgments

* [Christophe Limpalair Youtube Channel](https://www.youtube.com/channel/UCzo_FqWUbEH0AYs0NilUWpA)
* [ProgrammingKnowledge Youtube Channel](https://www.youtube.com/watch?v=64VG179N4no&list=PLS1QulWo1RIYZZxQdap7Sd0ARKFI-XVsd)


text:
# Puck 101 Slides

Some thoughts on hockey analytics, and a demo of NHL charts made with d3js.

## Feedback

Send to [@Puck_Quant](http://twitter.com/Puck_Quant).

Updated [demo](http://vast-trail.surge.sh/) is here.

#### Thanks

Project was forked from [Spectacle Boilerplate](https://github.com/FormidableLabs/spectacle/), a great starter for slides made with `react`/`webpack`.

## DEPLOYS

deploy with surge.sh (a neat CLI).

extension: markdown


text:
# Course 046196 - Introduction to Machine Learning

The website can be found at <https://technion046195.netlify.app/>

This repository contains:

- The site's content.
- The Jupyter notebooks which are uses to to create some of the courses content.
- The Jupyter notebooks assignments.

## Some technical details

The course's website is powered by the [Gatsby platform](http://gatsbyjs.com/), and is served using [netlify](https://www.netlify.com/). In addition the site and the Jupyter server can be ran locally using a [docker](https://www.docker.com/) container. The details about running the site locally can be found bellow.

The content of the web site (lectures, tutorials, additional data) is written in [markdown](https://en.wikipedia.org/wiki/Markdown) and is concentrated in the content folder.

The deployment status of the site can be found here: [![Netlify Status](https://api.netlify.com/api/v1/badges/98ffd985-f712-420b-9c05-2fd440fd134f/deploy-status)](https://app.netlify.com/sites/technion046195/deploys)

The diagrams in this course are generated using [draw.io](https://app.diagrams.net/). The file containing all the diagrams can be found in *content/assets/diagrams.drawio*

## Contributing

The suggested way for editing the content of the website is by running the site localy which is updated on the fly as the markdown content is being updated.

### Install docker

In order to run the site locally docker must be installed. On Ubuntu 18.04 (or newer) this can be done using the following commands:

``` bash
sudo apt install docker.io
sudo systemctl start docker
sudo systemctl enable docker
```

The installation details for other OSs can be found on the offical website:

- **Windows**: <https://docs.docker.com/docker-for-windows/install/>
- **Mac**: <https://docs.docker.com/docker-for-mac/install/>
- **Other linux distributions**: <https://docs.docker.com/engine/install/>

### Running locally

To run the website and the Jupyter server move to the folder containing this repository and run the following command:

``` bash
sudo docker run -it --rm -v "$PWD:/project/app" --net=host omeryair/technion046195:v0.1
```

The website should then be avilable at <http://localhost:8000>. The jupyter service should be avilable at <http://localhost:7000/tree/content>.

At this point changes which are made to the markdown file in the content folder should immediately appear on the site each save of the file. The markdown files can be edit using any arbitrary text editor or be dedicated editors (see resources section).

## Editing markdown files

### [Typora](https://typora.io/)

Typora is a dedicated editor for markdown files an formats the markdown text as you type it (including equations). Typora does not support viewing right-to-left(RTL) documents out of the box, but this can be fixed by adding an custom RTL theme.

### Adding support for inline equatiopins

Support for inlien equations should be added in *File->Presences->Markdown->Syntax Support->Inline Math

### Adding RTL theme

On such RTL theme can be found at <https://github.com/peleg68/github-rtl>. To add it to Typora you need to download the *github-rtl.css* file and the *github-rtl* folder to Typora's theme's folder. The theme folder can be found by goint to *File->Preference->Appearance->OpenTheme Folder*.

After adding the theme it can be selected from the Themes menu.

### [VSCode](https://code.visualstudio.com/)

VSCode in a great open-source code editor maintained by Microsoft. It offers live markdown preview out of the box but without support for equations. Equation support can be added by installing an plugin such as [Markdown+Math](https://marketplace.visualstudio.com/items?itemName=goessner.mdmath)

### Committing notebooks

In order to remove some unnecessary temporary data from the Jupyter notebooks (which clutters the commits) use the following method to add an automatic clean up command to the git add process (this will only have effect in this repository). This need to be done once:

1. Install jq

  ``` bash
  sudo apt install jq
  ```

2. run the following command in the repository folder:

  ```bash
  git config --local include.path ../.gitconfig
  ```

## Resources

Free images:

- [Unsplash](https://unsplash.com/)
- [Pixabay](https://pixabay.com/)
- [Pexels](https://www.pexels.com/)

Free vector graphics:

- [freepik](https://www.freepik.com/)
- [Vecteezy](https://www.vecteezy.com/)
- [Free Vector](https://www.freevector.com/)


text:
# sweep

### Sweep - analyse data from JIRA

* Authenticates to and accesses JIRA
* Sends requests to the JIRA REST API and reformats the results
* Defines the result of a query to JIRA as a QueryFrame object which contains all date you might want to get from it
* Partially caches results in a local database for speeding up repeatedly querying
* Provides some utilities for dealing with the data
* Sweep offers data in the convenient pandas DataFrame format

### New: Jupyter support

Sweep now supports JQL queries which result in a `QueryFrame`, which encapsulates several pandas `DataFrames`.
This allows for more readable operations on the data and for interactive development with Jupyter notebooks.

Check out the [instructional notebook](src/notebook_to_jira.ipynb) that shows how to use Sweep and the [examples](src/examples.ipynb)

# Goal
Create unified reports on work planned and done out of Jira for a whole portfolio.

1. Avoid creating "dashboards" per project or team
   - Time consuming to configure and maintain
   - Unlikely to be or remain uniform
   - Relatively hard to navigate to and through

2. No navigation to reports needed (typical in Jira: go to project, go to reports, select the right report, select e.g. version, then see report)

3. Have a single overview of progress for the entire portfolio

4. Use Jupyter and pandas `DataFrames` for comfortable interactive development of new functionality.

# Assumptions
1. An extra Jira project can be created for project meta-data
2. No assumptions on methodology (Scrum or Kanban, storypoints or estimations in time)

# Plan

## Current status

[Proof of Concept](poc.md) is completed. It ties together connecting with the Jira Cloud, caching issues in a local database, using a graphical library to generate a number of charts (line chart, area chart, pie chart), and present the result in generated HTML using a templating system.

Current development goals can be found in the [plan](plan.md)

Actual changes and the reasons for them can be found in [changes](changes.md)

# Installation & running
Details on installation and running Sweep are in [INSTALL.md](INSTALL.md)

# Other JIRA data analysis projects
[jira metrics extract](https://github.com/rnwolf/jira-metrics-extract)

repository: ceesroele/portfolio-sweep

repo_name: ceesroele/portfolio-sweep


text:
## Abstract

This project addresses the modeling and simulation of progressive changes over time, such as human face aging. By treating the age phases as a sequence of image domains, we construct a chain of transformers that map images from one age domain to the next. Leveraging recent adversarial image translation methods, our approach requires no training samples of the same individual at different ages. Here, the model must be flexible enough to translate a child face to a young adult, and all the way through the adulthood to old age. We find that some transformers in the chain can be recursively applied on their own output to cover multiple phases, compressing the chain. The structure of the chain also unearths information about the underlying physical process. We demonstrate the performance of our method with precise and intuitive metrics, and visually match with the face aging state-of-the-art.

## Paper

[Paper preprint](https://arxiv.org/abs/1802.05023)

## Examples

A partially-recursive transformation sequence for transforming an approximately 15-year-old to 65-year-old.
The double-trained 25→35 transformer is applied also to 35→45 transformation.

![alt text](samples/age_15_id_2B.jpg)
![alt text](samples/age_25_id_2B.jpg)
![alt text](samples/age_35_id_2B.jpg)
![alt text](samples/age_45_id_2B.jpg)
![alt text](samples/age_55_id_2B.jpg)
![alt text](samples/age_65_id_2B.jpg)

## Codes

[Source code and utilities on GitHub](https://github.com/AaltoVision/img-transformer-chain)

## Referencing

```
@inproceedings{Heljakka+Solin+Kannala:2018,
      title = {Recursive Chaining of Reversible Image-to-image Translators For Face Aging},
     author = {Heljakka, Ari and Solin, Arno
               and Kannala, Juho},
       year = {2018},
  booktitle = {Proceedings of Advanced Concepts for Intelligent Vision Systems }
}
```

repository: AaltoVision/img-transformer-chain

repo_name: AaltoVision/img-transformer-chain


text:
---
title: "associate_vlan.go"
description: "associate_vlan.go"
date: "2017-11-23"
classes:
    - "SoftLayer_Network_Gateway_Vlan"
tags:
    - "gateway"
---

```go
/*
Associate a Network_Vlan object in a gateway device.

Important manual pages:
http://sldn.softlayer.com/reference/services/SoftLayer_Network_Gateway_Vlan/createObjects
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_Gateway_Vlan

License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc<EMAIL_ADDRESS>*/
package main

import (
	"fmt"
	"github.com/softlayer/softlayer-go/datatypes"
	"github.com/softlayer/softlayer-go/services"
	"github.com/softlayer/softlayer-go/session"
	"github.com/softlayer/softlayer-go/sl"
	"encoding/json"
)

func main() {
	// SoftLayer API username and key
	username := "set me"
	apikey   := "set me"

	// If true, Vlan will be bypassed. If false, it will be routed.
	bypassFlag := true

	// The id of gateway you wish to associate.
	gatewayId := 61522

	// The id of vlan you wish to associate. To get the vlan id you can run the method
	// SoftLayer_Network_Gateway_Vlan::getPossibleInsideVlans
	vlanId := 1502997

	// Build Network_Gateway_Vlan skeleton in order to pass it to createObject() method
	templateObject := datatypes.Network_Gateway_Vlan{
		BypassFlag:       sl.Bool(bypassFlag),
		NetworkGatewayId: sl.Int(gatewayId),
		NetworkVlanId:    sl.Int(vlanId),
	}

	// Create a session
	sess := session.New(username, apikey)

	// Get SoftLayer_Network_Gateway_Vlan service
	service := services.GetNetworkGatewayVlanService(sess)

	// Call to createObject() method to associate vlan to gateway
	gatewayVlan, err := service.CreateObject(&templateObject)
	if err != nil {
		fmt.Printf("\n Unable to create association:\n - %s\n", err)
		return
	}

	// Following helps to print the result in json format.
	jsonFormat, jsonErr := json.MarshalIndent(gatewayVlan,"","     ")
	if jsonErr != nil {
		fmt.Println(jsonErr)
		return
	}
	fmt.Println(string(jsonFormat))
}

```

gha_language: HTML


text:
# Sitemap 参考

Introduction

The sitemap.xml defines the sitemap of a site. It provides an overview of a web application and assembles all pages and resources together.

A typical sitemap.xml has the following structure:

```xml
        <site domain="dev.test">
            <common>...</common>
            <page template="templates/single.xml" path="" />*
            <resources dir="images" path="images" />*
            <services>...</services>
        </site>
```

One will immediately notices the following sections:

Common section: this section contains common page headers that will be embedded into all pages.

Page section: a web application contains one or more pages.

Resources section: this mapps static resources to be delivered directly without any processing.

Services section: this section defines REST style services.

The common section

In the common section, all contents will be incorporated into each page.

```xml
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,  initial-scale=1" />
    <title>XPE Cloud IDE</title>
        <link rel="stylesheet" href="/css/common.css" />
        <link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon" />
        <combine>
            <script src="/js/core.js" />
            <script src="/js/sha256.js" />
            <script src="/js/login.js" />
            <script src="/js/session.js" />
        </combine>
    </head>
```

In the example, an html head is defined and the head will be merged with all head sections of each page. All normal html5 head tags are allowed.

The combine element will instruct XPE to combine all scripts together to become one single file in order to reduce the number questions for faster loading.

Using group

The concept of group extends from common.  For example, a number of pages need to use the same set of css and javascripts but not all pages do.  In situations like this,
    you first declare a group and assign it a uniquie id.  Subsequently, you refer to the group by referencing this id as shown in the example below.  The framework will
    automatically merge the head section and body sections.

```xml
    <group id="backend">

        <head>
            <link rel="stylesheet" href="/css/pagination.css" />
            <link rel="stylesheet" href="/css/common.css" />
            <link rel="stylesheet" href="/css/form.css" />
            <link rel="stylesheet" href="/css/panel.css" />
            <link rel="stylesheet" href="/css/desktop.css" />
            <link rel="stylesheet" href="/css/leftmenu.css" />
            <script src="/js/desktop.js" />
            <script src="/js/ie8.js" />
            <script src="/js/tinyscrollbar.js" />
            <script src="/js/leftmenu.js" />
            <script src="/js/paginationSamePage.js" />
            <script src="/js/cusImageSelector.js" />
            <script src="/js/getDate.js" />
        </head>
        <load href="content/header.xml" to="header" />
        <load href="content/leftmenu.xml" to="menu" />
        <load href="content/footer.xml" to="footer" />
    </group>
    <!-- 首页 -->
    <page template="templates/single.xml" path="" title="首页">
        <group ref="backend"></group>

        <head>
            <link rel="stylesheet" href="/css/panel.css" />
        </head>
        <load href="content/aboutSite.xml" to="panel" />
    </page>
```

The services section

In this section, various services can be configured:

```xml
<services>
            <service store="tickets.db" storeType="binary" primaryKey="id" fields="id" dict="id,projId,title,description,owner,body">
                <get path="/json/ticket" xpipe="http://www.xmlpipe.org/xpe/db/unique/record/get" />
                <del path="/json/ticket/del" xpipe="http://www.xmlpipe.org/xpe/db/unique/record/del" />
                <post path="/json/tickets" xpipe="http://www.xmlpipe.org/xpe/db/unique/record/post" />
                <get path="/json/tickets" xpipe="http://www.xmlpipe.org/xpe/db/search" mask="id,projId,title,description,owner.body" />
            </service>
        </services>
```

Normally, services are grouped together when they are about the same representation so they can share the same configruations. In the example above, typical services associated with a ticket system are defined together.

Configs defined at the top level service

Tag references

            Tag
            Description

            async
            asynchronous service

            childMenu
            child menu

            combine
            combine scripts and css into one file

            common
            common sections for all pages

            content
            top level container

            default
            default template if no results are found

            get
            http get

            group
            group a block commonly used definitions to be reused by reference

            hide
            hide the page for any menu generations

            load
            load an external fragment into target

            metaInfo
            meta info about search results

            override
            overrides template fragment

            page
            defines a page

            post
            http post

            repeat
            repeating the included template

            resources
            static resources

            service
            defines a service

            services
            a collection of services

            siblingMenu
            sibling menu

            site
            site info

            webSocket
            define a web socket connection

            xlet
            defines an xlet

            xmlSample
            XML Samples, any XML fragment will be rendered in html


text:
# TrivialTestRunner

[![Build Status](https://dev.azure.com/ville0567/ville/_apis/build/status/vivainio.TrivialTestRunner?branchName=master)](https://dev.azure.com/ville0567/ville/_build/latest?definitionId=6&branchName=master)

[![NuGet](http://img.shields.io/nuget/v/TrivialTestRunner.svg)](https://www.nuget.org/packages/TrivialTestRunner/)

Dotnet Test Runner For The Rest Of Us (tm)

## Use case

- You have a small library with a modest set of tests.
- You don't care about "test explorer" or whatnot, but rather want to have a simple console application to run your tests.

- You are too stupid and/or lazy to understand everything the bigger test frameworks do under the hood

## Installation

https://www.nuget.org/packages/TrivialTestRunner/ - or add TrivialTestRunner.cs to your project

## Usage

In your test console application (where classes TestClass1 and TestClass2 contain the test methods):

```csharp
using TrivialTestRunner

static anync Task Main(string[] args)
{
    TRunner.AddTests<TestClass1>();
    TRunner.AddTests<TestClass2>();
    await TRunner.RunTestsAsync();
    // write results to console
    TRunner.ReportAll();
}
```

In your test classes:

```csharp
// normal case
[Case]
public static void Test1()
{
    Assert.IsTrue(true);
}

// normal non static case
[Case]
public void Test2()
{
    Assert.IsTrue(true);
}

// normal non static async case
[Case]
public async Task Test3()
{
    Assert.IsTrue(true);
    return await Task.CompletedTask;
}

// focused case
[fCase]
public static void Test3()
{
    Assert.IsTrue(true);
}

```

Note that one of the tests is "focused", i.e. fCase. If there are any focused tests in your set, only the focused tests will be run (yes, this means you don't need that "test explorer" to launch tests one by one)

If you want not to catch exceptions while running the tests (i.e. you want to trigger the debugger when it happens), do:

```csharp

// CrashHard will raise exception all the way
TRunner.CrashHard = true;
```

## License

MIT

repository: vivainio/TrivialTestRunner

repo_name: vivainio/TrivialTestRunner


text:
{# This content gets published to the following location: #}
{#   https://firebase.google.com/docs/flutter/setup       #}

* Install your preferred [editor or IDE](//flutter.io/get-started/editor/).

* Set up a device or emulator for running your app.
  [Emulators](https://developer.android.com/studio/run/managing-avds){: .external}
  must use an emulator image with Google Play.

* Make sure that your app meets the following requirements:

    * Targets API level {{android_min_api_level}} ({{android_min_api_codename}})
      or higher
    * Uses Android {{android_min_version}} or higher

* [Install Flutter](//flutter.io/get-started/install/) for your specific
  operating system, including the following:

    * Flutter SDK
    * Supporting libraries
    * Platform-specific software and SDKs

* [Sign into Firebase]({{name_appmanagerURL}}){: .external} using your Google
  account.

If you don't already have a Flutter app, you can complete the [Get
Started: Test Drive](//flutter.io/get-started/test-drive/#androidstudio) to
create a new Flutter app using your preferred editor or IDE.

repository: MilkBiscuit/flutterfire

gha_language: Dart

repo_name: MilkBiscuit/flutterfire


text:
---
title: TCPR - Getting Started
position: 1
---

TCPR is the standard way to administrate a KAG server remotely through TCP. Its usage is similar to that of RCON, accessed from the `/rcon` command in KAG's built-in console (home key).
Because of its nature, it's easy to use in nearly every language. This documentation will provide an example application in Python, but it is doable (with external libraries) in C++, Java, C#...

You can find an [(outdated) documentation of TCPR](https://wiki.kag2d.com/wiki/Remote_Administration) on the KAG Wiki.
KAG build [`1591`](https://forum.thd.vg/threads/kag-build-1591-maps-and-bombs.24220)(?) came up with overhauled TCPR with more capabilities (such as now being Windows-compatible) and build [`1865`](https://forum.thd.vg/threads/build-1865-engine-update-sponges-in-tdm-windows-modded-server-fixes.25483) came up with a TCPR maximal line size change.
{: .info }

`sv_tcpr` has to be set to `1` for TCPR to be enabled. Then, set `sv_rconpassword` to the password of your choice (which can be used both to login with TCPR and over RCON).
The `50301` port has to be forwarded for TCP (whereas the game itself uses UDP over `50301` as well) to connect from another machine.


text:
# Change log

## 1.0.0
* Initial release

## 1.0.1
* The meta model can be created from different annotation processors

## 1.0.2
* added support for com.mysema.query.apt.QuerydslAnnotationProcessor

## 1.0.3
* Internal refactoring, only one task `QuerydslCompile` is added to the project that configures all annotation processors

## 1.0.4
* Plugin portal release process changed
* Support for `providedCompile` and `providedRuntime` dependencies

## 1.0.5
* Gradle 2.6 compatibility

## 1.0.6
* Querydsl 4 library dependency is now required for this plugin.
* Querydsl 4 is required for SpringData "Hopper" JPA generation.

## 1.0.7
* Bugfix (issue #51) for compileQuerydsl task, Java compiler setting of destinationDir, must evaluate user's querydslSourcesDir preference.

## 1.0.8
* Querydsl 4 library dependency updated to (4.1.3) matching Spring Data version
* Gradle 3.3 compatibility

## 1.0.9
* Set JDK-8 as default

## 1.0.10-SNAPSHOT
* Querydsl 4 library dependency updated to (4.1.4)
* Add support for custom `aptOptions` parameter

## 1.0.11-SNAPSHOT
* Current plugin snapshot

repository: ewerk/gradle-plugins

gha_language: Groovy

repo_name: ewerk/gradle-plugins


text:
1630\. Arithmetic Subarrays

Medium

A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] == s[1] - s[0]` for all valid `i`.

For example, these are **arithmetic** sequences:

1, 3, 5, 7, 9 7, 7, 7, 7 3, -1, -5, -9

The following sequence is not **arithmetic**:

1, 1, 2, 5, 7

You are given an array of `n` integers, `nums`, and two arrays of `m` integers each, `l` and `r`, representing the `m` range queries, where the ith query is the range `[l[i], r[i]]`. All the arrays are **0-indexed**.

Return _a list of_ `boolean` _elements_ `answer`_, where_ `answer[i]` _is_ `true` _if the subarray_ `nums[l[i]], nums[l[i]+1], ... , nums[r[i]]` _can be **rearranged** to form an **arithmetic** sequence, and_ `false` _otherwise._

**Example 1:**

**Input:** nums = `[4,6,5,9,3,7]`, l = `[0,0,2]`, r = `[2,3,5]`

**Output:** `[true,false,true]`

**Explanation:**

In the 0th query, the subarray is [4,6,5].

This can be rearranged as [6,5,4], which is an arithmetic sequence.

In the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence.

In the 2nd query, the subarray is `[5,9,3,7]. This` can be rearranged as `[3,5,7,9]`, which is an arithmetic sequence.

**Example 2:**

**Input:** nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]

**Output:** [false,true,false,false,true,true]

**Constraints:**

*   `n == nums.length`
*   `m == l.length`
*   `m == r.length`
*   `2 <= n <= 500`
*   `1 <= m <= 500`
*   `0 <= l[i] < r[i] < n`
*   -105 <= nums[i] <= 105

repository: javadev/LeetCode-in-Java

gha_language: Java

repo_name: javadev/LeetCode-in-Java


text:
---
layout: post
comments: true
title: "Unintended Consequences"
date: 2007-08-11 00:00
categories: [computers, software, mac os x]
---

This is the story of an unintended interference between two
UI-aware applications. This kind of unexpected interaction happens
a lot with software.

<!-- more -->

The computer I use at home is a 17" [MacBook Pro][]. The machine's less
than a year old, and yesterday, the display started [acting funny][]. The
display began to look more and more harsh and washed out. By the end of the
day, a typical window looked like this:

![bad Finder display](/images/finder-bad.png)

instead of how it should look:

![good Finder display](/images/finder-good.png)

I was having increasing difficulty reading my email, looking at the
calendar entries in iCal, or doing much of anything. The [photos][] I use
as my background were also looking very unappealing.

"Great," I thought. "A problem with the LCD."

Luckily, the machine is less than a year old, so it's still under
hardware warranty. But I wasn't looking forward to the hassle of
getting it repaired.

Then, I logged out. When the login screen appeared, the display
looked normal again. I logged back in. Initially, the display
looked fine, but then it "went bad" again partway through the login
process.

I created a new account, then logged out of my account and into the
new one. The display looked perfectly normal. I logged out and
logged back into my account again. Once again, partway during the
login, the display went south.

Okay, it clearly was not a hardware failure; there was something peculiar
to my account that was causing the problem. I logged out again. From a
remote [SSH][] window on another machine, I moved all the files out of my
home directory. Then, I logged into the laptop again. Everything looked
perfectly fine. So, I began the tedious process of logging out, restoring a
directory, logging back in, logging out, restoring a directory, logging
back in ...

It didn't take long. As soon as I restored my
`Applications/Preferences` directory, the problem came back.

After digging through the files in that directory (starting with
the most recently modified ones), I finally found a likely
culprit:

    $ cd ~/Library/Preferences
    $ plutil -convert xml1 -o /tmp/foo.xml com.apple.universalaccess.plist
    $ cat /tmp/foo.xml

The constants of that file:

{% codeblock com.apple.universalaccess.plist lang:xml %}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
          "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>PID</key>
        <integer>6282</integer>
        <key>UserAssignableHotKeys</key>
        <array>
                <dict>
                        <key>enabled</key>
                        <true/>
                        <key>key</key>
                        <integer>99</integer>
                        <key>modifier</key>
                        <integer>0</integer>
                        <key>sybmolichotkey</key>
                        <integer>64</integer>
                </dict>
                <dict>
                        <key>enabled</key>
                        <true/>
                        <key>key</key>
                        <integer>49</integer>
                        <key>modifier</key>
                        <integer>1572864</integer>
                        <key>sybmolichotkey</key>
                        <integer>65</integer>
                </dict>
        </array>
        <key>closeViewDriverMouseZoomSwitch</key>
        <true/>
        <key>closeViewScrollWheelToggle</key>
        <true/>
        <key>contrast</key>
        <real>0.30812768</real>
</dict>
</plist>
{% endcodeblock %}

The culprit:

{% codeblock lang:xml %}
<key>contrast</key>
<real>0.30812768</real>
{% endcodeblock %}

I removed the `contrast` keyword and value and recreated the binary file:

{% codeblock lang:shell %}
$ plutil -convert binary1 -o com.apple.universalaccess.plist /tmp/foo.xml
{% endcodeblock %}

After logging out and logging back in, everything was perfect
again.

But how did the Universal Access contrast value suddenly get set? I
decided to look at the Universal Access preferences screen, in the
System Preferences application:

![Universal Access](/images/universal-access.png)

Looking at that screen, I knew immediately what had happened. As the
Universal Access Preference screen clearly shows, the default keyboard
shortcut for boosting the screen contrast is
Command-Option-Control-*period*. I'd been typing that key sequence. Why?
Well, I recently installed [Quicksilver][], the [Leatherman][] of Mac OS X
applications. Using Quicksilver's iTunes plug-in, I'd created keyboard
shortcuts so I could increase and decrease the iTunes volume settings, skip
to the next or previous song, and pause and resume iTunes without having to
switch to the iTunes window. I often pause whatever I'm playing on iTunes
when I pick up the phone, and that day had been a fairly busy phone day;
it's extraordinarily convenient and efficient to pause and resume iTunes
from the keyboard. The keyboard shortcut I'd chosen for the pause/resume
action was Command-Option-Control-*period*, chosen *deliberately* so that
it wouldn't interfere with Emacs keys, the hot keys in my [Java IDE][], and
other applications. Little did I know that I'd chosen the exact same key
sequence used by the Mac OS X Universal Access system to **increase the
screen contrast.**

A little experimentation showed that unchecking the "Enable access
for assistive devices" checkbox had no effect on this feature; even
with that checkbox unchecked, the Command-Option-Control-*period*
shortcut still increased the screen contrast. I didn't want to
change my iTunes shortcut, because it's a key sequence I'm not
likely to hit by accident. (I'm sure that's why it was also chosen
for Universal Access's "Increase contrast" function.) To fix the
problem, I had to disable the corresponding Universal Access
keyboard shortcut entirely, via System Preferences > Keyboard
and Mouse > Keyboard Shortcuts. For good measure, I disabled
*all* the Universal Access keyboard shortcuts:

![Universal Access keyboard shortcuts](/images/keyboard-shortcuts.png)

Maybe this blog entry will save someone else some time...

[MacBook Pro]: http://www.apple.com/macbookpro/
[acting funny]: http://books.google.com/books?id=BzRfkR51i60C&dq=%22acting+funny%22&printsec=frontcover&source=web&ots=BGoE6aSChA&sig=jgdJrGfy87AYu5kkU8mDNrdTyYQ
[photos]: http://www.clapper.org/bmc/photography/gallery/
[SSH]: http://www.openssh.org/
[Quicksilver]: http://quicksilver.blacktree.com/
[Leatherman]: http://www.leatherman.com/
[Java IDE]: http://www.netbeans.org/

repository: bmc/brizzled

repo_name: bmc/brizzled


text:
---
layout: post
title: 'Go语言汇编器的设计'
subtitle: 'Rob Pike在开发者大会上的演讲'
date: 2019-07-22
categories: 技术
cover: ''
tags: Golang
---

这篇博文来自视频 [GopherCon 2016: Rob Pike - The Design of the Go Assembler](https://www.youtube.com/watch?v=KINIAgRpkDA) 里，Rob Pike 关于 Go 汇编器的讲述，记录部分我认为比较重要的文字。下面视频来自 youtube:

> The most important single thing to realize about assembler language is that it enables the programmer to use all System/360 machine functions as if he were coding in System/360 machine language. - A programmer's Intruduction to IBM System/360 Assembler Language, 1970

> The assembler is how you talk to the machine at very lowest level.

> CPUs look pretty much the same nowadays, most of them(certainly all the ones that go runs on) are pretty much the same if you ignore a lot of detail. We can construct a common grammer for all of these machines.

接着 Rob 介绍了 plan 9 上的 C compiler。

> The plan 9 C compiler didn't actually generate real instructions, it generated what you might think of as pseudo-code. Then the second program that run on the output of the compiler which is the linker actually turned those pseudo instructions into real instructions.

可见在 plan 9 上，没有 assembler 这个概念。Compiler 输出伪码到 linker，如果写一句如下伪码:

```
MOVW $0, var
```

plan 9 上的 linker 可能会将上面的伪码翻译成下面这样:

```
XORW  R1, R1
STORE R1, var
```

这个过程称为 [Instrction selection](https://en.wikipedia.org/wiki/Instruction_selection)。

![](http://ww1.sinaimg.cn/large/c9caade4gy1g58juhzonlj21840k6q7q.jpg)

> The top line is the sort of tranditioal architecture, like GCC runs. The bottom two are what the plan 9 architecture look like. The assembler was cut half and the first part of the assembler got stuck into the compiler and the second part of the assembler went into the linker, what flowing across the red line is kind of binary represtation of the pseudo instructions.

> All the assembler is doing in plan 9 world is giving a way to write textual version of instruction that drive the linker.

> The plan 9 world has a compiler drive the linker or the assembler drive the linker.

> In Go1.3, Russ took a big chunk of linker and pulled it out, and make it a library called "liblink", a big piece of which was what we called [Instrction selection](https://en.wikipedia.org/wiki/Instruction_selection) algorithm.

现在 liblink 这个库改名为 [obj](https://golang.org/pkg/cmd/internal/obj/#pkg-overview)。

> The compiler use liblink to generate the real instruction from the pseudo instruction.

将原本 linker 做的事转移到 compiler 中了，这样做加快了 build 的速度(因为compiler承担了更多的工作)。

> The compiler slows down but the builds actually sped up.

由于 instruction selection 的重新设计，整个流程变成了这样:

![](http://ww1.sinaimg.cn/large/c9caade4gy1g58ku3q9xij21840k6afj.jpg)

> After Go1.5, the many compiler(6g, 8g etc.) were replaced with a single tool: compile.

url: https://raw.githubusercontent.com/drivebyer/old-blog-theme/199b9cf8a7bfdfa4dd1a3db741858bd42e2c3f55/_posts/2019-07-22-The Design of the Go Assembler.md

repository: drivebyer/old-blog-theme

gha_language: CSS

repo_name: drivebyer/old-blog-theme


text:
---
layout: page
title: Adaptive Playing & Opponent Modeling in Competitive Games
description:
img: assets/img/Adaptive_Playing_and_Opponent_Modeling/board_configuration.png
importance: 1
category: work
---
Link to the code

 Abstract

>Despite the success of Artificial Intelligence systems such as Deep Blue, AlphaGo and OpenAI five, most modern commercial videogames still rely on the use of scripts. This is mainly because developers are concerned about the unpredictable behavior of AI.
>
>The ability to create a balanced matching between the user's skills and the level of difficulty of the game can greatly improve the user's gaming experience.
>
>Previous attempts at achieving this goal have required a large amount of data from human matches or specific knowledge related to the game.
>
>In our work, we have proposed a new method that allows us to eliminate the demand for data from games between human players and to decrease the amount of specific knowledge related to the game needed.

 Train and Store

            In this section we train an

            agent through

            reinforcement learning and

            self-play tecniques.

            During this phase we

            evaluate the agent and

            store some of its best

            policies for the next step.

        {% include figure.html path="assets/img/Adaptive_Playing_and_Opponent_Modeling/Algorithm1_v2.jpg" title="example image" class="img-fluid rounded z-depth-1" %}

        {% include figure.html path="assets/img/Adaptive_Playing_and_Opponent_Modeling/Learning_Behaviour.jpg" title="example image" class="img-fluid rounded z-depth-1" %}

 Adaptive Playing

            We use the previously stored

            policies to create a dataset

            of matches between agents

            using these policies.

            We train a model to recognize

            the level of the agents by

            looking at their sequence of moves.

 Adaptive Playing

            We use the previously stored

            policies to create a dataset

            of matches between agents

            using these policies.

            We train a model to recognize

            the level of the agents by

            looking at their sequence of moves.


text:
---
layout: post
title: Gitlab CLI dengan GLAB
modified: 2023-01-18T17:00:28+07:00
categories:
description: "Gitlab CLI dengan GLAB"
tags: [gitlab, cli, glab, gitlab cli, git cli]
image:
  background: triangular.png
comments: true
share: true
date: 2023-01-18T17:00:28+07:00
---

![GLab](https://gitlab.com/gitlab-org/cli/-/raw/main/docs/assets/glab-logo.png)

[![Go Report Card](https://goreportcard.com/badge/gitlab.com/gitlab-org/cli)](https://goreportcard.com/report/gitlab.com/gitlab-org/cli)
![Coverage](https://gitlab.com/gitlab-org/cli/badges/main/coverage.svg)
[![Mentioned in Awesome Go](https://awesome.re/mentioned-badge.svg)](https://github.com/avelino/awesome-go#version-control)
[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?style=flat&logo=gitpod&logoColor=white)](https://gitpod.io/#https://gitlab.com/gitlab-org/cli/-/tree/main/)

GLab is an open source GitLab CLI tool bringing GitLab to your terminal next to where you are already working with `git` and your code without switching between windows and browser tabs. Work with issues, merge requests, **watch running pipelines directly from your CLI** among other features.

`glab` is available for repositories hosted on GitLab.com and self-managed GitLab instances. `glab` supports multiple authenticated GitLab instances and automatically detects the authenticated hostname from the remotes available in the working Git directory.

![command example](https://gitlab.com/gitlab-org/cli/-/raw/main/docs/assets/glabgettingstarted.gif)

## Table of contents

- [Table of contents](#table-of-contents)
- [Usage](#usage)
- [Demo](#demo)
- [Documentation](#documentation)
- [Installation](#installation)
  - [macOS](#macos)
  - [Windows](#windows)
  - [Linux](#linux)
    - [Homebrew](#homebrew)
    - [Snapcraft (out of date)](#snapcraft-out-of-date)
    - [Arch Linux](#arch-linux)
    - [Alpine Linux](#alpine-linux)
      - [Install a pinned version from edge](#install-a-pinned-version-from-edge)
      - [Alpine Linux Docker-way](#alpine-linux-docker-way)
    - [Nix/NixOS](#nixnixos)
    - [MPR (Debian/Ubuntu)](#mpr-debianubuntu)
      - [Prebuilt-MPR](#prebuilt-mpr)
    - [Spack](#spack)
  - [Building from source](#building-from-source)
    - [Prerequisites for building from source](#prerequisites-for-building-from-source)
- [Authentication](#authentication)
- [Configuration](#configuration)
- [Environment variables](#environment-variables)
- [Issues](#issues)
- [Contributing](#contributing)

## Usage

To get started with `glab`:

1. Follow the [installation instructions](#installation) appropriate for your operating system.
1. [Authenticate](#authentication) into your instance of GitLab.
1. Optional. Configure `glab` further to meet your needs:
   - Set any needed global, per-project, or per-host [configuration](#configuration).
   - Set any needed [environment variables](#environment-variables).

You're ready! Run `glab --help` to view a list of core commands. Commands follow this pattern:

```shell
glab <command> <subcommand> [flags]
```

Many core commands also have sub-commands. Some examples:

- List merge requests assigned to you: `glab mr list --assignee=@me`
- List review requests for you: `glab mr list --reviewer=@me`
- Approve a merge request: `glab mr approve 235`
- Create an issue, and add milestone, title, and label: `glab issue create -m release-2.0.0 -t "My title here" --label important`

## Demo

[![asciicast](https://asciinema.org/a/368622.svg)](https://asciinema.org/a/368622)

## Documentation

Read the [documentation](https://gitlab.com/gitlab-org/cli/-/tree/main/docs/source) for usage instructions or check out `glab help`.

## Installation

Download a binary suitable for your OS at the [releases page](https://gitlab.com/gitlab-org/cli/-/releases).
Other installation methods depend on your operating system.

### macOS

- Homebrew (officially supported)
  - Install with: `brew install glab`
  - Update with: `brew upgrade glab`
- [MacPorts](https://ports.macports.org/port/glab/summary):
  - Install with: `sudo port install glab`
  - Update with: `sudo port selfupdate && sudo port upgrade glab`
- Install into `usr/bin` with a shell script:
  `curl -s "https://gitlab.com/gitlab-org/cli/-/raw/main/scripts/install.sh" | sudo sh`

  Before running any install script, review its contents.

### Windows

- [WinGet](https://github.com/microsoft/winget-cli)
  - Install with: `winget install glab.glab`
  - Update with: `winget install glab.glab`
- [scoop](https://scoop.sh)
  - Install with: `scoop install glab`
  - Update with: `scoop update glab`
- Download an EXE installer or the `glab.exe` binary from the [releases page](https://gitlab.com/gitlab-org/cli/-/releases)

### Linux

- Download prebuilt binaries from the [releases page](https://gitlab.com/gitlab-org/cli/-/releases)

#### Homebrew

Installing from Homebrew is the officially supported installation method for Linux.

- Install with: `brew install glab`
- Update with: `brew upgrade glab`

#### Snapcraft ([out of date](https://gitlab.com/gitlab-org/cli/-/issues/1127))

To install `glab` from the [Snap Store](https://snapcraft.io/glab):

1. Make sure you have [snap installed](https://snapcraft.io/docs/installing-snapd) on your Linux distribution.
1. Install the package: `sudo snap install --edge glab`
1. Grant `glab` access to SSH keys: `sudo snap connect glab:ssh-keys`

[![Download from the Snap Store](https://snapcraft.io/static/images/badges/en/snap-store-black.svg)](https://snapcraft.io/glab)

#### Arch Linux

For Arch Linux, `glab` is available:

- From the [`community/glab`](https://archlinux.org/packages/community/x86_64/glab/) package.
- By downloading and installing an archive from the
  [releases page](https://gitlab.com/gitlab-org/cli/-/releases).
- From the [Snap Store](https://snapcraft.io/glab), if
  [snap](https://snapcraft.io/docs/installing-snap-on-arch-linux) is installed.
- Installing with the package manager: `pacman -S glab`

#### Alpine Linux

`glab` is available on the [Alpine Community Repository](https://git.alpinelinux.org/aports/tree/community/glab?h=master) as `glab`.

When installing, use `--no-cache` so no `apk update` is required:

```shell
apk add --no-cache glab
```

##### Install a pinned version from edge

To ensure that by default edge is used to get the latest updates. We need the edge repository in `/etc/apk/repositories`.

Afterwards you can install it with `apk add --no-cache glab@edge`

We use `--no-cache` so an `apk update` is not required.

```shell
echo "@edge http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories
apk add --no-cache glab@edge
```

##### Alpine Linux Docker-way

Use edge directly

```shell
FROM alpine:3.13
RUN apk add --no-cache glab
```

Fetching latest glab version from edge

```shell
FROM alpine:3.13
RUN echo "@edge http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories
RUN apk add --no-cache glab@edge
```

#### Nix/NixOS

Nix (NixOS) users can install from [nixpkgs](https://search.nixos.org/packages?channel=unstable&show=glab&from=0&size=30&sort=relevance&query=glab) with the command `nix-env -iA nixos.glab`.

#### MPR (Debian/Ubuntu)

`glab` is available inside the [makedeb package repository](https://mpr.makedeb.org/packages/glab). To install, run the following:

```shell
git clone 'https://mpr.makedeb.org/glab'
cd glab/
makedeb -si
```

##### Prebuilt-MPR

The above method downloads glab from source and builds it before packaging it into a `.deb` package. If you don't want to compile or just want a prebuilt package, you can also install glab from the Prebuilt-MPR:

1. Set up [the Prebuilt-MPR on your system](https://docs.makedeb.org/prebuilt-mpr/getting-started/#setting-up-the-repository).
1. Install with the command `sudo apt install glab`.

#### Spack

- To install: `spack install glab`.
- To update: `spack uninstall glab && spack install glab`

### Building from source

If a supported binary for your OS is not found at the [releases page](https://gitlab.com/gitlab-org/cli/-/releases), you can build from source:

#### Prerequisites for building from source

- `make`
- Go 1.18+

To build from source:

1. Run the command `go version` to verify that Go version 1.18 or later is installed.
   If `go` is not installed, follow instructions on [the Go website](https://go.dev/doc/install).
1. Clone this repository: `git clone https://gitlab.com/gitlab-org/cli.git glab`
1. Change into the project directory: `cd glab`
1. If you have `$GOPATH/bin` or `$GOBIN` in your `$PATH`, run `make install` to install in `$GOPATH/bin`).
1. If you do not have `$GOPATH/bin` or `$GOBIN` in your `$PATH`:
   1. Run `make` to build the project.
   1. Run `export PATH=$PWD/bin:$PATH` to update your PATH with the newly compiled project.
1. Run `glab version` to confirm that it worked.

## Authentication

To authenticate your installation of `glab`:

1. Get a GitLab personal access token with at least the `api`
   and `write_repository` scopes. Use the method appropriate for your instance:
   - For GitLab.com, create one at the [Personal access tokens](https://gitlab.com/-/profile/personal_access_tokens) page.
   - For self-managed instances, visit `https://gitlab.example.com/-/profile/personal_access_tokens`,
     modifying `gitlab.example.com` to match the domain name of your instance.
1. Start interactive setup: `glab auth login`
1. Authenticate with the method appropriate for your GitLab instance:
   - For GitLab SaaS, authenticate against `gitlab.com` by reading the token
     from a file: `glab auth login --stdin < myaccesstoken.txt`
   - For self-managed instances, authenticate by reading from a file:
     `glab auth login --hostname salsa.debian.org --stdin < myaccesstoken.txt`
   - Authenticate with token and hostname: `glab auth login --hostname gitlab.example.org --token xxxxx`
     Not recommended for shared environments.

## Configuration

By default, `glab` follows the
[XDG Base Directory Spec](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html).
Configure it globally, locally, or per-host:

- **Globally**: run `glab config set --global editor vim`.
  - The global configuration file is available at `~/.config/glab-cli`.
  - To override this location, set the `GLAB_CONFIG_DIR` environment variable.
- **The current directory**: run `glab config set editor vim` in any folder in a Git repository.
  - The local configuration file is available at `.git/glab-cli` in the current working Git directory.
- **Per host**: run `glab config set editor vim --host gitlab.example.org`, changing
  the `--host` parameter to meet your needs.
  - Per-host configuration info is always stored in the global configuration file, with or without the `global` flag.

## Environment variables

- `GITLAB_TOKEN`: an authentication token for API requests. Setting this avoids being
  prompted to authenticate and overrides any previously stored credentials.
  Can be set in the config with `glab config set token xxxxxx`
- `GITLAB_URI` or `GITLAB_HOST`: specify the URL of the GitLab server if self-managed (eg: `https://gitlab.example.com`). Default is `https://gitlab.com`.
- `GITLAB_API_HOST`: specify the host where the API endpoint is found. Useful when there are separate (sub)domains or hosts for Git and the API endpoint: defaults to the hostname found in the Git URL
- `GITLAB_REPO`: Default GitLab repository used for commands accepting the `--repo` option. Only used if no `--repo` option is given.
- `GITLAB_GROUP`: Default GitLab group used for listing merge requests, issues and variables. Only used if no `--group` option is given.
- `REMOTE_ALIAS` or `GIT_REMOTE_URL_VAR`: `git remote` variable or alias that contains the GitLab URL.
  Can be set in the config with `glab config set remote_alias origin`
- `VISUAL`, `EDITOR` (in order of precedence): the editor tool to use for authoring text.
  Can be set in the config with `glab config set editor vim`
- `BROWSER`: the web browser to use for opening links.
   Can be set in the configuration with `glab config set browser mybrowser`
- `GLAMOUR_STYLE`: environment variable to set your desired Markdown renderer style
  Available options are (`dark`|`light`|`notty`) or set a [custom style](https://github.com/charmbracelet/glamour#styles)
- `NO_COLOR`: set to any value to avoid printing ANSI escape sequences for color output.
- `FORCE_HYPERLINKS`: set to `1` to force hyperlinks to be output, even when not outputting to a TTY

---
stage: Create
group: Code Review
info: To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/product/ux/technical-writing/#assignments
---

# GitLab CLI - `glab`

GLab is an open source GitLab CLI tool. It brings GitLab to your terminal:
next to where you are already working with Git and your code, without
switching between windows and browser tabs.

- Work with issues.
- Work with merge requests.
- Watch running pipelines directly from your CLI.

![command example](https://gitlab.com/gitlab-org/cli/-/raw/main/docs/assets/command-example.png)

The GitLab CLI uses commands structured like `glab <command> <subcommand> [flags]`
to perform many of the actions you normally do from the GitLab user interface:

```shell
# Sign in
glab auth login --stdin < token.txt

# View a list of issues
glab issue list

# Create merge request for issue 123
glab mr for 123

# Check out the branch for merge request 243
glab mr checkout 243

# Watch the pipeline in progress
glab pipeline ci view

# View, approve, and merge the merge request
glab mr view
glab mr approve
glab mr merge
```

## Core commands

- `glab alias`
- `glab api`
- `glab auth`
- `glab ci`
- `glab issue`
- `glab label`
- `glab mr`
- `glab project`
- `glab release`
- `glab snippet`
- `glab ssh-key`
- `glab user`
- `glab variable`

## Install the CLI

Installation instructions are available in the GLab
[`README`](https://gitlab.com/gitlab-org/cli/#installation).

## Authenticate with GitLab

To authenticate with your GitLab account, run `glab auth login`.
`glab` respects tokens set using `GITLAB_TOKEN`.

## Report issues

Open an issue in the [`gitlab-org/cli` repository](https://gitlab.com/gitlab-org/cli/issues/new)
to send us feedback.

## Related topics

- [Install the CLI](https://gitlab.com/gitlab-org/cli/-/blob/main/README.md#installation)
- [Documentation](https://gitlab.com/gitlab-org/cli/-/tree/main/docs/source)
- The extension source code is available in the
  [`cli`](https://gitlab.com/gitlab-org/cli/) project.

## Clone With Gitlab Self Hosted (PoC)
- glab auth login
- select self hosted
- using https method and your token access
- use the command below

{% highlight bash %}
GITLAB_HOST=GITLAB_SELF_HOSTED glab repo clone groupname/path/project_name
GITLAB_HOST=GITLAB_SELF_HOSTED glab repo clone yourgitlabname/project_name
- Clone by group subdir with namespace
GITLAB_HOST=GITLAB_SELF_HOSTED glab repo clone -g groupname/subdir -paginate
- Clone all by group name with namespace
GITLAB_HOST=GITLAB_SELF_HOSTED glab repo clone -g groupname -p
- Cloner all and subdir by group name with namespace
GITLAB_HOST=GITLAB_SELF_HOSTED glab repo clone -g groupname/subdir/pathname -p
{% endhighlight %}

Refferences :
- Install: https://gitlab.com/gitlab-org/cli/#installation
- CLI : https://gitlab.com/gitlab-org/cli/-/blob/main/docs/source/repo/clone.md
- Demo : https://asciinema.org/a/368622