text:
# Network Project
[![Build Status](https://travis-ci.org/dingding2018/Networks.svg?branch=master)](https://travis-ci.org/dingding2018/Networks)

# About
This repo is for the project of Network class.
The website is built using Python, Flask and mySQL.

# Website Fuctions (for the moment)
- User registration/login/logout
- Post a topic
- Comment on a topic
- Search by keyword
- Automated underwriting demo
- Browser info about insurance

# How to run the codes in your local PC
1. Required installations
- Python 2.7
- Flask
- SQLAlchemy
- PyMySQL
- Flask-Migrate
- Virtualenv
- Pycharm (optional)
- Gitbash: https://git-scm.com/download

2. Download the repo from github and run
```shell
git clone https://github.com/dingding2018/Networks.git
cd File/
python auw_demo.py
```
Go to the brower and input:
http://<IP_ADDRESS>:5000 or localhost:5000
The webpage should be running.

3. Database
Since the service is running on local, you still need to make sure the database is available on your local PC.

(1) Setup (please do it under virtual flask env)
```shell
cd File/
python manage.py db init
python manage.py db migrate
python manage.py db upgrade
```
(2) Open mySQL command line
- Input the password "root" to enter the database
- SQL command lines to check the tables in database
```shell
CREATE DATABASE test_demo;
use test_demo;
show tables;
desc user; (check the columns in table "user")
select * from user; (check the information stored in the table "user")
```

gha_language: HTML


text:
## Description

Plexus aims to be a one stop solution for all kinds of digital events like Quizes. It specially targets the yearly online events happening in our college. This platform will allow other societies to host their events without any friction or technical know-how.

[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)

## To Setup the Project for Development -

 A. Setting Up the server -
   1. Install heroku-cli with `npm i -g heroku-cli`.
   2. Install nodemon with `npm i -g nodemon`.
   3. Run `npm i` to install the server-side dependencies.
   4. Run `cp .env.example .env` to create `.env` file, open it and fill the credentials.

 B. Setting Up the client -
   1. Run `cd client ` in separate terminal to change into client directory.
   2. In client directory run `npm i` to install client-side dependencies.
   3. In client directory run `touch .env`.

## To Start Local Server -

 1. Run `npm start` to start backend server.
 2. Run `npm run client` to start frontend server.
 3. Run `npm run test:watch` to start the test watchers to test if something breaks.
 4. Navigate to [http://localhost:3000](http://localhost:3000) in the browser.

## Guidelines
 1. First make an issue and then start working on it.
 2. Always make a separate branch in following format name-patch-#issueNo. Eg: aditya-patch-#62. (Words are separated by -).
 3. In the commit message do mention the issue no. Eg: fixes #1.
 4. Use proper code formatting. Run `npm run format` to make prettier format everything automagically.
 5. Run `npm test` to check if nothing has broken.
 6. Do mention if `npm install` is needed after merging the commit.

Note -
1. Heroku Cli is used for handling **environment variables** and deploys.
2. To get **googleClientID** and **googleClientSecret** make a new project at [here](https://console.developers.google.com) and enable the Google+ api.
3. To get **facebookAppId** and **facebookAppSecret** make a new app at [here](https://developers.facebook.com) and add the facebook login product.
4. If you don't have **mongodb** locally, then create a remote db [here](https://mlab.com/home) or you can download it from [here](https://www.mongodb.com/download-center?jmp=docs&_ga=2.47151591.1318332256.1507577170-1071278786.1507217039#community)
5. Whenever you commit the code. Prettier runs and it formats the code. If any changes are made then do stage again and commit.

## Technology Stack

 * Create-React-App (**CRA**)
 * Webpack
 * React
 * Redux
 * Node
 * Express
 * Mongodb / Mongoose
 * Tape
 * Prettier
 * Heroku

## Project Maintainers

 * [Ankit Jain](https://github.com/ankitjain28may)
 * [Aditya Agarwal](https://github.com/itaditya)

## Other Contributors

 * [Kunal Vishnoi](https://github.com/kunalvishnoi)
 * [Shubham Singh](https://github.com/ShubhMisaki)
 * [Rohit Chandra](https://github.com/krrohitch)

license: MIT

branch_name: refs/heads/master

extension: md

gha_language: JavaScript

gha_license_id: MIT

license_type: permissive


text:
# git

Git CLI [docs](https://git-scm.com/docs/git)

## Reset, restore and revert

> There are three commands with similar names: git reset, git restore and git revert.

> git-revert[1] is about making a new commit that reverts the changes made by other commits.

> git-restore[1] is about restoring files in the working tree from either the index or another commit. This command does not update your branch. The command can also be used to restore files in the index from another commit.

> git-reset[1] is about updating your branch, moving the tip in order to add or remove commits from the branch. This operation changes the commit history.

repository: korenmiklos/dev-cheatsheets

repo_name: korenmiklos/dev-cheatsheets


text:
# ALWebViewController 🌐

[![Version](https://img.shields.io/cocoapods/v/ALWebViewController.svg?style=flat)](https://cocoapods.org/pods/ALWebViewController)
[![License](https://img.shields.io/cocoapods/l/ALWebViewController.svg?style=flat)](https://cocoapods.org/pods/ALWebViewController)
[![Platform](https://img.shields.io/cocoapods/p/ALWebViewController.svg?style=flat)](https://cocoapods.org/pods/ALWebViewController)
[![Language](https://img.shields.io/badge/swift-5-orange.svg)](http://swift.org)

## Installation

### CocoaPods
**ALWebViewController** is available through [CocoaPods](https://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod 'ALWebViewController'
```

### Swift Package Manager
From Xcode 11, you can use Swift Package Manager to add ALWebViewController to your project.

1. Select File > Swift Packages > Add Package Dependency. Enter https://github.com/applogistdev/ALWebViewController.git in the "Choose Package Repository" dialog.
2. In the next page, specify the version resolving rule as "Up to Next Major" with "0.2.1" as its earliest version.
3. After Xcode checking out the source and resolving the version, you can choose the "ALWebViewController" library and add it to your app target.

## Usage

```swift
import ALWebViewController

// URL Example
let url = URL(string: "https://www.google.com")!
let urlType = ALWebContentType.url(url: url)
let webVC = ALWebViewController(content: type)
navigationController?.pushViewController(webVC, animated: true)

// Html String Example
var html = "<html><body><h1> Title </h1></body></html>"
let htmlType = ALWebContentType.html(html: html
let webVC = ALWebViewController(content: htmlType)
navigationController?.pushViewController(webVC, animated: true)

// ALWebViewDelegate

extension ViewController: ALWebViewDelegate {
    func webView(didStartLoading webVC: ALWebViewController) {
        debugPrint("Start Loading")
    }

    func webView(didFinishLoading webVC: ALWebViewController) {
        debugPrint("Finish Loading")
    }
}

```

## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

## Author

Soner Güler<EMAIL_ADDRESS>Ünal Çelik<EMAIL_ADDRESS>
## License

ALWebViewController is available under the MIT license. See the LICENSE file for more info.

repository: applogistdev/ALWebViewController

gha_language: Swift

repo_name: applogistdev/ALWebViewController


text:
# OSS Notice #

This application is Copyright © Kakao Enterprise Corp. All rights reserved.

The following sets forth attribution notices for third party software that may be contained in this application.

If you have any questions or concerns, please contact us at [tsp<EMAIL_ADDRESS>
 **jekyll**

https://jekyllrb.com

Copyright (c) 2008-present Tom Preston-Werner and Jekyll contributors

MIT License

 **jekyll-footnotes**

https://github.com/orangejulius/jekyll-footnotes

© Ben Eills, 2013 © Julian Simioni, 2015

MIT License

# MIT License #

``````````
MIT License

Copyright (c) <year> <copyright holders>

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

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

 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
``````````

<EMAIL_ADDRESS><EMAIL_ADDRESS><!-- Hermes : Legal Notice successful Generated -->


text:
[![](https://vsmarketplacebadge.apphb.com/version/tcneuen.blamer-vs.svg)](https://marketplace.visualstudio.com/items?itemName=tcneuen.blamer-vs)
[![](https://vsmarketplacebadge.apphb.com/installs/tcneuen.blamer-vs.svg)](https://marketplace.visualstudio.com/items?itemName=tcneuen.blamer-vs)

# SVN Gutter (fork/tcneuen)

This is the Visual Studio Code version of the [Blamer](https://github.com/BeauAgst/Blamer) plugin, built for Sublime Text and a published fork of the [original from BeauAgst](https://github.com/BeauAgst/blamer-vs) due to inactivity.

[Pull requests are always welcome!](https://github.com/tcneuen/blamer-vs/issues/)

## Commands:

This extension contributes the following commands to the Command palette.

`SVN Gutter - Show Blame`: Adds icons to gutter with tooltips containing information from each revision

`SVN Gutter - Clear Blame`: Clears icons and tooltips

## Shortcuts:

Currently only a single keyboard shortcut is available.

**SVN Gutter - Show Blame**
`CTRL + ALT + D` (Windows)
`CTRL + CMD + X` (Mac)

## Features

When run, this extension will place an icon next to each line of your file. Each differently-coloured icon means a different revision. Hovering a line will produce a tooltip, showing the committer, date, and message.

For example if you're working on a project and you want to see who modified a specific line:

![Example Usage](example.gif)

## Requirements

This extension requires that you're either:

- On a Windows machine with Tortoise SVN installed, with command-line tools.
- A Unix machine.

## Extension Settings

**Enable Detail** - By default, the extension get detailed log information for each unique revisions. Disabling this can increase speed, while still showing revision, date, & author in the tooltip.

**Enable Pips** - By default, the extension displays a coloured pip next to each line number. This can be turned off, whilst still showing the blame information in the tooltip.

## Known Issues

### From upstream

- When detail is enabled, can be slow, because all unique logs have to be retrieved first. ([#3](https://github.com/BeauAgst/blamer-vs/issues/3))
- Authentication errors [#5](https://github.com/BeauAgst/blamer-vs/issues/5), [#9](https://github.com/BeauAgst/blamer-vs/issues/9)

## Future features

- Automatic blame on file open
- Ideas and contributions always welcome!

repository: sergentn/blamer-vs

repo_name: sergentn/blamer-vs


text:
# 0.1.0

1. --fix gameplay bug (energy management)--
1. --split big actual Ring into dedicated Ring for UI, GamePlay--
1. replace string 'ship' by 'drone' (code, doc)
1. fire bullet with '2' and not 'spacebar'

# 0.2.0

1. despawn/spawn targetG1 when hit (instead of impulse)
1. collision with wall crash the ship => management of respawn
1. tuning : adjust energy up/down (ex boost 20s should consumme all energy)

# 0.3.0

1. display value on targetG1
1. display shadow of ship
1. animations for spawn, despawn and other case (ex : ship rotate)
1. manage animations blending ?
1. "billboard", display information (2d) around 3d object
1. display via billboard gain of points (+1) with an animation

# 0.4.0

1. sound on events (blending ?, multi event in parallele ?)
1. control ship with mouse ?
1. ui/api from console to customize ships behavior (for dev)
1. remove ?bust on resources on GAE

# 0.5.0

1. add shield + implusion
1. activate shield with '1'
1. add armor to shield (shield should consume armor on hit, or more energy ?)

# 0.6.0

1. background music
1. preload assets

# 0.7.0

1. loading screen (also display controls ?)
1. display title + instructions

# 0.8.0

1. replay screen
1. polish visual assets items
1. make a box2dbebug visual layer ?

# 0.9.0

1. drone spawn area define in 3d model (blender : use property, name, material name ??)
1. use particules to display boost
1. use particules for explosions and some animations

# 0.10.0

1. provide a leaderboard (login, best score per game/ship)

# 1.0.0

1. first announce 1.0.0

# 1.1.0

1. control ship with joypad
1. display ads (where ?)
1. full screen (on/off)

# 1.2.0

1. ui to customize keys @settings
1. manage user/ship settings (store, autoreload, notify) @settings
1. ui to customize ships behavior @settings

# 1.3.0

1. control ship with touch @tablet
1. reactive resolution @tablet
1. display mini-radar

# 2.0.0

1. display name of pilot @multi
1. use a server + run 2 ships (try PuNub) @mutli

# Backlog

1. use Periodic Event to manage Energy, consommable ?, need for non-discret event (timeline, periodic sub-event)
1. move ring gamerules (include physics) in a WebWorker

# Misc

1. Music
1. Sound Effects (jsfxrt)
1. Splash screen (loading bar + advertising / animation)
1. Victoty/Achevement screen per user, global
1. Scores screen (per area/level)
1. Story
1. Instruction/explanations/tutorial (learning curve, achivments, mission,...)

license: Unlicense


text:
---
layout: post
title: "C中的Trigraphs"
date: 2010-06-18  21:12
comments: true
categories: tech
tags: ["c","c++"]
_baiduhi_id: c5d58d942f014813d31b70de.html
_baiduhi_category: c&c++
---

(hplonline)2010.6.18

今天又在论坛火星地发现一个东西了。。

先来个加强版的demo：

#include <stdio.h>

int main()??<

printf("??!") ;

printf("%d" ,  1 ??' 0) ;

return 0 ;

??>

》》转：关于Trigraphs

Trigraphs

The source character set of C source programs is contained within the 7-bit ASCII character set but is a superset of the ISO 646-1983 Invariant Code Set. Trigraph sequences allow C programs to be written using only the ISO (International Standards Organization) Invariant Code Set. Trigraphs are sequences of three characters (introduced by two consecutive question marks) that the compiler replaces with their corresponding punctuation characters. You can use trigraphs in C source files with a character set that does not contain convenient graphic representations for some punctuation characters.

Table 1.1 shows the nine trigraph sequences. All occurrences in a source file of the punctuation characters in the first column are replaced with the corresponding character in the second column.

Table 1.1   Trigraph Sequences

Trigraph Punctuation Character

??= #

??( [

??/ \

??) ]

??’ ^

??< {

??!  |

??> }

??-  ~

A trigraph is always treated as a single source character. The translation of trigraphs takes place in the firsttranslation phase, before the recognition of escape characters in string literals and character constants. Only the nine trigraphs shown in Table 1.1 are recognized. All other character sequences are left untranslated.

The character escape sequence, \?, prevents the misinterpretation of trigraph-like character sequences. (For information about escape sequences, see Escape Sequences.) For example, if you attempt to print the string What??! with this printf statement

printf( "What??!\n" );

the string printed is What| because ??! is a trigraph sequence that is replaced with the | character. Write the statement as follows to correctly print the string:

printf( "What?\?!\n" );

In this printf statement, a backslash escape character in front of the second question mark prevents the misinterpretation of ??! as a trigraph.

上面标红的这个first translation phase很关键！

编译器对trigraphs的解析是在所有动作之前的，

甚至在对转义字符“\“的前面。

所以转文附带了一个在问号前加转义的例子。

又正由于这个特性，

连前后大小括号也可以这么替代。。。

于是就出现了上面这个长的很别扭的程序。

据说是因为以前有些键盘没有这些符号才这样搞的，

但这应该是很早很早以前的事了吧。。

repository: hupili/backup-hplonline

repo_name: hupili/backup-hplonline


text:
# (Attempt) Implementation of a glottal inverse filtering algorithm

Written by Chloé (Rika) Ichinose, under MIT License

---

## Dependencies

* GNU Scientific Library 2.5 with CBLAS
* PortAudio v19

---

## How to use

```sh
make BUILD_TYPE=Release
```
Builds release variant binaries.

```sh
make
# or
make BUILD_TYPE=Debug
```
Builds ddebug variant binaries.

See `Makefile` for more make targets.

---

## Sources and references

* Alternating minimisation for glottal inverse filtering - [Ismael Rodrigo Bleyer et al 2017 Inverse Problems 33 065005](https://doi.org/10.1088/1361-6420/aa6eb8)
* COVAREP's implementation of the IAIF algorithm - [COVAREP's GitHub repository](https://github.com/covarep/covarep/blob/master/glottalsource/)
* The algebra of harmonic functions for a matrix-valued transfer operator - [arXiv:math/0611539v3 (math.FA) 7 Jun 2007](https://arxiv.org/pdf/math/0611539.pdf)
* MATLAB's explanation of their LPC analysis algorithm - [Mathworks MATLAB Documentation lpc](https://www.mathworks.com/help/signal/ref/lpc.html)
* Time-domain digital filter representations - [DSPRELATED.com Introduction to Digital Filters](https://www.dsprelated.com/freebooks/filters/Time_Domain_Digital_Filter.html)

**TODO: List all references**

---

Readme was last updated on Jan 23., 2019

repository: project-spectra/glottal-inverse

repo_name: project-spectra/glottal-inverse


text:
+++
title="Struct Extension for Compiled Bril Programs"
[[extra.authors]]
name = "Mark Moeller"
[extra]
latex = true
bio = """
  Mark Moeller is a first-year graduate student in Computer Science at Cornell
  interested in compilers and formal foundations of programming languages.
"""
+++

### Motivation: Garbage Collection for Compilers

Building garbage collectors for compilers (as opposed to interpreters) is
particularly tricky, since almost everything about garbage collection algorithms
is informed by dynamic information. Assuming we are not in a virtual machine
environment (such as Java, which can relegate details of garbage collection to
the JVM), we must "bake in" statically a host of things to be checked or
performed dynamically. This involves, at least, the following decisions:
* What type of collection? While the two main choices here are tracing and
  reference counting, we saw in the [Unified Theory of Garbage
  Collection][unified], complete answers lie on a spectrum. This choice is somewhat
  orthogonal to the compiler/interpreter issue.
* When to collect? Certainly this decision will ideally be informed by dynamic
  information about the heap state to minimize unnecessary pauses or overhead.
  This is still more complicated when compiling to native binaries as opposed to
  virtual machine bytecode where more safepoints may be available. For example,
  to be a drop-in replacement for manual memory managment in C, one (naively at
  least) has only malloc calls to work with as possible collection times.
* How much to collect? Both tracing and reference counting have tunable early
  returns that offer sacrificing memory efficiency for performance. Again,
  whatever decisions we need to make must be evaluated by code that was emitted
  statically.

### Contributions

To explore these issues, I built a new compiler from Bril to LLVM that supports the
[memory extension][memex] (due to Zagieboylo, Doenges).

Before getting into any garbage collection, I needed a little more expressive
language for heap manipulation than just pointers to primitive arrays. For this,
I built [a compiler][brilc] that implements a new *struct extention* for Bril, which allows
the use of structs similar to those in C.

# A Struct Extension for Bril

Programs using this extension have a second top-level key (i.e., in addition to
`"functions"`), called `"structs"`, which define C-like struct datatypes for use
in the program. A struct definition has only two keys:
* `name`: a name for the struct type.
* `mbrs`: a list of dictionaries that represent the members of the struct type.
          Each dictionary has two keys, `type`, which gives a valid Bril type,
          and `name`. (Observe that these are the same two fields that an
          argument to a function has).

## Warm-up Example
To use the standard first struct example, we might define a struct to represent
a point in `$\textbf{Z}^2$`. (Note that we narrowly miss one of the three
disallowed names for a struct type, `int`, `bool`, and `ptr`.)
```
struct point = {
    x: int;
    y: int;
}
```
which would have the JSON representation:
```
{"name": "point", "mbrs":[{"type": "int", "name": "x"}, {"type": "int", "name": "y"}]}
```
For the rest of this post, we'll only use the text representation for
definitions.

## Memory Allocation for Structs
Instances of structs are only allowed to be allocated on the heap, using the
memory extension.  Thus, we can use
`alloc` without modification to get a space for an instance of a struct on
the heap, or to get really exciting, a whole array. Importantly, the struct is
not automatically initialized. It is illegal to `load` from any struct member
that has not been previously written to.

So we can allocate a `point` with:
```
one: int = const 1
p: ptr<point> = alloc one
```

To access the members of the struct, we only need a way to get a name for the
members, since we can read and write using `load` and `store` from the normal
memory extension. For this, we a new value instructions:

* `getmbr`, which takes two arguments: a pointer to a struct, and the name of a
  member of the struct. It returns a pointer to the requested element, with
  appropriate pointer type. Since we can only ever have pointers to structs,
  this is always possible.

In text form, this would look like this:
```
<dest>: <ty> = getmbr <ptr> <mbr>
```
If this evokes LLVM's `getelementptr` in your mind, you've got it! (That is how
this instruction is implemented.) In the future, it might be convenient to
provide a "dot-notation" as syntactic sugar for member access.

Or in the case of our `point` struct, we would initialize (`x`, `y`) to (1, 1) with:
```
px: ptr<int> = getmbr p x;
store px one;

py: ptr<int> = getmbr p y;
store py one;
```

## Recursive Example
Of course, to do anything actually interesting with structs, we need the ability
to point to other structs from a struct. We can do this, but note that we can
only have pointers to other structs, not nested definitions of new structs
(Since we don't have any concept of closures, this would not be useful anyway.)

For example, we could have a linked list as:
```
struct int_list = {
    elt: int;
    next: ptr<int_list>;
}
```

Naturally, we need a way to close off such a recursive structure. Strictly
speaking, we could do this with another member (say, a bool to indicate the last
element). This would be rather inelegant, however, since then we'd have
uninitialized data in an active struct. Instead, somewhat reluctantly, I
added a `nullptr` constant that can be assigned to any pointer type. Suppose
`last` is a `ptr<int_list>` and the last element of a linked list. Then we can
end the list with:
```
last_n: ptr<ptr<int>> = getmbr last next;
```

Finally to allow recursive algorithms to be encoded in the usual way, a test for
whether a pointer is `nullptr` is provided with an `isnull` predicate:
```
<dest>: bool = isnull <ptr>
```

With those preliminaries in hand, we can start expressing typical algorithms for
our new data structure:
```
@cons (head: int, tail:ptr<int_list>): ptr<int_list> {
    one: int = const 1;
    p: ptr<int_list> = alloc one;

    phead: ptr<int> = getmbr p elt;
    ptail: ptr<ptr<int_list>> = getmbr p next;

    store phead head;
    store ptail tail;

    ret p;
}

@print_list (list: ptr<int_list>) {
    empty: bool = isnull list;
    br empty .end .print;
.print:
    xp: ptr<int> = getmbr list elt;
    x: int = load xp;
    print x;

    tp: ptr<ptr<int_list>> = getmbr list next;
    t: ptr<int_list> = load tp;
    call @print_list t;
.end:
    ret;
}

@free_list (list: ptr<int_list>) {
    empty: bool = isnull list;
    br empty .end .freetail;
.freetail:
    tp: ptr<ptr<int_list>> = getmbr list next;
    t: ptr<int_list> = load tp;
    call @free_list t;
    free list;
.end:
    ret;
}
```
# Implementation

The compiler is implemented in Python, with help from clang to generate LLVM for
builtin functions written in C. I modified the Bril parser to allow structs as
described; that extension is [here][brilex]. I add the struct extension features
to the reference interpreter.

The compiler first performs the SSA conversion on the input program. I used my
implementation from Lesson 5.) This required a couple of modifications:
* The member name argument to `getmbr` is "special" syntactically, and should
  not be renamed during SSA conversion.

* My SSA conversion allowed blocks to "fallthrough" the next label. Since LLVM
  disallows this, I updated my SSA conversion to end each block with a
  terminator.

* Bril actually disallows constant propagation to a degree, in the sense that
  literals cannot be dropped into later expressions where constants are used.
  LLVM requires this since you cannot assign constants to registers.

# Evaluation

### Correctness

I validated my solution first and foremost by compiling and running the Bril
benchmark suite. There is one outstanding bug from the benchmark suite:
`mat-mul` outputs some negative numbers which does not happen when under the
reference interpreter. In experimenting with this bug, I wondered if
I had selected the wrong LLVM instruction for Bril's `div` (I had picked `sdiv`,
the signed integer division instruction.) Curiously enough, replacing `sdiv`
with *any* of `udiv`, `udiv exact`, or `sdiv exact` "fixed" the bug (but broke
one other test in each case).

### Memory Management

The major evaluation in my proposal had been to measure the memory footprint of
programs using garbage collection. Since my implementation is well short of that
goal, I did not evaluate the memory management (as it was being done manually).
I did at least confirm that my programs did not have dynamic memory violations
by running them under Valgrind.

Part of my proposal had been fairly hand wavy about where I would get enough
benchmarks to measure the code running in the first place. A big lesson learned
for me from the experience of doing this project is that generating a lot of
valid input programs for compiler testing is really hard!

# Conclusions

While this project has not matured quickly enough yet to explore the garbage
collection issues I was originally after, we are at least now in a position to
do so in future work.

The decision to write something from scratch always has its costs and benefits.
I do think my compiler is built in a way suitable for an automatic garbage
collection improvement.

To return to three garbation collection design questions I posed at the top of
this post, I think the best approach is to start with a simple, flexible
solution and tune towards particular use cases. To that end, I think the best
answers for a first version of a collector for this compiler would be:
* What type of collection? Tracing, since the naive implementation collects
  everything, while a naive implementation of reference counting misses cycles.
  To make things more efficient, it can be an improvement later on to add
  generations that are only reference counted.
* When to collect? For a simple starting point, we could record
  heap size periodically (whether it is an object count or byte count) and
  collect in conjunction with an alloc whenever we exceed some threshold increase.
  That would provide plenty of opporunity for tuning later on as well.
* How much to collect? Since we chose tracing, the best starting point would
  just be to do a full collection every time, then we can experiment from there
  with generations to decide what types of collection are the most worthwhile.

[memex]:   https://capra.cs.cornell.edu/bril/lang/memory.html
[unified]: https://www.cs.cornell.edu/courses/cs6120/2020fa/blog/unified-theory-gc/
[brilc]:   https://github.com/mdmoeller/6120_tasks/tree/master/project
[brilex]:  https://github.com/mdmoeller/bril/tree/structex


text:
---
id: 38
title: 'Announcing Hacking the Impossible – The Developer’s Guide to Working with Visionaries'
date: 2014-07-09T16:48:58+00:00
author: Jonathan Cutrell
templateKey: blog-post

dsq_thread_id:
  - '3005980611'
tags:
  - Thoughts
---

## Update: I've abandoned this project for now.
It's important to know when to leave something behind.

I’m more than excited to announce that I will be publishing a book soon that’s all about the work I do on a day-to-day basis with some incredibly creative people here at Whiteboard.

In the book, you’ll find ideas that I believe could change the way developers and visionaries work together, and I’m really excited to share it with you.

If you’re interested in learning more about the book in the upcoming days, drop by http://hackingtheimpossible.com and sign up for the mailing list, and then follow @hackimpossible on Twitter.

About the book

If you work at a creative agency, you’ve almost certainly experienced the phenomenon of personality difference that Hacking The Impossible is all about. The two polar creative opposites - The Developer and The Visionary - sit in their corners of the room, each with entirely different understandings of what it means to work. The developer believes in concrete structure and receives in equal portions nerd-ridicule and geek-cred; the visionary follows the latest fashion trends and seems to shift from one idea to the next, living in complete oblivion to the complexity of technology. The developer is often accused of being anti-social, closed-minded, or pessimistic, while the visionary is accused of having their head in the clouds, getting wrapped up in impractical or downright impossible ideas.

The truth, however, is that the powerful creative abilities of each of these polar opposite caricatures are held within their ability to be the extreme versions of themselves. The visionary holds keys to imagining the impossible things, and the developer’s job is to build the impossible.

This book is about two things: how to work better with people, and how to use those skills to think about problems in a new light. This new light illuminates the path to innovation, and reminds you that with the right people in the right room at the right time, the impossible can be achieved.

Don’t forget to sign up for the mailing list at http://hackingtheimpossible.com to receive periodic updates from me about the book!

repository: jcutrell/jonathancutrell

repo_name: jcutrell/jonathancutrell


text:
# CodeSplitJava
CodeSplitJava splits Java projects by putting classes and methods into separate files. It is useful when we want to have definition of a class or a method.

## Compilation
We use maven to develop and build this application with the help of Eclipse IDE and libraries.
To create a runnable jar, run the following command in the directory where the repository is cloned:
```text
mvn clean install
```
If you use Eclipse:
* open the project using Eclipse
* then right-click on the project name and select 'run as > maven install'

## Execute the tool
After the previous step is done:
* Open terminal/command line console and run the jar
```text
  java -jar CodeSplitJava.jar -i <path of the input source folder> -o <path of the output folder> -m <mode>
  ```
  Here, <mode> could be either "method" or "class".

repository: tushartushar/CodeSplitJava

repo_name: tushartushar/CodeSplitJava


text:
# Hangry

Rutgers Coding Bootcamp Project One - Frontend Development.

Hangry is a restaurant finder in three easy steps using Google maps and Zamato API.

## Demo

https://kalmontee.github.io/Balletime/

## Technologies

* HTML
* CSS
* JavaScript
* jQuery
* Bootstrap

## How the App Works

The user will have the option to find their location or add their current address.
* If the user clicks "Find My Location" it will display their exact location.
* If user decides to write their address it will display their location.

![Animated GIF-downsized_large (2)](https://user-images.githubusercontent.com/52462582/69441276-6b5f3800-0d18-11ea-835a-c6020c126940.gif)

Also have the option to choose the radius of how far they're willing to search for a restaurant.

Once user's location is set, they can now find restaurants by clicking "Find A Place".

Each time they press "Find A Place" a new random restaurant will appear.

![Animated GIF-downsized_large (3)](https://user-images.githubusercontent.com/52462582/69441535-e9bbda00-0d18-11ea-89b0-dd35c51b9fb1.gif)

If user wants to view all their restaurants they found then they should click "Previous Places". There it will display all
the restaurants they search.

![Animated GIF-downsized_large (4)](https://user-images.githubusercontent.com/52462582/69441772-4b7c4400-0d19-11ea-8f16-143614d2c3eb.gif)

## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

## Commits

To see all the commits click here: [LazaroPerez0823/Balletime](https://github.com/LazaroPerez0823/Balletime)

## Authors

* **Lazaro Perez** - [LazaroPerez0823](https://github.com/LazaroPerez0823)

* ***Marc Dycus*** - [marcdycus](https://github.com/marcdycus)

## License
[MIT](https://choosealicense.com/licenses/mit/)

repository: kalmontee/Balletime

repo_name: kalmontee/Balletime


text:
---
layout: post
title: My month of January, the cliff notes version
---
I spent most of January working on exercism challenges and refamiliarizing myself with Rails. I haven't been able to pair program with other people yet and online
exercises have been the only way I've gotten feedback for the programs I've written. It's been a good way to learn more about design patterns and subtleties in the Ruby language. Out of all the exercises there, I enjoyed the one about Binary Search Trees the most. Another user on the site turned me towards using the Null Object Pattern and my research into the topic led me to an [article](http://devblog.avdi.org/2011/05/30/null-objects-and-falsiness/) that illustrated how it could be used in Ruby. In the end, I ended up with code that looked like this:

~~~ ruby
class Bst
  attr_accessor :left, :right, :data

  def initialize(data)
    @data = data
    @left = NullObject.new
    @right = NullObject.new
  end

  def insert(number)
    if number > @data
      in_right(number)
    elsif number <= @data
      in_left(number)
    end
  end

  def each(&block)
    left.each(&block)
    block.call(data)
    right.each(&block)
  end

  private

  def in_right(number)
    right.insert(number) or @right = Bst.new(number)
  end

  def in_left(number)
    left.insert(number) or @left = Bst.new(number)
  end
end
class NullObject
  def data
    nil
  end

  def insert(*)
    false
  end

  def each(*)
    self
  end
end

~~~

The exercism website also had challenges that involved other data structures
like linked lists and matrices. I've been reading more and more about how to
become job ready as a programmer and there have been a lot of advice on being
familiar with common data structures and how to implement them as well as
recognizing the [Big-O](http://bigocheatsheet.com/) complexities of different algorithms. I've mostly been teaching
myself and I know that I need to spend time on subjects that other programmers
would have been exposed to in school. I want to do my best to expose my
ignorance now.

 I've also started a membership at [upcase](upcase.com) so that I could become
more familiar with the tools that Ruby on Rails developers use. I've learned
more about how to use vim and testing use rspec/capybara. I'm amazed by how
efficient I could be using while vim and how easy it could be to learn when I'm
pointed in the right direction. I've neglected how to write my own tests in the
past and I'm trying to remedy that by learning how to use the tools other
developers employ. Currently, I'm also trying to learn how to use tmux in one of
upcase's new trails.

repository: raysapida/previous-jekyll-blog

repo_name: raysapida/previous-jekyll-blog


text:
# Learn Python by Building Data Science Applications

This is the code repository for [Learn Python by Building Data Science Applications](https://www.packtpub.com/programming/learn-python-by-building-data-science-applications?utm_source=github&utm_medium=repository&utm_campaign=9781789535365), published by Packt.

**A fun, project-based guide to learning Python 3 while building real-world apps**

## What is this book about?
Python is the most widely used programming language for building data science applications. Complete with step-by-step instructions, this book contains easy-to-follow tutorials to help you learn Python and develop real-world data science projects. The “secret sauce” of the book is its curated list of topics and solutions, put together using a range of real-world projects, covering initial data collection, data analysis, and production.

This book covers the following exciting features:
* Code in Python using Jupyter and VS Code
* Explore the basics of coding – loops, variables, functions, and classes
* Deploy continuous integration with Git, Bash, and DVC
* Get to grips with Pandas, NumPy, and scikit-learn
* Perform data visualization with Matplotlib, Altair, and Datashader
Create a package out of your code using poetry and test it with PyTest
Make your machine learning model accessible to anyone with the web API

If you feel this book is for you, get your [copy](https://www.amazon.com/dp/1789535360) today!

## Instructions and Navigations
All of the code is organized into folders. For example, Chapter01.

The code will look like the following:
```
import pandas as pd

for word in 'Hello Word!'.split():
    print(word)
```

**Following is what you need for this book:**
This book is aimed at new Python developers with little to no prior programming skills beyond basic computer literacy. The book doesn't require any previous background in data science or statistics either. That being said, it covers a variety of topics, from data processing to visualization, to delivery—including dashboards, building APIs, Extract, Transform, Load (ETL) pipelines, or a standalone package. Thus, it is also suited to experienced data scientists interested in productizing their work. For a complete novice, this book aims to cover all major parts of the data application life cycle—from Python basics to scripts, data collection and processing, and the delivery of your work in different formats.

With the following software and hardware list you can run all code files present in the book (Chapter 1-20).
### Software and Hardware List
| Chapter | Software required | OS required |
| -------- | ------------------------------------ | ----------------------------------- |
| All | Python 3, Visual Studio Code, Anaconda | Windows, Linux, macOS |

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. [Click here to download it](https://static.packt-cdn.com/downloads/9781789535365_ColorImages.pdf).

### Related products
* Expert Python Programming - Third Edition  [[Packt]](https://www.packtpub.com/application-development/expert-python-programming-third-edition?utm_source=github&utm_medium=repository&utm_campaign=9781789808896) [[Amazon]](https://www.amazon.com/dp/1789808898)

* Mastering Object-Oriented Python - Second Edition  [[Packt]](https://www.packtpub.com/in/programming/mastering-object-oriented-python-second-edition?utm_source=github&utm_medium=repository&utm_campaign=9781789531367) [[Amazon]](https://www.amazon.com/dp/1789531365)

## Get to Know the Author
**Philipp Kats**
is a researcher at the Urban Complexity Lab, NYU CUSP, a research fellow at  Kazan Federal University, and a data scientist at StreetEasy, with many years of experience in software development. His interests include data analysis, urban studies, data journalism, and visualization. Having a bachelor's degree in architectural design and a having followed the rocky path (at first) of being a self-taught developer, Philipp knows the pain points of learning programming and is eager to share his experience.

**David Katz**
is a researcher and holds a Ph.D. in mathematics. As a mathematician at heart, he sees code as a tool to express his questions. David believes that code literacy is essential as it applies to most disciplines and professions. David is passionate about sharing his knowledge and has 6 years of experience teaching college and high school students.

### Suggestions and Feedback
[Click here](https://docs.google.com/forms/d/e/1FAIpQLSdy7dATC6QmEL81FIUuymZ0Wy9vH1jHkvpY57OiMeKGqib_Ow/viewform) if you have any feedback or suggestions.

### Download a free PDF

 If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.

 https://packt.link/free-ebook/9781789535365

gha_language: Jupyter Notebook


text:
# submit-anything

microservice for posting anything

self hosted form-submit-capture service

### example request

    # endpoint of service: http://acme.com/submit-anything
    # org: acme
    # type: contact
    # POST submission/{org}/send/{type}
    curl --header "Content-Type: application/json" \
      http://acme.com/submit-anything/submission/acme/send/contact \
      -d '{"name":"strange guy","email":"latoya@myspace.com","message":"i like your website, please call back"}'

hmm, ok, now that we can post anything to the bucket, how is it going on from here. i guess we need some user/auth/token magic to let our orgs read and delete submissions.

... and configure stuff, like send-email, send-to-messanger, hook some webs.

... and a vue component for submissions

... and another one for dashboard integration

you see, it's very experimental

i'd like to know, how mysql performs in terms of table with json field vs. new xdevapi/ document store

### managing api

#### create org

	 curl -v -X POST http://acme.com/submit-anything/manage/org/create/acme -H "x-any-admin: secret"

	 => {"name":"acme","password":"XbRQvaE3gm6eL##","api_key":"c56c61505a7abbd9d0d5a975e8d59ec08da0cbc1b3517e3f180978a07eb59a69","types":"{}"}

repository: cwmoss/submit-anything

branch_name: refs/heads/main

repo_name: cwmoss/submit-anything


text:
# Serverless Web API with Azure Functions, Azure Cosmos DB MongoDB API and C#

In this tutorial, we’ll build a Web API using Azure Functions that stores data in Azure Cosmos DB with MongoDB API in C#

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gbqg9bg7kxqvqv1r2frk.png)

[Azure Cosmos DB](https://docs.microsoft.com/en-us/azure/cosmos-db/) is a globally distributed, multi-model, NoSQL database service that allows us to build highly available and scalable applications. Cosmos DB supports applications that use Document model data through it’s [SQL API](https://docs.microsoft.com/en-us/azure/cosmos-db/introduction) and [MongoDB API](https://docs.microsoft.com/en-us/azure/cosmos-db/mongodb-introduction).

I’ve been meaning to produce more content on Cosmos DB’s Mongo API, so in this article, I’m going to be developing a Serverless API in [Azure Functions](https://docs.microsoft.com/en-us/azure/azure-functions/) that uses a Cosmos DB MongoDB API account. This article has been loosely based on this fantastic tutorial on [creating a Web API with ASP.NET Core and MongoDB](https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-5.0&tabs=visual-studio#prerequisites).

By the end of this article, you’ll know how to create a Cosmos DB account that uses the MongoDB API. You’ll also know how to create a simple CRUD Web API in C# that interacts with a Mongo DB API account.

If you want to see the whole code before diving into the article, you can check it out on my GitHub [here](https://github.com/willvelida/cosmosdb-mongo-api).

What you’ll need to follow along with this article:
- Visual Studio 2019 with the Azure Development workload.
- Azure Subscription.
- [Postman](https://www.postman.com/).

## How does Azure Cosmos DB support a MongoDB API?

[Azure Cosmos DB implements the wire protocol for MongoDB](https://docs.microsoft.com/en-us/azure/cosmos-db/mongodb-introduction#wire-protocol-compatibility), allowing us to use client drivers and tools that we’re used to, but allow us to host our data in Azure Cosmos DB.

This is great if we already have applications that use MongoDB. We can change our applications to use Azure Cosmos DB without having to make significant changes to our codebase. We can also gain the benefits of Azure Cosmos DB, such as Turnkey distribution and elastic scalability in both throughput and storage.

## Setting up an Account with the MongoDB API

Let’s set up our Cosmos DB account. Login to Azure and click on Create a resource. Look for Azure Cosmos DB and click ‘New’.
On the ‘Create Azure Cosmos DB Account’ page, provide the following configuration:

- *Resource Group* — Resource groups in Azure are a logical collection of resources. For this tutorial, you can create a new one or add your account to an existing one.
- *Account Name* — This will be the name of your account. It needs to be unique across Azure, so make it a good one :)
API — Azure Cosmos DB is a multi-model database, but when we create a Cosmos DB account, we can only pick one API and that will be the API for the lifetime of the account. Since this is a Mongo DB API tutorial, pick the ‘**Azure Cosmos DB for MongoDB API**’ option.
- *Location* — Where we want to provision the account. I’ve chosen Australia East as that’s the datacenter close to me, but pick a datacenter close to you.
- *Capacity Mode* — In a nutshell, this is how throughput will be provisioned in this account. I have written articles on how throughput works in Cosmos DB if you are interested, but for now choose ‘**Serverless**’ (still in preview at time of writing).
- *Account Type* — Choose production
- *Version* — This is the version of the MongoDB wire protocol that the account will support. Choose 3.6
- *Availability Zones* — Disable this for now.

You configuration should look like the figure below:

![](https://miro.medium.com/max/1400/1*Y92WfhaI0ysHCQqMaAln2g.png)

Click **Review+Create**, then **Create** to create your Cosmos DB account. Feel free to grab a cup of tea while you wait.
Once our account is set up, we can create our Database and collection we need for this tutorial. In the original blog post, we would create our Database and Collection via the Mongo Shell. But to keep things simple, we can do this in the portal.

In your Cosmos DB account, head into your Data Explorer and click ‘**New Collection**’.  We are then asked to choose a shard key.

Sharding in Mongo DB is a method for distributing data across multiple machines. If you’ve used the SQL API in Azure Cosmos DB, this is similar to a Partition Key. Essential this shard will help your application scale in terms of both throughput and storage through horizontal scaling.

For this tutorial, I’m going to pick the category as the shard key. Click OK to create your database and collection.

![](https://miro.medium.com/max/1400/1*CsAZZxJCmCRzKrmLfxTVpg.png)

We now have our Database, collection and account all set up. We just need one more thing before setting up, our connection string. Click on Connection String and copy the *PRIMARY CONNECTION STRING* value. Save this for later.

## Creating our Function Application.

Let’s head into Visual Studio and create our Serverless API. Open Visual Studio and click ‘**Create a new project**’.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2z1yuqjmgg1sj9kvehxa.png)

Choose ‘**Azure Functions**’ as our template to create the project. (Make sure C# is the selected language).

![](https://miro.medium.com/max/1400/1*Ae3YhG297CE1alhpTh4JWQ.png)

Call this project ‘**CosmosBooksApi**’, store the project in a location of your choice and click create:

![](https://miro.medium.com/max/1400/1*TPuFyeo0g4gh8x_Nng_ZhQ.png)

Select Azure Functions v3 (.NET Core) as our Runtime and create an empty project with no triggers:

![](https://miro.medium.com/max/1400/1*CkUYZaBs7V6CspQPUA30vA.png)

Before we start creating any of our Functions, we need to install the **MongoDB.Driver** package. To do this, right click your project and select ‘**Manage NuGet Packages**’. In the Browse section, type in MongoDB.Driver and install the latest stable version.

![](https://miro.medium.com/max/1400/1*ALbTXna1ofZNMqgvuht89w.png)

Once that’s installed, let’s create a *Startup.cs* file that will instantiate our *MongoClient*:

```
using CosmosBooksApi;
using CosmosBooksApi.Services;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Driver;
using System.IO;
using System.Security.Authentication;

[assembly: FunctionsStartup(typeof(Startup))]
namespace CosmosBooksApi
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build();

            builder.Services.AddSingleton<IConfiguration>(config);

            MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(config["ConnectionString"]));
            settings.SslSettings = new SslSettings() { EnabledSslProtocols = SslProtocols.Tls12 };

            builder.Services.AddSingleton((s) => new MongoClient(settings));
            builder.Services.AddTransient<IBookService, BookService>();
        }
    }
}
```

Since v2 of Azure Functions, [we have support for Dependency Injection](https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection). This will help us instantiate our *MongoClient* as a Singleton, so we can share our *MongoClient* amongst all of our Functions rather than creating a new instance of our client every time we want to invoke our Functions.

Let’s go through this class. To register our services, we need to add components to a *IFunctionsHostBuilder* instance, which we pass as a parameter in our *Configure* method.

In order to use this method, we need to add the *FunctionsStartup* assembly attribute to the Startup class itself.

We then create a new configuration of type *IConfiguration*. All this does is pick up configuration for the Function application from a *local.settings.json* file. We then add the *IConfiguration* service as a Singleton.

We can then set up our *MongoClient*. We start off by setting our connection string by passing in our *PRIMARY CONNECTION STRING* from earlier as a *MongoUrl()* object. Save this in your *local.settings.json* file. For reference, this is what my file looks like:

```
{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "ConnectionString": "<PRIMARY_CONNECTION_STRING>",
    "DatabaseName": "BookstoreDB",
    "CollectionName":  "Books"
  }
}
```

We can then pass the key of the setting (“**ConnectionString**”) into our *MongoUrl* object.

We then need to enable SSL by using the Tls12 protocol in the *SslSettings* for our *MongoClientSettings*. This is required by Azure Cosmos DB to connect to our MongoDB API account.

Once we’ve set up our *MongoClientSettings*, we can just pass this into our *MongoClient* object, which we set up as a Singleton Service.

Now we need to create a basic class to represent our Book model. Let’s write the following:

```
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace CosmosBooksApi.Models
{
    public class Book
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }

        [BsonElement("name")]
        public string BookName { get; set; }
        [BsonElement("price")]
        public decimal Price { get; set; }
        [BsonElement("category")]
        public string Category { get; set; }
        [BsonElement("author")]
        public string Author { get; set; }
    }
}
```

In this class, we have properties for the Book’s Id, name, price, category and author. The Id property has been annotated with the *BsonId* property to indicate that this will be the document’s primary key. We have also annotated the Id property with *[BsonRepresentation(BsonType.ObjectId)]* to pass our id as type string, rather than *ObjectId*. Mongo will handle the conversion from string to *ObjectId* for us.

The rest of our properties have been annotated with *[BsonElement()]*. This will determine how our properties look within our collection.

Now we’re going to create a service that will that handle the logic that works with our Cosmos DB account. Let’s define an interface called *IBookService.cs*.

```
using CosmosBooksApi.Models;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace CosmosBooksApi.Services
{
    public interface IBookService
    {
        /// <summary>
        /// Get all books from the Books collection
        /// </summary>
        /// <returns></returns>
        Task<List<Book>> GetBooks();

        /// <summary>
        /// Get a book by its id from the Books collection
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        Task<Book> GetBook(string id);

        /// <summary>
        /// Insert a book into the Books collection
        /// </summary>
        /// <param name="book"></param>
        /// <returns></returns>
        Task CreateBook(Book bookIn);

        /// <summary>
        /// Updates an existing book in the Books collection
        /// </summary>
        /// <param name="id"></param>
        /// <param name="book"></param>
        /// <returns></returns>
        Task UpdateBook(string id, Book bookIn);

        /// <summary>
        /// Removes a book from the Books collection
        /// </summary>
        /// <param name="book"></param>
        /// <returns></returns>
        Task RemoveBook(Book bookIn);

        /// <summary>
        /// Removes a book with the specified id from the Books collection
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        Task RemoveBookById(string id);
    }
}
```

This is just a simple CRUD interface that defines the contract that our service should implement. Now let’s implement this interface:

```
using CosmosBooksApi.Models;
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CosmosBooksApi.Services
{
    public class BookService : IBookService
    {
        private readonly MongoClient _mongoClient;
        private readonly IMongoDatabase _database;
        private readonly IMongoCollection<Book> _books;

        public BookService(
            MongoClient mongoClient,
            IConfiguration configuration)
        {
            _mongoClient = mongoClient;
            _database = _mongoClient.GetDatabase(configuration["DatabaseName"]);
            _books = _database.GetCollection<Book>(configuration["CollectionName"]);
        }

        public async Task CreateBook(Book bookIn)
        {
            await _books.InsertOneAsync(bookIn);
        }

        public async Task<Book> GetBook(string id)
        {
            var book = await _books.FindAsync(book => book.Id == id);
            return book.FirstOrDefault();
        }

        public async Task<List<Book>> GetBooks()
        {
            var books = await _books.FindAsync(book => true);
            return books.ToList();
        }

        public async Task RemoveBook(Book bookIn)
        {
            await _books.DeleteOneAsync(book => book.Id == bookIn.Id);
        }

        public async Task RemoveBookById(string id)
        {
            await _books.DeleteOneAsync(book => book.Id == id);
        }

        public async Task UpdateBook(string id, Book bookIn)
        {
            await _books.ReplaceOneAsync(book => book.Id == id, bookIn);
        }
    }
}
```

I’ve injected my dependencies to my *MongoClient* and *IConfiguration*, then I create my database and collection so I can perform operations against them. Lets explore the different methods one by one.

[InsertOneAsync](https://mongodb.github.io/mongo-csharp-driver/2.5/apidocs/html/M_MongoDB_Driver_IMongoCollection_1_InsertOneAsync.htm) — This will insert a single document into our *IMongoCollection* asynchronously. Here, we pass in the document we want to persist, this case being the Book object. We could also pass in some custom options (*InsertOneOptions*) and a *CancellationToken*. We’re not returning anything here expect the result of the insert operation ‘Task’.

[FindAsync](https://mongodb.github.io/mongo-csharp-driver/2.4/apidocs/html/M_MongoDB_Driver_IMongoCollectionExtensions_FindAsync__1_1.htm) — This will find a document that matches our filter asynchronously. Here, we use a lambda expression to find a book with the same id that we have provided in the method. We then use Linq to return the matching book.

[DeleteOneAsync](https://mongodb.github.io/mongo-csharp-driver/2.4/apidocs/html/M_MongoDB_Driver_IMongoCollectionExtensions_DeleteOneAsync__1_1.htm) — This will delete a single document that matches our expression asynchronously. Again, we use a lambda expression to find the book we wish to delete. We don’t return anything except the result of the operation.

[ReplaceOneAsync](https://mongodb.github.io/mongo-csharp-driver/2.4/apidocs/html/M_MongoDB_Driver_IMongoCollectionExtensions_ReplaceOneAsync__1.htm) — This will replace a single document asynchronously.

So we’ve created our *MongoClient* and have a basic CRUD service that we can use to interact with our Cosmos DB account. We’re now ready to start creating our Functions.

For this tutorial we will create the following functions:
- CreateBook
- DeleteBook
- GetAllBooks
- GetBookById
- UpdateBook

To create a new Function, we right-click our solution file and select ‘**Add New Azure Function**’. We should see a pop-up like this. Select Http Trigger and select Anonymous as the Function’s Authorization level.

![](https://miro.medium.com/max/1400/1*nLIGCbjpGLpjngkfl9qWAA.png)

Let’s start with our *CreateBook* function. Here is the code:

```
using CosmosBooksApi.Models;
using CosmosBooksApi.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Threading.Tasks;

namespace CosmosBooksApi.Functions
{
    public class CreateBook
    {
        private readonly ILogger<CreateBook> _logger;
        private readonly IBookService _bookService;

        public CreateBook(
            ILogger<CreateBook> logger,
            IBookService bookService)
        {
            _logger = logger;
            _bookService = bookService;
        }

        [FunctionName(nameof(CreateBook))]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "Book")] HttpRequest req)
        {
            IActionResult result;

            try
            {
                var incomingRequest = await new StreamReader(req.Body).ReadToEndAsync();

                var bookRequest = JsonConvert.DeserializeObject<Book>(incomingRequest);

                var book = new Book
                {
                    Id = ObjectId.GenerateNewId().ToString(),
                    BookName = bookRequest.BookName,
                    Price = bookRequest.Price,
                    Category = bookRequest.Category,
                    Author = bookRequest.Author
                };

                await _bookService.CreateBook(book);

                result = new StatusCodeResult(StatusCodes.Status201Created);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Internal Server Error. Exception: {ex.Message}");
                result = new StatusCodeResult(StatusCodes.Status500InternalServerError);
            }

            return result;
        }
    }
}
```

Here we are injecting our *IBookService* and our *ILogger* into the function. We invoke this Function by making a post request to the ‘**/Book**’ Route. We take the incoming HttpRequest and Deserialize it into a Book object. We then insert the Book into our Books collection. If we’re successful, we get a 201 response (Created). If not, we’ll throw a 500 response.

It’s a bit of a dramatic response code. We would want to throw a different code if there was a bad request of if our Cosmos DB account is unavailable, but for this basic example it will suffice.

Now let’s take a look at the *DeleteBook* function:

```
using CosmosBooksApi.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;

namespace CosmosBooksApi.Functions
{
    public class DeleteBook
    {
        private readonly ILogger<DeleteBook> _logger;
        private readonly IBookService _bookService;

        public DeleteBook(
            ILogger<DeleteBook> logger,
            IBookService bookService)
        {
            _logger = logger;
            _bookService = bookService;
        }

        [FunctionName(nameof(DeleteBook))]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "Book/{id}")] HttpRequest req,
            string id)
        {
            IActionResult result;

            try
            {
                var bookToDelete = await _bookService.GetBook(id);

                if (bookToDelete == null)
                {
                    _logger.LogWarning($"Book with id: {id} doesn't exist.");
                    result = new StatusCodeResult(StatusCodes.Status404NotFound);
                }

                await _bookService.RemoveBook(bookToDelete);
                result = new StatusCodeResult(StatusCodes.Status204NoContent);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Internal Server Error. Exception thrown: {ex.Message}");
                result = new StatusCodeResult(StatusCodes.Status500InternalServerError);
            }

            return result;
        }
    }
}
```

This time, we pass in an id to our Function (‘**/Book/id**’) to find the Book that we want to delete from our collection. We first look for the book using *IBookService* method *.GetBook(id)*. If we the book doesn’t exist, the Function will throw a 404 (not found) response.

If we can find the book, we then pass this book into our *RemoveBook(book)* method to delete the book from our collection in Cosmos DB. If successful, we return a 204 response.

Here is the code for the *GetAllBooks* function:

```
using CosmosBooksApi.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;

namespace CosmosBooksApi.Functions
{
    public class GetAllBooks
    {
        private readonly ILogger<GetAllBooks> _logger;
        private readonly IBookService _bookService;

        public GetAllBooks(
            ILogger<GetAllBooks> logger,
            IBookService bookService)
        {
            _logger = logger;
            _bookService = bookService;
        }

        [FunctionName(nameof(GetAllBooks))]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Books")] HttpRequest req)
        {
            IActionResult result;

            try
            {
                var books = await _bookService.GetBooks();

                if (books == null)
                {
                    _logger.LogWarning("No books found!");
                    result = new StatusCodeResult(StatusCodes.Status404NotFound);
                }

                result = new OkObjectResult(books);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Internal Server Error. Exception thrown: {ex.Message}");
                result = new StatusCodeResult(StatusCodes.Status500InternalServerError);
            }

            return result;
        }
    }
}
```

In this function, we simply make a GET request to the ‘**/Books**’ route. This Function will call the *.GetBooks()* method on our *IBookService* to retrieve all the books in our collection. If there are no books, we throw 404. If there are books returned to us, the function will return these as an array back to the user.

Our *GetBookById* function is similar to our *GetAllBooks* function, but this time we pass the id of the Book that we want to return to us:

```
using CosmosBooksApi.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;

namespace CosmosBooksApi.Functions
{
    public class GetBookById
    {
        private readonly ILogger<GetBookById> _logger;
        private readonly IBookService _bookService;

        public GetBookById(
            ILogger<GetBookById> logger,
            IBookService bookService)
        {
            _logger = logger;
            _bookService = bookService;
        }

        [FunctionName(nameof(GetBookById))]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Book/{id}")] HttpRequest req,
            string id)
        {
            IActionResult result;

            try
            {
                var book = await _bookService.GetBook(id);

                if (book == null)
                {
                    _logger.LogWarning($"Book with id: {id} doesn't exist.");
                    result = new StatusCodeResult(StatusCodes.Status404NotFound);
                }

                result = new OkObjectResult(book);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Internal Server Error. Exception thrown: {ex.Message}");
                result = new StatusCodeResult(StatusCodes.Status500InternalServerError);
            }

            return result;
        }
    }
}
```

We also pass an id to our *UpdateBook* function. We first make a call to our *.GetBook(id)* method to find the book we want to update. Once we’ve found the book, we then read the incoming request and deserialize it into a Book object. We then use the deserialized request to update our Book object and then pass this object into out *.UpdateBook()* method along with the id that we used to invoke the Function.

```
using CosmosBooksApi.Models;
using CosmosBooksApi.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Threading.Tasks;

namespace CosmosBooksApi.Functions
{
    public class UpdateBook
    {
        private readonly ILogger<UpdateBook> _logger;
        private readonly IBookService _bookService;

        public UpdateBook(
            ILogger<UpdateBook> logger,
            IBookService bookService)
        {
            _logger = logger;
            _bookService = bookService;
        }

        [FunctionName(nameof(UpdateBook))]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = "Book/{id}")] HttpRequest req,
            string id)
        {
            IActionResult result;

            try
            {
                var bookToUpdate = await _bookService.GetBook(id);

                if (bookToUpdate == null)
                {
                    _logger.LogWarning($"Book with id: {id} doesn't exist.");
                    result = new StatusCodeResult(StatusCodes.Status404NotFound);
                }

                var input = await new StreamReader(req.Body).ReadToEndAsync();

                var updateBookRequest = JsonConvert.DeserializeObject<Book>(input);

                Book updatedBook = new Book
                {
                    Id = id,
                    BookName = updateBookRequest.BookName,
                    Author = updateBookRequest.Author,
                    Category = bookToUpdate.Category,
                    Price = updateBookRequest.Price
                };

                await _bookService.UpdateBook(id, updatedBook);

                result = new StatusCodeResult(StatusCodes.Status202Accepted);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Internal Server Error: {ex.Message}");
                result = new StatusCodeResult(StatusCodes.Status500InternalServerError);
            }

            return result;
        }
    }
}
```

## Testing our Function

Now that we’ve finished coding up our Functions, let’s spin it up and test it! Press F5 to start running our function locally. Give it a second to spin up and you should see the following endpoints for each of our Functions.

![](https://miro.medium.com/max/1400/1*TGejFS-m5T0Y0euZaE1Y7Q.png)

As you can see, our functions are running on localhost. We can use Postman to test these endpoints.

Let’s start with our *CreateBook* Function. Copy and Paste the endpoint for the Function into Postman. Set the request method to POST and click on the body tab. We need to send our request as a JSON payload, so set it to JSON and add the following body:

```
{
  "BookName" : "Computer Science: Distilled",
  "Price": 11.99,
  "Category": "Technology",
  "Author": "Wladston Ferreira Filho"
}
```

Your Postman request should look like this:

![](https://miro.medium.com/max/1400/1*idOuRJxoInuRYS34nDGovQ.png)

Hit Send to send the request. We should get the following response (201).

![](https://miro.medium.com/max/1400/1*D0X1yOqZhoMNe631QdxE3Q.png)

We can view the document in our Cosmos DB account to make sure that we added the document to our account, which it has:

![](https://miro.medium.com/max/1400/1*TVnhiVMl6U5TzbHu4dFUIQ.png)

Insert a couple more books before moving on. We will now try to retrieve all the books in our collection using the *GetAllBooks* Function. Clear the JSON payload from the Body and change the request method to GET. Hit Send to make the request:

![](https://miro.medium.com/max/1400/1*NR_HCnBOFPQ12BWufPtYSg.png)

We should get a response like this:

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rx44arlwgc0950lh681l.png)

Here we have all the books in our collection returned back to us as a JSON array. Now, let’s test our *GetBookById* Function. In the response of our *GetAllBooks* function, grab an id and add it as a parameter in your route. Keep the body clear and keep the GET request method. All that has changed here is that we are looking for a specific book by using its Id.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fmhb9g1wbxyx3lr59rre.png)

Hit Send to make the request. We should have the book object returned to us like so:

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ievidqwisth067ocbmp.png)

Now let’s remove this book from our Cosmos DB collection. Change your request method to DELETE in Postman and hit Send.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kcjbgvnunqpycz7injta.png)

We should get the following response:

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dmlst0mr846oy1n5b26z.png)

Checking our Collection in Azure Cosmos DB, we can see that the book is no longer there:

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ide40rvpg1uzmt0tt2hj.png)

Finally, let’s try updating a book. Let’s take the following book in our collection:

```
{
  "id": "603ae1b621786dd7fd92d5c0",
  "bookName": "The Dark Net",
  "price": 18.99,
  "category": "Technology",
  "author": "Jamie Bartlett"
}
```

Grab the id and use it as a parameter to our *UpdateBook* function. Change the method to a PUT request and add the following body to our request:

```
{
  "bookName": "The Dark Net v2",
  "price": 11.99,
  "author": "Jamie Bartlett"
}
```

We send this body as a JSON payload. Hit Send to update this Book document.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ns4qwn63ufucgrqi81y.png)

We should get the following response.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96cv19zzgjvtt4jp0fmn.png)

We can also verify that the document has updated successfully in our Cosmos DB account.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qv4p0i2vr5akp907mumb.png)

## Conclusion

In this tutorial, we built an CRUD Web API using Azure Functions that manages books in a Cosmos DB Mongo API account. While this was a simple tutorial, hopefully you can see that if you’ve already built applications using MongoDB as a datastore, you can easily change to Azure Cosmos DB without making drastic changes to your code base.

If you want to download the full code, check it out on my [GitHub](https://github.com/willvelida/cosmosdb-mongo-api) (If you notice anything wrong and want to help fix it, please feel free to make a PR!)

If you have any questions, please feel to comment below or reach out to me via [Twitter](https://twitter.com/willvelida).

repository: griffinbird/cosmosdb-mongo-api

repo_name: griffinbird/cosmosdb-mongo-api


text:
# Nidhogg
A Mojang [Yggdrasil](http://wiki.vg/Authentication) Kotlin/Multplatform client for Minecraft account authentication
 and communication to the Mojang APIs

## Compiling
The library JAR can be build using ``gradle jvmJar`` or ``gradle jsJar`` respectively. Please note, that the JS
 version may depend on the same code base, so it should work, but I never actually tested it.

## Usage
The Yggdrasil API is wrapped in ``YggdrasilClient``. When creating the client, a secret token can be given as
 parameter that can later be reused to refresh generated sessions. If no token is passed, a random one will be
  generated.

The client instance then offers the following methods, each of wich is a coroutine and is thus performed
 asynchronously:

````Kotlin
val client = YggdrasilClient(clientToken = uuid4().toString())

// login using credentials
val response = runBlocking {
    client.authenticate(AccountCredentials("username", "verysecurepassword"), MinecraftAgent, true)
}
val session = response.session

// validate a session. Returns true, if the session is valid, throws an appropriate exception otherwise.
runBlocking {
    client.validate(session, doSendClientToken = true)
}

// refreshes a session, if it is no longer valid
val response = runBlocking {
    client.refresh(session, selectedProfile = null, requestProfile = false)
}
session = response.session

// invalidate a session
runBlocking {
    client.invalidate(session)
}

// sign out of any existing sessions
runBlocking {
    client.signOut(AccountCredentials("username", "verysecurepassword"))
}
````

The Mojang API is wrapped in ``MojangClient``. It can be instantiated the same way as the ``YggrasilClient``, it just
 does not require a secret token.

Refer to the
[Yggdrasil test cases](https://github.com/Cydhra/Nidhogg/blob/master/src/jvmTest/kotlin/net/cydhra/nidhogg/YggdrasilClientTest.kt),
[Mojang test cases](https://github.com/Cydhra/Nidhogg/blob/master/src/jvmTest/kotlin/net/cydhra/nidhogg/MojangClientTest.kt)
and the [Batch test cases](https://github.com/Cydhra/Nidhogg/blob/master/src/jvmTest/kotlin/net/cydhra/nidhogg/BatchRequestsTest.kt)
 for more information about the clients' usage.

## Dependency Management
This project is currently not in any Maven repository, but you can use [Jitpack](https://jitpack.io/) instead:

#### Maven
````
<repositories>
    <repository>
	    <id>jitpack.io</id>
	    <url>https://jitpack.io</url>
	</repository>
</repositories>
````

````
<dependency>
    <groupId>com.github.Cydhra</groupId>
    <artifactId>Nidhogg</artifactId>
    <version>2.0.0</version>
</dependency>
````

#### Gradle

````
repositories {
     maven { url "https://jitpack.io" }
}
````
````
dependencies {
    compile group: 'com.github.Cydhra', name: 'Nidhogg', version: '2.0.0'
}
````

## Additional Dependencies
The library is built upon ktor, but does not depend on a specific HTTP engine. You can choose the engine by simply
 adding it to project dependencies like this:

````
implementation group: 'io.ktor', name: 'ktor-client-cio', version: ktor_version
````
Refer to the [Ktor Documentation](https://ktor.io/docs/http-client-engines.html#jvm) for more information about the
 available HTTP engines.

## License
This project is subject to the [MIT License](https://en.wikipedia.org/wiki/MIT_License) license.
Earlier versions of this library were distributed under Creative Commons.
If you still use those old versions, the license agreement is unchanged.
The new license should not make a notable difference to you, Creative Commons is just unsuited for code, so any new
 code added to the library will be distributed under the terms of MIT license.


text:
# Capacitated Vehicle Routing Problem #

### This repository contains algorithms to solve the CVRP (Capacitated Vehicle Routing Problem) in C++ ###

[![Build Status](https://travis-ci.com/vss2sn/cvrp.svg?branch=master)](https://travis-ci.com/vss2sn/cvrp)

#### Algorithms: ####
1. Greedy Solution
2. Local Search (Run on each vehicle separately; search restricted to the selected vehicle's initial route) (LS)
3. Local Search (LS)
4. Tabu Search (TS)
5. Genetic Algorithm (GA)
6. Simulated Annealing (SA)
7. Hybrid Algorithms (Using the solution found using one of the algorithms above as the input/starting point for another) (HA)

#### To build and run: ####
    git clone https://github.com/vss2sn/cvrp.git
    cd cvrp
    mkdir build
    cd build
    cmake .. && make -j4
    ./cvrp

#### Table of contents: ####
- [Algorithms](#algorithms)
- [Instructions](#instructions)
- [Table of contents](#toc)
- [Code Overview](#overview)
- [Documentation](#docs)
- [Overview of Algorithm Implementations](#algorithm_implementations)
- [Notes](#notes)
- [Visualization](#visualization)
- [TODOs](#todos)

#### Code Overview: ####
1. The code contains `Problem`, `Solution` and `Vehicle` classes. Each algorithm implementation has its own class and inherits the `Solution` class.
2. The problem is setup using the `Problem` class which specifies the number of nodes (centres/dropoff points), maximum demand, number of vehicles, their capacity, the grid range and the type of distribution. The demand for each centre as well as its location is randomly generated.
3. A base class called `Solution` has been created to store the basic elements of the solution in a user friendly format. This includes a `vector` of instances of the `Vehicle` class.
4. The `Vehicle` class stores the vehicle id, the route it takes, the total capacity, the number of units still left in the vehicle, and the cost associated with the vehicle's route. The `<<` operator is overloaded to show the status of the node and vehicle respectively. `PrintVehicleRoute()` prints only the route of the vehicle.
5. The `Solution` class also contains a virtual method called `Solve()`. Each algorithm class overrides the `Solve()` method.
6. The `Solution` class also contains a method called `PrintSolution(option)` with the an input option (`option`) to print vehicles' statuses or routes in addition to the total cost and validity of the solution.

#### Documentation: ####
1. [Documentation](https://vss2sn.github.io/cvrp/) can be found on GitHub pages.
2. It has been created using `Doxygen`, and pip3 packages `Sphinx` (`sphinx==1.8.31`), `Breathe` (breathe==4.12.0), `Exhale` (`exhale==0.2.2`),` Read the Docs` Sphinx Theme (`sphinx_rtd_theme==0.4.3`) and `m2r`.

#### Overview of Algorithm Implementations ####
For a brief overview on the implementations of the algorithms, please refer to this [document](https://vss2sn.github.io/cvrp/algorithm_implementations.html).

#### Notes: ####
1. The documentation for private functions (such as operators in the `GASolution` class) has been made available to aid understanding.
2. Custom hybrid algorithms, that involve feeding in the solution of 1 algorithm to another can easily be implemented, as the structure allows the extraction of solution from the algorithm classes. An example is shown at the end of `main.cpp`.

#### Visualization: ####
This repository (**optionally**) uses `SFML` for visualization. It can be installed using `sudo apt install libsfml-dev`.
To run with `SFML`, include the header file `graphics_utils.hpp` in `main.cpp`, and use the function `DisplaySolution(<solution>)`, passing in the solution to e displayed, and build the code with `cmake .. -DDISPLAY_SOLUTION=ON`, or modify its value in `ProjectSpecificSettings.cmake`.

#### TODOs: ####
1. Read in problem from a file.
2. Consider adding plot of best solution cost vs time.
3. Consider adding savings algorithm
4. Consider adding maximum distance constraint
5. Consider modifying to allow heterogeneous vehicles.
6. Consider adding multiple knapsack solver for initial solution if greedy solution fails, as well as a sanity check to check whether demand exceeds supply.
7. Consider adding in a clustering algorithm to break large problems into a `vector` of small problems.
8. Refactor genetic algorithm to use a struct


text:
# yang-js

YANG parser and composer

Super light-weight and fast. Produces adaptive JS objects bound by
YANG schema expressions according to
[RFC 6020](http://tools.ietf.org/html/rfc6020)
specifications. Composes dynamic YANG schema expressions by analyzing
arbitrary JS objects.

  [![NPM Version][npm-image]][npm-url]
  [![NPM Downloads][downloads-image]][downloads-url]

```coffeescript
Yang = require 'yang-js'
schema = """
  container foo {
    leaf a { type string; }
    leaf b { type uint8; }
  }
  """
model = (Yang schema) {
  foo:
    a: 'apple'
    b: 10
}
model.on 'update', (x) -> # do something with 'x'
```

## Installation

```bash
$ npm install yang-js
```

When using with the web browser, grab the *minified* build inside
`dist/yang.min.js` (currently **~95KB**).

## Features

* Robust parsing
* Focus on high performance
* Extensive test coverage
* Flexible control logic binding
* Powerful XPATH expressions
* Isomorphic runtime
* Adaptive validations
* Dynamic schema generation
* Granular event subscriptions

Please note that `yang-js` is not a code-stub generator based on YANG
schema input. It directly embeds YANG schema compliance into ordinary
JS objects as well as generates YANG schema(s) from oridnary JS
objects.

## Quick Start

Here's a quick example for using this module in coffeescript:

```coffeescript
Yang = require 'yang-js'
schema = """
  container foo {
    leaf a { type string; }
    leaf b { type uint8; }
  }
  """
model = Yang.parse(schema).eval {
  foo:
    a: 'apple'
    b: 10
}
```

The example above uses the *explict* long-hand version of using this
module, which uses the [parse](./src/yang.litcoffee#parse-schema)
method to generate the [Yang expression](./src/yang.litcoffee) and
immediately perform an [eval](./src/yang.litcoffee#eval-data-opts)
using the [Yang expression](./src/yang.litcoffee) for the passed-in JS
data object.

Since the above is a common usage pattern sequence, this module also
provides a *cast-style* short-hand version as follows:

```coffeescript
model = (Yang schema) {
  foo:
    a: 'apple'
    b: 10
}
```

It is functionally equivalent to the *explicit* version but provides
cleaner syntactic expression regarding how the data object is being
*cast* with the `Yang` expression to get back a new schema-driven
object.

Once you have the `model` instance, you can directly interact with its
properties and see the schema enforcement and validations in action.

As the above example illustrates, the `yang-js` module takes a
free-form approach when dealing with YANG schema statements. You can
use **any** YANG statement as the top of the expression and
[parse](./src/yang.litcoffee#parse-schema) it to return a
corresponding YANG expression instance. However, only YANG expressions
that represent a data element will
[eval](./src/yang.litcoffee#eval-data-opts) to generate a new
[Model](./src/model.litcoffee) instance.

## Reference Guides

- [Getting Started Guide](./TUTORIAL.md)
- [Using YANG with Express](http://github.com/corenova/yang-express) (external)
- [Coverage Report](./test/yang-compliance-coverage.md)

## API

Below are the list of methods provided by the `yang-js` module. You
can click on each method entry for detailed info on usage.

### Main module
- [parse (schema)](./src/yang.litcoffee#parse-schema)
- [compose (data)](./src/yang.litcoffee#compose-data-opts)
- [resolve (name)](./src/yang.litcoffee#resolve-from-name)
- [require (name)](./src/yang.litcoffee#require-name-opts)
- [register ()](./src/yang.litcoffee#register-opts)

### Yang instance
- [bind (obj)](./src/yang.litcoffee#bind-obj)
- [eval (data)](./src/yang.litcoffee#eval-data-opts)
- [extends (schema)](./src/yang.litcoffee#extends-schema)
- [locate (ypath)](./src/yang.litcoffee#locate-ypath)
- [toString ()](./src/yang.litcoffee#tostring-opts)
- [toObject ()](./src/yang.litcoffee#toobject)

### Model instance
- [on (event)](./src/model.litcoffee#on-event)
- [in (uri)](./src/model.litcoffee#in-uri)

## Examples

**Jukebox** is a simple example YANG module extracted from
[RFC 6020](http://tools.ietf.org/html/rfc6020). This example
implementation is included in this repository's [example](./example)
folder and exercised as part of the test suite. It demonstrates use of
the [register](./src/yang.litcoffee#register) and
[require](./src/yang.litcoffee#require-name-opts) facilities for
loading the YANG schema file and binding various control logic
behavior.

 - [YANG Schema](./example/jukebox.yang)
 - [Schema Bindings](./example/jukebox.coffee)

**Promise** is a resource reservation module implemented for
[OPNFV](http://opnfv.org). This example implementation is hosted in a
separate GitHub repository
[opnfv/promise](http://github.com/opnfv/promise) and utilizes
`yang-js` for the complete implementation. It demonstrates use of
multiple YANG data models in modeling complex systems. Please be sure
to [check it out](http://github.com/opnfv/promise) to learn more about
advanced usage of `yang-js`.

## Tests

To run the test suite, first install the dependencies, then run `npm
test`:
```
$ npm install
$ npm test
```

Also refer to [Compliance Report](./test/yang-compliance-coverage.md)
for the latest [RFC 6020](http://tools.ietf.org/html/rfc6020) YANG
specification compliance. There's also **active** effort to support
the latest **YANG 1.1** draft specifications. You can take a look at
the *mocha* test suite in the [test](./test) directory for compliance
coverage unit-tests and other examples.

## License
  [Apache 2.0](LICENSE)

This software is brought to you by
[Corenova Technologies](http://www.corenova.com). We'd love to hear
your feedback.  Please feel free to reach me at<EMAIL_ADDRESS>anytime with questions, suggestions, etc.

[npm-image]: https://img.shields.io/npm/v/yang-js.svg
[npm-url]: https://npmjs.org/package/yang-js
[downloads-image]: https://img.shields.io/npm/dt/yang-js.svg
[downloads-url]: https://npmjs.org/package/yang-js

repository: ramukima/yang-js

repo_name: ramukima/yang-js


text:
English | [简体中文](./README.md)

------------------------------------------------------------------------------------------
[![PyPI - PaddleNLP Version](https://img.shields.io/pypi/v/paddlenlp.svg?label=pip&logo=PyPI&logoColor=white)](https://pypi.org/project/paddlenlp/)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/paddlenlp)](https://pypi.org/project/paddlenlp/)
[![PyPI Status](https://pepy.tech/badge/paddlenlp/month)](https://pepy.tech/project/paddlenlp)
![python version](https://img.shields.io/badge/python-3.6+-orange.svg)
![support os](https://img.shields.io/badge/os-linux%2C%20win%2C%20mac-yellow.svg)
![GitHub](https://img.shields.io/github/license/paddlepaddle/paddlenlp)

## News

* [2021-06-07] **NLP Live Course** from Baidu has started!🔥🔥🔥 Click [HERE](https://aistudio.baidu.com/aistudio/course/introduce/24177) to join us!
* [2021-06-04] [ERNIE-Gram](https://arxiv.org/abs/2010.12148) pretrained model has been released! Install v2.0.2 to try it.
* [2021-05-20] PaddleNLP 2.0 has been officially relealsed! :tada: For more information please refer to [Release Note](https://github.com/PaddlePaddle/PaddleNLP/releases/tag/v2.0.0).

## Introduction

**PaddleNLP** is a powerful NLP library with **Awesome** pre-trained Transformer models and easy-to-use interface, supporting wide-range of NLP tasks from research to industrial applications.

* **Easy-to-Use API**
  - The API is fully integrated with PaddlePaddle 2.0 high-level API system. It minimizes the number of user actions required for common use cases like data loading, text pre-processing, awesome transfomer models, and fast inference, which enables developer to deal with text problems more productively.

* **Wide-range NLP Task Support**
  - PaddleNLP support NLP task from research to industrial applications, including Lexical Analysis, Text Classification, Text Matching, Text Generation, Information Extraction, Machine Translation, General Dialogue and Question Answering etc.

* **High Performance Distributed Training**
  -  We provide an industrial level training pipeline for super large-scale Transformer model based on **Auto Mixed Precision** and Fleet distributed training API by PaddlePaddle, which can support customized model pre-training efficiently.

## Installation

### Prerequisites

* python >= 3.6
* paddlepaddle >= 2.1

More information about PaddlePaddle installation please refer to [PaddlePaddle's Website](https://www.paddlepaddle.org.cn/install/quick?docurl=/documentation/docs/zh/install/conda/linux-conda.html).

### PIP Installation

```
pip install --upgrade paddlenlp
```

## Easy-to-use API

### Transformer API: Awesome Pre-trained Model Ecosystem

We provide **15** network architectures and **67** pretrained models. Not only includes all the SOTA model like ERNIE, PLATO and SKEP released by Baidu, but also integrates most of the high quality Chinese pretrained model developed by other organizations. We also welcome developer to contribute your Transformer models! 🤗

```python
from paddlenlp.transformers import *

ernie = ErnieModel.from_pretrained('ernie-1.0')
ernie_gram = ErnieGramModel.from_pretrained('ernie-gram-zh')
bert = BertModel.from_pretrained('bert-wwm-chinese')
albert = AlbertModel.from_pretrained('albert-chinese-tiny')
roberta = RobertaModel.from_pretrained('roberta-wwm-ext')
electra = ElectraModel.from_pretrained('chinese-electra-small')
gpt = GPTForPretraining.from_pretrained('gpt-cpm-large-cn')
```

PaddleNLP also provides unified API experience for NLP task like semantic representation, text classification, sentence matching, sequence labeling, question answering, etc.

```python
import paddle
from paddlenlp.transformers import ErnieTokenizer, ErnieModel

tokenizer = ErnieTokenizer.from_pretrained('ernie-1.0')
text = tokenizer('natural language understanding')

# Semantic Representation
model = ErnieModel.from_pretrained('ernie-1.0')
sequence_output, pooled_output = model(input_ids=paddle.to_tensor([text['input_ids']]))
# Text Classificaiton and Matching
model = ErnieForSequenceClassification.from_pretrained('ernie-1.0')
# Sequence Labeling
model = ErnieForTokenClassification.from_pretrained('ernie-1.0')
# Question Answering
model = ErnieForQuestionAnswering.from_pretrained('ernie-1.0')
```

For more pretrained model usage, please refer to [Transformer API](./docs/model_zoo/transformers.rst)

### Dataset API: Rich Dataset Integration and Quick Loading

```python
from paddlenlp.datasets import load_dataset

train_ds, dev_ds, test_ds = load_dataset("chnsenticorp", splits=["train", "dev", "test"])
```

For more dataset API usage please refer to [Dataset API](./docs/datasets.md).

### Embedding API: Quick Loading for Word Embedding

```python
from paddlenlp.embeddings import TokenEmbedding

wordemb = TokenEmbedding("fasttext.wiki-news.target.word-word.dim300.en")
wordemb.cosine_sim("king", "queen")
>>> 0.77053076
wordemb.cosine_sim("apple", "rail")
>>> 0.29207364
```

For more `TokenEmbedding` usage, please refer to [Embedding API](./docs/model_zoo/embeddings.md)

### More API Usage

- [Transformer API](./docs/model_zoo/transformers.rst)
- [Data API](./docs/data.md)
- [Dataset API](./docs/datasets.md)
- [Embedding API](./docs/model_zoo/embeddings.md)
- [Metrics API](./docs/metrics.md)

Please find more API Reference from our [readthedocs](https://paddlenlp.readthedocs.io/).

##  Wide-range NLP Task Support

PaddleNLP provide rich application examples covers mainstream NLP task to help developer accelerate problem solving.

### NLP Basic Task

- [Word Embedding](./examples/word_embedding/)
- [Lexical Analysis](./examples/lexical_analysis/)
- [Language Model](./examples/language_model/)
- [Semantic Parsing (Text to SQL)](./examples/text_to_sql):star:

### NLP Core Technique

- [Text Classification](./examples/text_classification/)
- [Text Matching](./examples/text_matching/)
- [Text Generation](./examples/text_generation/)
- [Semantic Indexing](./examples/semantic_indexing/)
- [Information Extraction](./examples/information_extraction/)

### NLP Industrial Applications

- [Sentiment Analysis](./examples/sentiment_analysis/skep/):star2:
- [General Dialogue System](./examples/dialogue/)
- [Machine Translation](./examples/machine_translation/)
- [Simultaneous Translation](././examples/simultaneous_translation/)
- [Machine Reading Comprehension](./examples/machine_reading_comprehension/)

### Extented Application

- [Text Knowledge Linking](./examples/text_to_knowledge/):star2:
- [Machine Reading Comprehension](./examples/machine_reading_comprehension)
- [Model Compression](./examples/model_compression/)
- [Text Graph Learning](./examples/text_graph/erniesage/)
- [Time Series Prediction](./examples/time_series/)

## Tutorials

Please refer to our official AI Studio account for more interactive tutorials: [PaddleNLP on AI Studio](https://aistudio.baidu.com/aistudio/personalcenter/thirdview/574995)

* [What's Seq2Vec?](https://aistudio.baidu.com/aistudio/projectdetail/1283423) shows how to use simple API to finish LSTM model and solve sentiment analysis task.

* [Sentiment Analysis with ERNIE](https://aistudio.baidu.com/aistudio/projectdetail/1294333) shows how to exploit the pretrained ERNIE to solve sentiment analysis problem.

* [Waybill Information Extraction with BiGRU-CRF Model](https://aistudio.baidu.com/aistudio/projectdetail/1317771) shows how to make use of Bi-GRU plus CRF to finish information extraction task.

* [Waybill Information Extraction with ERNIE](https://aistudio.baidu.com/aistudio/projectdetail/1329361) shows how to use ERNIE, the Chinese pre-trained model improve information extraction performance.

* [Use TCN Model to predict COVID-19 confirmed cases](https://aistudio.baidu.com/aistudio/projectdetail/1290873)

## Community

### Special Interest Group (SIG)

Welcome to join [PaddleNLP SIG](https://iwenjuan.baidu.com/?code=bkypg8) for contribution, eg. Dataset, Models and Toolkit.

### Slack
To connect with other users and contributors, welcome to join our [Slack channel](https://paddlenlp.slack.com/).

### QQ
Join our QQ Technical Group for technical exchange right now! ⬇

## ChangeLog

For more details about our release, please refer to [ChangeLog](./docs/changelog.md)

## License

PaddleNLP is provided under the [Apache-2.0 License](./LICENSE).

repository: jiaqianjing/ChineseBERT-Paddle

repo_name: jiaqianjing/ChineseBERT-Paddle


text:
# Moderated User testing Survey

The questions here are to be answered by the person who was assisting the user moderated user testing.

* How much time did the user take to install the bot ?

* How much time did the user use the bot ?

* Was the bot able to integrate properly with your class / slack channels ?

* How many classes / slack channels did the bot integrate with ? Were there any classes / slack channel where the bot did not work ?

* Was the bot able to identify the information that is helpful to the user ? If not , please specify what did the bot miss out on.

* Did the user miss any notification from the bot ?

* Did the bot crash while user was using it ? If yes, was there any particular action that user did that might have acted as a trigger ?

* Was diagnostic data being collected while the test was going on ?

* Any comments that the user gave ?

repository: nikhilanathani/Classroom-Bot

repo_name: nikhilanathani/Classroom-Bot


text:
# ResumeReviewer
ResumeReviewer will prepare students for resume based interview rounds during Placements by highlighting critical topics and suggesting relevant questions based on past interviews.

The major parts of ResumeReviewer are -
1. Resume parser
2. Resume correction
3. Context modifications
4. Impact understanding
5. Key highlights
6. Interview question suggestion
7. Interface design

Most of the above goals are subjective to change according to feasibility and general feedback from other developers. Given KWOC will run for 4 weeks, I am hoping to get the first, second, fifth and sixth points to be covered, even if they might not be production level. So the timeline would approximately look like -
- [ ] Resume parser - 7th to 13th December
- [ ] Resume correction - 14th to 20th December
- [ ] Key highlights - 21st to 27th December
- [ ] Interview question suggestion - 28th to 2nd Jan

Tech stack will be predominantly Python based, and powered by open source libraries (unless using a paid API is the only option). Please keep checking the README for further updates, and join the [Slack channel](https://join.slack.com/t/resumereviewerkwoc/shared_invite/enQtODUxNTQ2NDYyODAwLTRjZmNkZWM4NGVmNTdlMmRmMzBkMWY3NmUzNDk3OTYyNzdkNDY3NTg0OWU0MzkxYTc5ZGU4NWM1NmUxYmQ3YjE) for further discussion regarding key development decisions.