text:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Webdioxide</title>
    <description>A blog built by Ishwerdas Studio
</description>
    <link>http://0.0.0.0:8080/</link>
    <atom:link href="http://0.0.0.0:8080/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Sun, 06 May 2018 15:06:59 +0000</pubDate>
    <lastBuildDate>Sun, 06 May 2018 15:06:59 +0000</lastBuildDate>
    <generator>Jekyll v3.5.0</generator>

      <item>
        <title>A Beginner's Guide to Using CSS Grids.</title>
        <description>
You know what, I am a big fan of Richard Fyenman's technique  of reducing everything to freshman level. I believe as he did, that if you are unable to explain a concept in simplest words you don't really understand it.

Addition of Grids in CSS spec is something that would change every course that's taught on web development. CSS Grids is relatively new but as fundamental a concept as say box model. So let's try teaching it without assuming any CSS expertise from audience.

What are grids?

Grid in its most simplest terms is rows and columns. Horizontal and vertical lines that divide the page, canvas or in our context screen into equal boxes. Grids provide rhythm to our design. Human mind loves symmetry, so when it sees symmetry it likes symmetry and hence finds a symmetric design aesthetically pleasing a.k.a good looking.

You can learn more about grids here

Before Grids were introduced into CSS

In the ancient times (a year ago) we did not have grids in CSS. In the pre-historic times (couple of years ago) we had to rely on 3rd party grid frameworks for building grid based layouts. These frameworks bloated our markup (html) or added extra burden on the site. Then came the flexbox. It somewhat allowed us to have grids but that was more of a hack than a solution. Using flexbox as a grid layout can be arguably considered as an improper use of flexbox. Well, we don't have to argue on that anymore because we have grids built in CSS Now.

Shut up! and show me how

Step 1: Make a container

Before you can add rows and columns, you need a container to contain those rows and columns. You do that by adding display:grid to your container element.

&lt;main class="container"&gt;
  &lt;div class='cell'&gt; 1 &lt;/div&gt;
  &lt;div class='cell'&gt; 2 &lt;/div&gt;
  &lt;div class='cell'&gt; 3 &lt;/div&gt;
  &lt;div class='cell'&gt; 4 &lt;/div&gt;
  &lt;div class='cell'&gt; 5 &lt;/div&gt;
  &lt;div class='cell'&gt; 6 &lt;/div&gt;
  &lt;div class='cell'&gt; 7 &lt;/div&gt;
  &lt;div class='cell'&gt; 8 &lt;/div&gt;
  &lt;div class='cell'&gt; 9 &lt;/div&gt;
  &lt;div class='cell'&gt; 10 &lt;/div&gt;
  &lt;div class='cell'&gt; 11 &lt;/div&gt;
  &lt;div class='cell'&gt; 12 &lt;/div&gt;
  &lt;div class='cell'&gt; 13 &lt;/div&gt;
  &lt;div class='cell'&gt; 14 &lt;/div&gt;
  &lt;div class='cell'&gt; 15 &lt;/div&gt;
  &lt;div class='cell'&gt; 16 &lt;/div&gt;
&lt;/main&gt;

.container {
    display:grid;
  }

See the Pen Beginner's Guide to CSS Grids - Step 1 by Inder Singh (@inderpreetsingh) on CodePen.

Step 2: Create Rows and Columns

Now we have grid, let's tell it the number and size of columns.

.container {
  display:grid;

  /* Create 4 columns of 100px each */
  grid-template-columns:100px 100px 100px 100px;

}

So as its obvious from the code, you use grid-template-columns to create columns and the extra columns (5 - 16) automatically gets arranged into rows. Pretty neat, eh?

This property of CSS grids to automatically create rows for you when you don't explicitly define those rows in your css, that's called implicit grid. Not just rows, implicit grid can also add implicit columns for you. By default the property grid-auto-flow is row, however if you change it to column instead of creating implicit rows it would create implicit columns.

In contrast, the grid that we define in css that's explicit grid.

Let's add the rows now , explicitly.

.container {
  display:grid;
  grid-template-columns:100px 100px 100px 100px;

  /* Create 4 rows, first one with height of 50px
   * &amp; rest of them adjusting their height to content
   */
  grid-template-rows: 50px auto 100px;
 }

See the Pen Beginner's Guide to CSS Grids - Step 2.1 by Inder Singh (@inderpreetsingh) on CodePen.

Just like grid-template-columns , grid-template-rows add explicit rows to grid. The auto value makes it adjust the height of content. Still cells 14 - 16 are in an implicit row. There's a way you can target implicit rows in css called grid-auto-rows. Let's try that.

.container {
  display:grid;
  grid-template-columns:100px 100px 100px 100px;
  grid-template-rows: 50px auto 100px;

  grid-auto-rows: 150px;
}

See the Pen Beginner's Guide to CSS Grids - Step 2.2 by Inder Singh (@inderpreetsingh) on CodePen.

Step 3: Add Gutter

Beside rows and columns, most grids have third thing called gutters. Gutters are the gap between 2 adjacent rows or 2 adjacent columns.

grid-column-gap and grid-row-gap to the rescue.

.container {
  display:grid;
  grid-template-columns:100px 100px 100px 100px;
  grid-template-rows: 50px auto 100px;
  grid-auto-rows: 150px;

  grid-column-gap:20px;
  grid-row-gap:20px;
}

If you want same gap on rows as in columns, there's a shorthand that you can use called grid-gap.

.container {
  display:grid;
  grid-template-columns:100px 100px 100px 100px;
  grid-template-rows: 50px auto 100px;
  grid-auto-rows: 150px;

  grid-gap:20px;
}

See the Pen Beginner's Guide to CSS Grids - Step 3 by Inder Singh (@inderpreetsingh) on CodePen.

By this knowledge you can create a basic grid, and using media queries even a flexible grid for yourself. However that's just surface of what grids have to offer. There are whole bunch of other properties that you can use to manipulate grids. If time allowed, I will create more posts about it and link them down under.

</description>
        <pubDate>Fri, 07 Jul 2017 18:38:19 +0000</pubDate>
        <link>http://0.0.0.0:8080/css/Beginners-Guide-To-CSS-Grids.html</link>
        <guid isPermaLink="true">http://0.0.0.0:8080/css/Beginners-Guide-To-CSS-Grids.html</guid>

        <category>css</category>

      </item>

      <item>
        <title>What are closures?.</title>
        <description>
Work in progress

Javascript is weirdly awesome.Closures in javascript are one of those things that would make your brain swoon over its weirdness, over it's mild yet intriguing complexity. Closure is a way to remember function's variables even after that function has finished running.

Let's get into code

function greet(greeting) {

  function noun(name) {
    return greeting + "  " + name +"!";
  }

  return noun;
}

Now the noun that's returned from greet is said to have closure over variable greeting. In simple terms it will remember whatever we pass as greeting to greet(greeting). Let's clarify that with an example.

/**
the noun that's returned from greet remembers the greeting that we pass to greet.
We are storing that noun inside different variables here.
*/
var helloGreet = greet('hello');
var holaGreet = greet('hola');

/**
Now helloGreet and holaGreet are kind of noun functions in disguise.
So we can pass them their intended argument a.k.a the variable `name` to it.
*/

helloGreet('inder'); // hello inder
holaGreet('gaurav'); // hola gaurav

A bit confusing isn't it?

It's supposed to be. Don't worry practice them a bit, and stay tuned for more explanation.

</description>
        <pubDate>Thu, 13 Oct 2016 07:37:22 +0000</pubDate>
        <link>http://0.0.0.0:8080/javascript/what-are-closures</link>
        <guid isPermaLink="true">http://0.0.0.0:8080/javascript/what-are-closures</guid>

        <category>javascript</category>

      </item>

      <item>
        <title>History behind typeof null equals object.</title>
        <description>
Introduction

Javascript is undoubtedly bit weird at times. However for me, that's what makes it special.
Javascript has 6 or 7 (depending upon how you count) primitive types. They are

string

number

boolean

object

symbol (new in es6)

Null and undefined

Now if you have met javascript before, you know that her variables don't have a type. It's the value that has a type. To find that type we use typeof.

var u;
typeof u; //undefined

var a = "inder";
typeof a;  // string

var b =  true;
typeof b; //boolean

However if you run typeof on a null value, it returns object, something you won't expect from a primitive type.

var i = NULL;
typeof i; //object

This is a bug that exists since the beginning of javascript. The reason that this bug exists is simple. Each javascript value has a type tag. First 1-3 bits of each value are reserved for it's type. The type tags for different types were as follows: -

000 - object

001 - int

010 - double

100 - string

110 - boolean

To define undefined they used a special number 2 -30

To define null NULL pointer was used.

After the type tage folows the actual value. typeof got confused between zeros of null pointer and 000 tag of object and thus the bug.

Why isn't this bug removed?

It would have been removed in EcmaScript 6, but the proposal got rejected because of a lot of old javascript code that relies on it. So for now, we are stuck with it.

</description>
        <pubDate>Fri, 07 Oct 2016 18:38:19 +0000</pubDate>
        <link>http://0.0.0.0:8080/javascript/why-typeof-null-returns-object-the-history</link>
        <guid isPermaLink="true">http://0.0.0.0:8080/javascript/why-typeof-null-returns-object-the-history</guid>

        <category>links</category>

      </item>

      <item>
        <title>Running My Meteor App on Android Device</title>
        <description>
Working in meteor is already super easy and a bliss. I have worked in meteor before, but this time, I wanted to use one of the best features of meteor that is making a cross platform application.
So the challenge here was to run and install my meteor app in my Xiaomi Redmi Note 3 Android (version Lollipop) phone.

Let's see how I did that.

1. Installing Meteor

Connect your computer with Internet and run this command in terminal

 curl https://install.meteor.com/ | sh

Linux curl will download meteor installation script and linux sh command is used to run that script.

2. Create new Meteor project

 meteor create piaoma

Meteor will create a project named piaoma having two folders Clients and Server and a package.json file. Explaining what these are about are out of scope of this post. You can anyway learn development in Meteor from https://guide.meteor.com/index.html

Now I wanted to run and install this project piaoma at my Android phone.
For this, I followed the Meteor guide https://guide.meteor.com/mobile.html#installing-prerequisites

To run your meteor application inside your android device, you need first to add android platform

 meteor add-platform android

But, it will require you to install some prerequisites including JDK (Java Development Kit) and Android Studio.

I am working in Ubuntu, so I preferred to use Ubuntu make as it installed JDK and Android Studio both easily just by using a few commands.

Add ubuntu make ppa first

 sudo add-apt-repository ppa:ubuntu-desktop/ubuntu-make

Update your system

 sudo apt-get update

Install Ubuntu make

 sudo apt-get install ubuntu-make

Run umake to install android

 umake android

Next step is Setting ANDROID_HOME and adding the tools directories to your PATH

If you see the guide, the path to Sdk that is to be put into ANDRIOD_HOME variable is ~/Library/Android/sdk, but Ubuntu-make made Android folder in my home folder and so the path that I had to store in ANDROID_HOME is "/home/shaina/Android/Sdk" , where 'shaina' is my username

export ANDROID_HOME="/home/shaina/Android/Sdk"

export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

I added above two lines in .bashrc file which resides in my home. To do that, just open the .bashrc file (I use vim as editor)

sudo vim ~/.bashrc

and add those lines at the last of the file.
Save and Quit

Then Reload .bashrc (by executing source ~/.bashrc)

 source ~/.bashrc

When I tried to run my project by

 cd ~/piaoma

 meteor run android-device

It asked me to install android-target: android 23 using SDK manager.
It is given in the hint, how to run sdk manager, as shown in screenshot below

Just go inside the Android/Sdk/tools and run android

 cd ~/Android/Sdk/tools

 ./android

Sdk manager dialog box opened up. Just select and install the SDK tools you require.

It is showing status installed in this screenshot as I just installed Android API 23.

Connect your phone before running the app again.

Connect your android device to your computer through USB.

Enable the USB debugging from Developer options settings into your android device. On Android 4.2 and higher, the Developer options screen is hidden by default. To make it visible, go to Settings &gt; About phone and tap Build number seven times. Return to the previous screen to find Developer options at the bottom.

(At my phone Xiaomi Redmi Note 3, nothing happened by tapping on Build Number seven times, after few searches, I came to know how to get to Developers options. Go to Settings &gt; About phone and tap MIUI version seven times. Go to Settings &gt; Additional Settings and you will find Developers Options. Open it and Enable USB debugging.)
Found this from http://xiaomiadvices.com/miui-7-enable-developer-options-and-usb-debugging-on-xiaomi-android-phones/

If you're developing on Ubuntu Linux, you need to add a udev rules file that contains a USB configuration for each type of device you want to use for development. In the rules file, each device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor} property.
Log in as root and create this file: /etc/udev/rules.d/51-android.rules.

 sudo vim /etc/udev/rules.d/51-android.rules

Use this format to add each vendor to the file:

SUBSYSTEM=="usb", ATTR{idVendor}=="2717", MODE="0666", GROUP="plugdev"

2717 is the vendorID of XIAOMI, you can search vendorID of your device online easily.

Now execute:

 sudo chmod a+r /etc/udev/rules.d/51-android.rules

Now run the app, Go to your project

 cd piaoma

 meteor run android-device

This will install and run your app into your android device.

Thank you :)

</description>
        <pubDate>Mon, 29 Aug 2016 18:38:19 +0000</pubDate>
        <link>http://0.0.0.0:8080/meteor-app-on-android-device</link>
        <guid isPermaLink="true">http://0.0.0.0:8080/meteor-app-on-android-device</guid>

        <category>links</category>

      </item>

      <item>
        <title>Virtual Reality Arriving Fast</title>
        <description>

Microsoft Hololens experience showcase opens for developers in New York.

Facebook is hiring a News and Media Content Lead for Oculus Rift.

A GearVR puzzle game E2per Review by VRift

Google reveals the plans for new VR headset and motion controller.

The WaveVR raises $2.5 million to mix music and virtual reality

If you have ever heard such news, you would be wondering that every big company is stepping into 3-Dimensional VR interfaces. They are making hardware like head sets, apps, platforms to develop apps, having conferences, funding, and a lot.

So, first let's learn, what is this all hype about?

What is that we call Virtual Reality?

Virtual Reality is a computer technology that simulates user's presence and environment for interactions that includes, sight, touch, hearing and smell, to create a lifelike experience.

How is it evolved?

Remember that red and green glasses we used to see 3D images in our childhood? Those are known as Anaglyph 3D glasses which were used to create stereoscopic 3D effect. When views through the color-coded anaglyph glasses, each of the two differently filtered colored images reaches the eye it's intended for, revealing a 3D image in front of your eyes.

After Anaglyph glasses, polarized 3D glasses came into use, to watch 3D animated movies or 3D games. In polarized 3D system, two images are projected superimposed onto the same screen and polarization glasses are used to create the illusion of 3D images.

Now, to have a super interactive virtual reality experience, companies are making interfaces like Oculus Rift, Samsung GearVR etc, but these are not so affordable yet.
Google has also made a low level alternative to Oculus Rift at very affordable rate, known as Google Cardboard, so that everyone can experience VR today.

How we see things in 3D around us in real world?

As our eyes sit side by side, each eye captures a slightly different view of an object. This is called binocular vision. When signals from the two eyes reach the brain, they are superimposed and processed into a single picture with depth. As a result, we get a 3D picture and are able to judge distances well.

This is the concept from where the virtual reality get inspired from.

Developers of VR apps make two different images or models of same object placed at angles that are slightly different from each other, one for each eye. Then we have to use a VR hardware like Google Cardboard or Oculus Rift to have 3D view of that image or model.

From all this above, we come to know that the next interface that is approaching fast is VR interfaces. Developers will be in need to make the sites and apps responsive for these interfaces too, as today they do for mobiles and tablets.

So to have a good taste of developing VR apps, I used A-frame.

What is A-frame?

A-frame is an open-source framework for creating 3D and virtual reality experiences on the web. It's like the bread to your sandwich, which will provide you with some ready made entities that you can use to make interesting applications. VR scenes created by A-frame work across desktop, oculus rift, mobiles, Google cardboard with just HTML.

A-frame is powered by three.js and WebVR. Three.js is a javascript library that is used to create 3D scenes and WebVR is another javascript API that provides access to the VR devices such as Oculus Rift, Google Cardboard etc.

To make a 3D scene in a-frame, you just need to make an HTML file, add a-frame script in the &lt;head&gt; and add entities you want in the &lt;body&gt;.

For Example, to make a box, the code in a-frame will look like this.

&lt;html&gt;
&lt;head&gt;
&lt;script src="aframe.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;a-scene&gt;
  &lt;a-box position="0 1 0" height="1" width="1"&gt;&lt;/a-box&gt;
&lt;/a-scene&gt;
&lt;/body&gt;
&lt;/html&gt;

</description>
        <pubDate>Mon, 22 Aug 2016 18:38:19 +0000</pubDate>
        <link>http://0.0.0.0:8080/vr/virtual-reality-and-aframe.html</link>
        <guid isPermaLink="true">http://0.0.0.0:8080/vr/virtual-reality-and-aframe.html</guid>

        <category>links</category>

      </item>

      <item>
        <title>Arrays Using Javascript</title>
        <description>
**Data Structures using Javascript - Arrays **

In programming we have something called variables. You can think of a variable as a named box and you can put stuff in it. Sometimes we need to put a bunch of related boxes in a bigger box, that's where arrays come into scene.

Arrays can also be thought of as list containing homogenous list items. By homogenous I mean, of the same datatype.

Create a new array

Creating an array is simple. Syntax is almost similar to that of creating a variable, just that a list of comma separated items are enlosed in square brackets [  ]

var cars = ['lambohrgini' , 'audi' , 'mercedes' , 'datsun'];
var years = [1990, 1992, 1985, 1984, 1947] ;

You can also create array using new Array() method. To do that

var arr = new Array(1,2,3,4);

Accessing a particular element of array (index)

Each element of array has an index. The indices start from 0.  You can access each element of array using arrayname followed by it's index in square brackets.

var cars = ['lambohrgini' , 'audi' , 'mercedes' , 'datsun'];
var years = [1990, 1992, 1985, 1984, 1947] ;
alert(cars[0]); // will alert lambohrgini
alert(cars[2]); // will alert mercedes

In javascript we can have named indices too, which is discussed later.

There are three basic operations that one can perform on array

Traversing an array

Insert an element into array

Remove an element from array

Traversing an array

Traversing an array means, visiting each element of array one by one and then performing a certain operation on it.

We need to use a loop to access each element of array. There are bunch of loops in Javascript, we will be using basic for loop for traversing. For loops exists in almost all the high level languages, so you can make use of this guide even if you are not that into Javascript.

var friends = ['jane', 'mary', 'valerie', 'stephanie', 'carol']
for(i = 0; i &lt; 5; i++) {
    alert(friends[i]);
}

What for loops does is, it initializes a variable named i to 0, and as long as i is less than five &lt; 5 , it keeps increasing it by 1 i++. This way the statement inside for loop runs 5 times, showing each element of array in a popup.

This syntax is fine when we know the legnth of array (5 here) .In case the length of array is changing or we are not yet sure about how many elements we would put in it, then we can use a special javascript method called .length to access the length of array.

var friends = ['jane', 'mary', 'valerie', 'stephanie', 'carol'];

for(i = 0; i &lt; friends.length; i++) {
    alert(friends[i]);
}

Another simpler way to traverse arrays in javascript is to use for .. in loop.

var friends = ['jane', 'mary', 'valerie', 'stephanie', 'carol']

for(i in friends) {
    alert(friends[i]);
}

Insert an element at end or array

Inserting an element at end of array is the simplest. Just find the length of array. Now you should note here that length of array is always one greater than highest index. So in following array

var arr = [45,46,47,48,49];

Highest index value is 4, as arr[4] is 49 but arr.length is 5 as there are 5 elements in array. So if we want to add an element at end of this array, we need to do it at arr[5] which can also be written as arr[arr.length]. So to insert an element at end of array, allw we have to do is :-

var arr = [45,46,47,48,49];
arr[arr.length] = 50; // which is same ass arr[5] = 50;

alert(arr); // will show 45,46,47,48,49,50

The above funciton was a bit general that can be used in any other programming language. A more javascript-ish way is to use .push() method.

var arr = [45,46,47,48,49];
arr.push(50);

alert(arr); // will show 45,46,47,48,49,50

Insert an element at any index

Inserting an element at beginning or mid of array is a tiny bit tricky. Because say if you want to add an element at 3rd index , then you have to move all the elements that come after 3rd element one index ahead.

Let's first setup our array and variables. We need an array, a new value to be inserted into that array, and a position at which the array will be inserted.

var fruits = ['apple','orange', 'kiwi', 'banana', 'mango'];
var newValue = 'pear';
var insPos = 2;
//we will add a new fruit (pear) at fruits[2], a.k.a in place of 'kiwi'

Now we need to know the highest index value of an array. As discussed earlier array.length is always 1 greater than highest index value. We can also say that highest index value is 1 less than length of an array.

var fruits = ['apple','orange', 'kiwi', 'banana', 'mango'];
var newValue = 'pear';
var insPos = 2; //insert Position
//we will add a new fruit (pear) at fruits[2], a.k.a in place of 'kiwi'

highestIndex = fruits.length - 1;

Our array and all other variables are now prepared. Next step would be to move each element after insPos one index ahead.We start from last element of array and move upwards till insert position.

for(i = highestIndex; i &gt;=insPos; i--){
    fruits[i+1] = fruits[i];
}

Now only thing left is to insert element at required position.

    fruits[insPos] = newValue;

The complete code now looks like.

var fruits = ['apple','orange', 'kiwi', 'banana', 'mango'];
var newValue = 'pear';
var insPos = 2;
//we will add a new fruit (pear) at fruits[2], a.k.a in place of 'kiwi'

highestIndex = fruits.length - 1;

for(i = highestIndex; i &gt;=insPos; i--){
    fruits[i+1] = fruits[i];
}

fruits[i] = newValue;
alert(fruits);

Hurray! now we have inserted an element into array.

Removing an element from end of array.

I have been unable to find a general way to remove an element from array in javascript. If you know one, let me know in comments or you can also send a PR to this article. So we are going to use Javascript's .pop() method.

var arr = [45,46,47,48,49];
arr.pop();

alert(arr); // will show 45,46,47,48

Removing an element from any index.

For removing an element from a certain index we will use .splice() method of javascript. Which removes the array at an index with single line of code. If that function was not available we would have deleted an array item from the array and then moved all the next elements one index value back. But as I don't know a general method of deleting some variable or array element in javascript, I will use built-in method splice to have same effect.

var arr = [45,46,47,48,49];
var remPos = 2;
arr.splice(remPos, 1);

alert(arr); // will show 45,46,48,49

So that completes guide to a very basic data structure called arrays. Array is a data structure that we will use to create other complex datastructures like matrices and graphs and so on. Stay tuned…

</description>
        <pubDate>Wed, 17 Aug 2016 18:38:19 +0000</pubDate>
        <link>http://0.0.0.0:8080/javascript/data-structures-using-javascript-arrays.html</link>
        <guid isPermaLink="true">http://0.0.0.0:8080/javascript/data-structures-using-javascript-arrays.html</guid>

        <category>links</category>

      </item>

      <item>
        <title>Network security notes</title>
        <description>
Below are the list of links about recent topics that I have been studying and teaching. For GNDPC, students here are your notes for second sessional exams ;).

VPN

All about VPN

VPN Protocol Basics

Internet Key Exchange

IDS

All about IDS

Teardrop Attack

DOS Attack

</description>
        <pubDate>Mon, 21 Mar 2016 18:38:19 +0000</pubDate>
        <link>http://0.0.0.0:8080/links/notes.html</link>
        <guid isPermaLink="true">http://0.0.0.0:8080/links/notes.html</guid>

        <category>links</category>

      </item>

      <item>
        <title>Why we need Intrusion Detection System?</title>
        <description>
Antiviruses and Firewalls are the gatekeepers, they try to keep enemy out but what if enemy has already entered? What to do of the enemy within?

Any country like India would understand the need of having, at least, two armed forces: one that stays on borders and tries to keep the enemy out and another that looks at the enemy within. Indians have the third largest standing army but no matter how strong it is, still intruders/terrorists get inside through the borders and wreak havoc. 26/11 and recent Gurdaspur Firings are good examples of breaches in Indian border security.

Similarly, we may have a strict firewall and a very advanced AntiVirus, still all you get is an illusion of security. Now, I am not saying that they are not useful but it's foolish to expect that no one will ever bypass your security.

Firewalls have little doors and windows inside them, the windows through which you are able to access the internet, watch a video or send an email. Antiviruses are good enough to detect only the viruses, that are already known to them and the weakest link in your security are humans. Humans that have emotions, prejudices, egoes and are prone to social engineering.

So while the Firewalls and Antiviruses try to keep the bad stuff out of the door, Intrusion Detection Systems try to detect malicious activity that has already entered the system. Intrusion Detection systems start when the system has failed to keep the bad stuff away.

So how do intrusion detection systems work?

IDSs try to check for an activity that could be thought of as malicious and makes a guess if it's an intrusion or not. For example there's an IP that's hitting at multiple ports, now why would someone do that?

The only obvious answer we can think of is someone trying to check which of the ports is open. Hitting all ports is similar to someone trying to open all the doors in hallway, obviously a strange activity that deserves attention. However is it really an intrusion or not? The answer would be we can't be 100% sure. Here's the point where tuning comes in. Intrusion Detection System is as much as a technology as much as it is a policy. Suppose we have configured our IDS initially and for the first week it gave way too many alerts, most of them being false positives, we would go back to configuration files and tune it, change it until we have the perfect balance.

</description>
        <pubDate>Fri, 22 Feb 2013 18:38:19 +0000</pubDate>
        <link>http://0.0.0.0:8080/lectures/why-intrusion-detection-system.html</link>
        <guid isPermaLink="true">http://0.0.0.0:8080/lectures/why-intrusion-detection-system.html</guid>

        <category>lectures</category>

      </item>

      <item>
        <title>Virtual Private Network</title>
        <description>
There is no one right definition of democracy, but if we were to comprehend on what it would look like? This world wide web, The Internet would be the most example. No surprise that governments and authoritative bodies freak out and try to control and limit what we, the netizens can freely access. However, we don't have to succumb to the atrocities they commit. We can free ourselves from the cages of censorships and firewalls as long as we have the messiah that they call Virtual Private Network.

Basics

There are two types of networks:-

Public Networks

Private Networks

Public Network just like our internet is available to everyone, whereas Private Network has restricted access to only a few. An example of private network would an office network or a college network.

We do not have any control over the wires, router and other hardware that makes up the internet. So while surfing a public network there's a possibility that someone could read our private conversations. Private networks provide that security and privacy but they are not scalable and the cost of establishing a private network is high.

Virtual Private Network acronymed as VPN is a best of both worlds situation. It's private network that runs on public network. It uses the infrastructure of public network to provide the functionality of private network.

A very good analogy to explain the basics of Public Networks, Private Networks and VPNs is given at howstuffworks.com

Features

Features and benefits of VPN depends upon what VPN software or what VPN service that you are using. However an average VPN would 3 inherent features Security, Scalability &amp; Reliability.

A VPN provides security by protecting your data from intruders. If your data is on public network it does not mean it's up for public use.

VPN is as scalable as a public network a.k.a anyplace where internet is available. You can connect to your office network from around the world. You can work for international companies while sitting in the comfort of your home.

A VPN has to be reliable , there should be no disruption to the users. In many cases VPN arguably provides more reliability than a private network. A private network has to be managed internally by network administrators, so it's reliability depends upon the skills of your network administrators. However Internet being a public network is managed by thousands of companies and ISPs. It's in their good interest to provide reliability and seamless service.

Types of VPN

There are two types of VPN Remote Access VPN &amp; Site to Site VPN.

Remote Access VPN

When a single user connects to a private network through VPN remotely is called Remote Access VPN. The user may be at home, vaccationing in himalayas or travelling in train, she can connect to private network as she is in office. It is also called Virtual Private Dial Up network . User connects to a special hardware called Network Access Server (NAS) also called as Media Server or Remote Access Server. NAS handles the authentication and authorization process, after which user is granted an entry to private network. Now enterprises can handle all the setup themselves or hire an Enterprise Service Provider to do that for them.

Site to Site VPN

When we connet two private networks together it's called Site to Site VPN. When both sites belong to single company then it's called Intranet Site to Site VPN whereas when both sites belong to different companies it's called Extranet Site to Site VPN

More at howstuffworks.com

</description>
        <pubDate>Fri, 22 Feb 2013 18:38:19 +0000</pubDate>
        <link>http://0.0.0.0:8080/lectures/virtual-private-network.html</link>
        <guid isPermaLink="true">http://0.0.0.0:8080/lectures/virtual-private-network.html</guid>

        <category>lectures</category>

      </item>

  </channel>
</rss>


text:
package parquet.thrift;

import java.nio.ByteBuffer;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TField;
import org.apache.thrift.protocol.TList;
import org.apache.thrift.protocol.TMap;
import org.apache.thrift.protocol.TMessage;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TSet;
import org.apache.thrift.protocol.TStruct;

abstract class ParquetProtocol extends TProtocol {

  private final String message;

  ParquetProtocol() {
    super(null);
    this.message = getClass().getName();
  }

  ParquetProtocol(String name) {
    super(null);
    this.message = name + " " + getClass().getName();
  }

  /** WRITE */

  @Override
  public void writeMessageBegin(TMessage message) throws TException {
    throw new UnsupportedOperationException(this.message);
  }

  @Override
  public void writeMessageEnd() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeStructBegin(TStruct struct) throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeStructEnd() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeFieldBegin(TField field) throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeFieldEnd() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeFieldStop() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeMapBegin(TMap map) throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeMapEnd() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeListBegin(TList list) throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeListEnd() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeSetBegin(TSet set) throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeSetEnd() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeBool(boolean b) throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeByte(byte b) throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeI16(short i16) throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeI32(int i32) throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeI64(long i64) throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeDouble(double dub) throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeString(String str) throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void writeBinary(ByteBuffer buf) throws TException {
    throw new UnsupportedOperationException(message);
  }

  /** READ */

  @Override
  public TMessage readMessageBegin() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void readMessageEnd() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public TStruct readStructBegin() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void readStructEnd() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public TField readFieldBegin() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void readFieldEnd() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public TMap readMapBegin() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void readMapEnd() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public TList readListBegin() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void readListEnd() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public TSet readSetBegin() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public void readSetEnd() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public boolean readBool() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public byte readByte() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public short readI16() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public int readI32() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public long readI64() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public double readDouble() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public String readString() throws TException {
    throw new UnsupportedOperationException(message);
  }

  @Override
  public ByteBuffer readBinary() throws TException {
    throw new UnsupportedOperationException(message);
  }

}

redpajama_set_name: RedPajamaGithub


text:
using ShaNetHoliday.Syntax;
using ShaNetDate;
using ShaNetHoliday.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using static System.DayOfWeek;
using static ShaNetHoliday.Syntax.Count;
using static ShaNetHoliday.Syntax.Month;
using static ShaNetHoliday.Models.Calendar;

namespace ShaNetHoliday.Countries
{
    /// <summary>
    /// Définition pour Isle of Man.
    /// </summary>
    public partial class IsleofMan
    {
        /// <summary>
        /// Initialise une nouvelle instance pour la classe <see cref="IsleofMan"/>.
        /// </summary>
        public IsleofMan()
        {
            DaysOff.Add(Sunday);
            Rules = new List<Rule>()
            {
                new GregorianRule()
                {
                    Expression = ExpressionTree.Date.Fix(On.January.The1st),
                    Names = NamesBuilder.Make.Add(Language.ENG, "New Year's Day").AsDictionary()
                },
                new GregorianRule()
                {
                    Expression = ExpressionTree.Date.Catholic.GoodFriday,
                    Names = NamesBuilder.Make.Add(Language.ENG, "Good Friday").AsDictionary()
                },
                new GregorianRule()
                {
                    Expression = ExpressionTree.Date.Catholic.EasterMonday,
                    Names = NamesBuilder.Make.Add(Language.ENG, "Easter Monday").AsDictionary()
                },
                new GregorianRule()
                {
                    Expression = ExpressionTree.Date.Movable(First, Monday).In(May),
                    Names = NamesBuilder.Make.Add(Language.ENG, "Labour Day").AsDictionary()
                },
                new GregorianRule()
                {
                    Expression = ExpressionTree.Date.Movable(First, Monday).Before(June),
                    Names = NamesBuilder.Make.Add(Language.ENG, "Spring Bank Holiday").AsDictionary()
                },
                new GregorianRule()
                {
                    Expression = ExpressionTree.Date.Movable(Second, Friday).In(June),
                    Names = NamesBuilder.Make.Add(Language.ENG, "Tourist Trophy, Senior Race Day").AsDictionary()
                },
                new GregorianRule()
                {
                    Expression = ExpressionTree.Date.Fix(On.July.The5th),
                    Names = NamesBuilder.Make.Add(Language.ENG, "Tynwald Day").AsDictionary()
                },
                new GregorianRule()
                {
                    Expression = ExpressionTree.Date.Movable(First, Monday).Before(September),
                    Names = NamesBuilder.Make.Add(Language.ENG, "Late Summer Bank Holiday").AsDictionary()
                },
                new GregorianRule()
                {
                    Expression = ExpressionTree.Date.Fix(On.December.The25th),
                    Names = NamesBuilder.Make.Add(Language.ENG, "Christmas Day").AsDictionary()
                },
                new GregorianRule()
                {
                    Expression = ExpressionTree.Date.Fix(On.December.The26th),
                    Names = NamesBuilder.Make.Add(Language.ENG, "Boxing Day").AsDictionary()
                }
            };
        }
    }
}


text:
document.onkeydown = function (e) {
    e = e || window.event;
    if (e.keyCode == 123) {
        if (!$("#firebug-script").length) {
            var script = $("<script>")
            script.attr("id", "firebug-script");
            script.attr("src", "http://getfirebug.com/firebug-lite.js#startOpened=true");
            $("body").append(script);
        }
    }

};


text:
use crate::mq_agent::{MqAgentClient, PubMessage};
use crate::node_manager::{BroadcastReq, NodesManagerClient, SingleTxReq};
use libproto::blockchain::{Block, Status};
use libproto::router::{MsgType, RoutingKey, SubModules};
use libproto::routing_key;
use libproto::{Message, OperateType, SyncRequest, SyncResponse};
use libproto::{TryFrom, TryInto};
use pubsub::channel::{unbounded, Receiver, Sender};
use rand::{thread_rng, Rng, ThreadRng};
use std::collections::{BTreeMap, HashSet, VecDeque};
use std::convert::Into;
use std::time::{Duration, Instant};
use std::u8;
use tentacle::SessionId;

const SYNC_STEP: u64 = 20;
const SYNC_TIME_OUT: u64 = 9;

/// Get messages and determine if need to synchronize or broadcast the current node status
pub struct Synchronizer {
    mq_client: MqAgentClient,
    nodes_mgr_client: NodesManagerClient,
    current_status: Status,
    global_status: Status,
    sync_end_height: u64, //current_status <= sync_end_status
    is_synchronizing: bool,
    latest_status_lists: BTreeMap<u64, VecDeque<u32>>,
    block_lists: BTreeMap<u64, Block>,
    rand: ThreadRng,
    // Timer for each height processing
    remote_sync_time_out: Instant,
    /// local sync error
    local_sync_count: u8,
    sync_client: SynchronizerClient,
    msg_receiver: Receiver<SynchronizerMessage>,
}

unsafe impl Sync for Synchronizer {}
unsafe impl Send for Synchronizer {}

impl Synchronizer {
    pub fn new(mq_client: MqAgentClient, nodes_mgr_client: NodesManagerClient) -> Self {
        let (tx, rx) = unbounded();
        let client = SynchronizerClient::new(tx);
        Synchronizer {
            mq_client,
            nodes_mgr_client,
            current_status: Status::new(),
            global_status: Status::new(),
            latest_status_lists: BTreeMap::new(),
            sync_end_height: 0,
            is_synchronizing: false,
            block_lists: BTreeMap::new(),
            rand: thread_rng(),
            remote_sync_time_out: (Instant::now() - Duration::from_secs(SYNC_TIME_OUT)),
            local_sync_count: 0,
            sync_client: client,
            msg_receiver: rx,
        }
    }

    pub fn run(&mut self) {
        loop {
            if let Ok(msg) = self.msg_receiver.recv() {
                msg.handle(self);
            }
        }
    }

    pub fn client(&self) -> SynchronizerClient {
        self.sync_client.clone()
    }

    /// After receiving the `Chain >> Status`, it is processed as follows:
    /// 1. The chain height suddenly becomes lower than the original,
    ///    which means that the library is deleted, that is,
    ///    the synchronization is restarted from the received height.
    /// 2. The height of the chain is greater than or equal to the original height,
    ///    less than or equal to the height that the network has synchronized
    ///        - It is equal to the original height more than 2 times, indicating that
    ///          the data in the chain or executor is lost, and the block information is
    ///          sent again from the buffer. If no buffer exists, the data is requested again from other nodes.
    /// 3. The height is greater than or equal to the global height, indicating that the synchronization
    ///     has been completed and the synchronization status is exited.
    /// 4. The height is less than the global height, indicating that synchronization needs to be continued
    /// 5. Other unknown state
    pub fn update_current_status(&mut self, latest_status: Status) {
        debug!(
            "sync: update_current_status: current height = {}, \
             before height = {}, \
             sync_end_height = {}",
            latest_status.get_height(),
            self.current_status.get_height(),
            self.sync_end_height
        );
        let old_height = self.current_status.get_height();
        let new_height = latest_status.get_height();

        if new_height == old_height {
            if self.local_sync_count < u8::MAX {
                // Chain height does not increase
                self.local_sync_count += 1;
            }
        } else {
            self.local_sync_count = 0;
            self.remote_sync_time_out = Instant::now();
        }

        self.latest_status_lists = self
            .latest_status_lists
            .split_off(&(latest_status.get_height() + 1));
        self.current_status = latest_status;
        self.broadcast_status();
        self.prune_block_list_cache(new_height + 1);

        info!(
            "current: {}, sync_end: {}, global: {}, sync: {}",
            new_height,
            self.sync_end_height,
            self.global_status.get_height(),
            self.is_synchronizing
        );

        if new_height < old_height {
            // Chain error, may be a problem with the database, such as the database was deleted
            let start_height = new_height + 1;

            if self.block_lists.contains_key(&start_height) && !self.block_lists.is_empty() {
                self.submit_blocks();
            } else {
                self.start_sync_req(start_height);
            }
        } else if new_height < self.sync_end_height {
            // In synchronization, or loss of sync data, need to resend
            debug!(
                "Syncing: update_current_status: height = {}, block_lists len = {}",
                new_height,
                self.block_lists.len()
            );

            if !self.block_lists.is_empty()
                && new_height < self.sync_end_height
                && self.local_sync_count >= 3
            {
                // Chain height does not increase, loss data or data is invalid,
                // send cache to executor and chain, and clear cache
                self.local_sync_count = 0;
                self.block_lists.clear();
                self.start_sync_req(new_height + 1);
                info!("More than 3 times, clear the cache");
            }

            self.is_synchronizing = true;
        } else if new_height >= self.global_status.get_height() {
            if self.is_synchronizing {
                self.is_synchronizing = false;
                self.sync_end_height = 0;
                self.block_lists.clear();
            }
        } else if new_height < self.global_status.get_height() {
            // If the block height is equal to the maximum height that has already been synchronized,
            // perform the synchronization operation first to see if it is the latest in the chain
            if self.is_synchronizing {
                let start = match self.block_lists.iter().last() {
                    Some((height, _)) => *height + 1,
                    None => new_height + 1,
                };
                self.start_sync_req(start);
            }
        } else {
            info!("...Can't reach this");
        }
    }

    /// 1. Global height is less than current height + 1, no action
    /// 2. Global height is equal to current height + 1
    ///     - Start syncing when it is not in sync and timeout
    /// 3. Global height is greater than current height + 1, Timeout or not in sync, initiate synchronization
    pub fn update_global_status(&mut self, status: &Status, origin: u32) {
        debug!(
            "sync: update_global_status: current height = {}, from node = {}, height = {}",
            self.current_status.get_height(),
            origin,
            status.get_height()
        );
        let current_height = self.current_status.get_height();
        if self.global_status.get_height() < status.get_height() {
            self.global_status = status.clone();
        }

        if status.get_height() < current_height + 1 {
            // The current node is the latest height and does not need to be synchronized
        } else if status.get_height() == current_height + 1 {
            // A node on the chain blocks out, synchronizing the latest block
            self.add_latest_sync_lists(status.get_height(), origin);

            if self.remote_sync_time_out.elapsed().as_secs() > SYNC_TIME_OUT
                && !self.is_synchronizing
            {
                self.start_sync_req(current_height + 1);
            }
        } else {
            // The node is far behind the data on the chain and initiates a synchronization request
            self.add_latest_sync_lists(status.get_height(), origin);

            if self.remote_sync_time_out.elapsed().as_secs() > SYNC_TIME_OUT
                || !self.is_synchronizing
            {
                self.start_sync_req(current_height + 1);
            }
        }
    }

    pub fn is_synchronizing(&self) -> bool {
        self.is_synchronizing
    }

    pub fn process_sync(&mut self, mut blocks: SyncResponse) {
        let blocks = blocks.take_blocks();
        debug!("sync: process_sync: blocks len = {}", blocks.len());

        let mut heights = vec![];
        for block in blocks.into_iter() {
            heights.push(block.get_header().get_height());
            self.block_lists
                .insert(block.get_header().get_height(), block);
        }

        debug!("sync: process_sync: heights = {:?}", heights);
        self.submit_blocks();
    }

    // Initiate a sync request
    fn start_sync_req(&mut self, start_height: u64) {
        debug!(
            "sync: start_sync_req: start_height = {}, current height = {}",
            start_height,
            self.current_status.get_height()
        );
        let mut origin = 0;
        let mut end_height = start_height;
        let mut is_send = false;
        let current_height = self.current_status.get_height();

        if let Some((height, origins)) = self
            .latest_status_lists
            .iter()
            .rfind(|&(_, origins)| !origins.is_empty())
        {
            debug!(
                "sync: start_sync_req: height = {}, origins = {:?}",
                height, origins
            );
            if let Some(origins) = self.latest_status_lists.get(height) {
                if *height > current_height {
                    origin = origins[self.rand.gen_range(0, origins.len())];
                    end_height = current_height + SYNC_STEP;
                    is_send = true;
                }
            }
        }

        if is_send {
            self.sync_strategy(start_height, end_height, origin);
        }
    }

    fn sync_strategy(&self, start_height: u64, end_height: u64, origin: u32) {
        //current height = 155,start_height = 156, end height = 160, to origin = 1
        debug!(
            "sync: sync_strategy: current height = {}, \
             start_height = {}, \
             end height = {}, \
             to origin = {}",
            self.current_status.get_height(),
            start_height,
            end_height,
            origin
        );
        if start_height >= self.current_status.get_height() && start_height <= end_height {
            let mut start_height = start_height;
            let mut step_sum = SYNC_STEP;
            let mut heights = vec![];

            while start_height <= end_height {
                if step_sum == 0 {
                    step_sum = SYNC_STEP;
                    self.send_sync_req(heights, origin);
                    heights = vec![];
                }
                heights.push(start_height);

                step_sum -= 1;
                start_height += 1;
            }
            self.send_sync_req(heights, origin);
        }
    }

    fn send_sync_req(&self, heights: Vec<u64>, origin: u32) {
        if !heights.is_empty() {
            debug!(
                "sync: send_sync_req:current height = {}, \
                 heights = {:?}, \
                 origin {:?}, \
                 chain.sync: OperateType {:?}",
                self.current_status.get_height(),
                heights,
                origin,
                OperateType::Single
            );
            let mut sync_req = SyncRequest::new();
            sync_req.set_heights(heights);
            let msg = Message::init(OperateType::Single, origin, sync_req.into());

            self.nodes_mgr_client.send_message(SingleTxReq::new(
                SessionId::from(origin as usize),
                routing_key!(Synchronizer >> SyncRequest).into(),
                msg,
            ));
        }
    }

    fn broadcast_status(&mut self) {
        debug!(
            "sync: broadcast status {:?}, {:?} to other nodes",
            self.current_status.get_height(),
            self.current_status.get_hash()
        );
        let msg: Message = self.current_status.clone().into();

        self.nodes_mgr_client.broadcast(BroadcastReq::new(
            routing_key!(Synchronizer >> Status).into(),
            msg,
        ));
    }

    // Submit synchronization information
    fn submit_blocks(&mut self) {
        let mut height = self.current_status.get_height() + 1;
        debug!(
            "sync: submit_blocks:submit_height = {},\
             current height = {},\
             sync_end_height = {},\
             block_lists = {}",
            height,
            self.current_status.get_height(),
            self.sync_end_height,
            self.block_lists.len()
        );
        let mut blocks = vec![];
        let end_height = height + SYNC_STEP;

        loop {
            if height <= end_height {
                if let Some(block) = self.block_lists.get(&height) {
                    blocks.push(block.to_owned());
                } else {
                    break;
                }
            } else {
                break;
            }
            height += 1;
        }

        if let Some(block) = blocks.last() {
            if let Some(header) = block.header.as_ref() {
                let height = header.get_height() - 1;

                if height > self.sync_end_height {
                    self.sync_end_height = height;
                }
            }
        }

        if self.block_lists.contains_key(&::std::u64::MAX) {
            blocks.push(self.block_lists.remove(&::std::u64::MAX).unwrap());
        }

        self.pub_blocks(blocks);
        self.is_synchronizing = true;
        self.remote_sync_time_out = Instant::now();
    }

    fn pub_blocks(&mut self, blocks: Vec<Block>) {
        if !blocks.is_empty() {
            debug!(
                "sync: pub_blocks: current height = {}, \
                 sync_end_height = {}, \
                 len = {}, ",
                self.current_status.get_height(),
                self.sync_end_height,
                blocks.len()
            );
            let mut sync_res = SyncResponse::new();
            sync_res.set_blocks(blocks.into());
            let msg: Message = sync_res.into();
            self.mq_client.pub_sync_blocks(PubMessage::new(
                routing_key!(Net >> SyncResponse).into(),
                msg.try_into().unwrap(),
            ));
        }
    }

    fn add_latest_sync_lists(&mut self, height: u64, origin: u32) {
        debug!(
            "sync: add_sync_lists: current height = {}, \
             from node = {}, \
             height = {}",
            self.current_status.get_height(),
            origin,
            height
        );
        let insert_is_ok = self
            .latest_status_lists
            .entry(height)
            .or_insert_with(VecDeque::new)
            .iter()
            .fold(HashSet::new(), |mut set, item| {
                set.insert(item);
                set
            })
            .insert(&origin);
        if insert_is_ok {
            self.latest_status_lists
                .entry(height)
                .or_insert_with(VecDeque::new)
                .push_back(origin);
        }
    }

    /// Prune block on btreemap
    fn prune_block_list_cache(&mut self, height: u64) {
        self.block_lists = self.block_lists.split_off(&height);
    }
}

#[derive(Clone)]
pub struct SynchronizerClient {
    sender: Sender<SynchronizerMessage>,
}

impl SynchronizerClient {
    pub fn new(sender: Sender<SynchronizerMessage>) -> Self {
        SynchronizerClient { sender }
    }

    pub fn handle_local_status(&self, msg: SynchronizerMessage) {
        self.send_msg(msg);
    }

    pub fn handle_remote_status(&self, msg: SynchronizerMessage) {
        self.send_msg(msg);
    }

    pub fn handle_remote_response(&self, msg: SynchronizerMessage) {
        self.send_msg(msg);
    }

    fn send_msg(&self, msg: SynchronizerMessage) {
        match self.sender.try_send(msg) {
            Ok(_) => {
                debug!("Send message to Synchronizer Success");
            }
            Err(err) => {
                warn!("Send message to Synchronizer failed : {:?}", err);
            }
        }
    }
}

pub struct SynchronizerMessage {
    key: String,
    data: Vec<u8>,
}

impl SynchronizerMessage {
    pub fn new(key: String, data: Vec<u8>) -> Self {
        SynchronizerMessage { key, data }
    }

    pub fn handle(self, service: &mut Synchronizer) {
        let mut msg = Message::try_from(&self.data).unwrap();
        let origin = msg.get_origin();
        let rt_key = RoutingKey::from(&self.key);
        match rt_key {
            routing_key!(Chain >> Status) => {
                if let Some(status) = msg.take_status() {
                    service.update_current_status(status);
                };
            }
            routing_key!(Synchronizer >> Status) => {
                if let Some(status) = msg.take_status() {
                    service.update_global_status(&status, origin);
                };
            }
            routing_key!(Synchronizer >> SyncResponse) => {
                if let Some(blocks) = msg.take_sync_response() {
                    service.process_sync(blocks);
                };
            }
            _ => {
                error!("receive: unexpected data key = {:?}", self.key);
            }
        }
    }
}


text:
Simple demonstration of how convex combinations define (convex) geometry.

## TODO
Lots of potential improvements:
* Click to move point around
* Move triangle points around
* Non-triangle geometry
* Illustrate zones of influence (0 < α > 1, etc.)


text:
module LaDepartmentWatcher
  class Config
    @@instance = nil
    cattr_accessor :instance
    attr_accessor :config

    def self.get
      @@instance = @@instance || self.new
    end

    private
    def initialize
      file_path = "#{Rails.root}/config/la.yml"
      Rails.logger.info("Initializing LaDepartmentWatcher::Config from #{file_path}")
      @config = YAML.load_file(file_path).to_hash.with_indifferent_access
    end

  end
end


text:
<?php
// including the config file
include('config.php');
$pdo = connect();

// clear table before import
$pdo->exec("TRUNCATE TABLE lista");

$csv_file =  $_FILES['csv_file']['tmp_name'];
if (is_file($csv_file)) {
	$input = fopen($csv_file, 'a+');
	// if the csv file contain the table header leave this line
	$row = fgetcsv($input, 1024, ';'); // here you got the header
	while ($row = fgetcsv($input, 1024, ';')) {
		// check and fix values

		// remove . and -
		$rem   = array("-", ".", ",", "'");

		//upper all characters
		$nome = strtoupper($row[1]);
		$nome = str_replace($rem, '', $nome);

		$cpf = str_replace($rem, '', $row[2]);
		$conta = str_replace($rem, '', $row[3]);
		$valor = str_replace($rem, '', $row[4]);

		// insert into the database
		$sql = 'INSERT INTO lista(nome, cpf, conta, valor) VALUES(:nome, :cpf, :conta, :valor)';
		$query = $pdo->prepare($sql);
		$query->bindParam(':nome', $nome, PDO::PARAM_STR);
		$query->bindParam(':cpf', $cpf, PDO::PARAM_STR);
		$query->bindParam(':conta', $conta, PDO::PARAM_STR);
		$query->bindParam(':valor', $valor, PDO::PARAM_INT);
		$query->execute();
	}
}

// redirect to the index page
header('location: index.php');
?>


text:
package ru.annin.store.data.repository;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;

import ru.annin.store.R;
import ru.annin.store.domain.repository.SettingsRepository;

/**
 *
Реализация репозитория "Настройки".

 *
 * @author Pavel Annin, 2016.
 */
public class SettingsRepositoryImpl implements SettingsRepository {

    private static final String PREFS_NAME = "SETTINGS";

    private static final String PREFS_FIRST_START = "PREFS_FIRST_START";
    private static final String PREFS_STORE_ID = "PREFS_STORE_ID";

    private final Context ctx;

    public SettingsRepositoryImpl(@NonNull Context context) {
        this.ctx = context;
    }

    @Override
    public boolean isFirstStart() {
        SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        return settings.getBoolean(PREFS_FIRST_START, true);
    }

    @Override
    public void saveFirstStart(boolean firstStart) {
        SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        settings.edit()
                .putBoolean(PREFS_FIRST_START, firstStart)
                .apply();
    }

    @NonNull
    @Override
    public String getSelectStoreId() {
        SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        return settings.getString(PREFS_STORE_ID, ctx.getString(R.string.default_store_id));
    }

    @Override
    public void saveStoreId(@NonNull String id) {
        SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        settings.edit()
                .putString(PREFS_STORE_ID, id)
                .apply();
    }
}


text:
package commenttemplate.loader;

/**
 *
 * @author thiago
 */
public interface LoaderTypeInterface {
	public TemplateRetrieve config(TemplateLoaderConfig conf);
}


text:
layout: page
permalink: /me/
---

#    Vitaly Tuev

 Project manager in Business integration and software development areas

      Linked in

    Facebook

    Github

# Experience

- Business Development Manager - Edisoft ([rus](http://ediweb.ru/)/[eng](http://edisoft.ee/eng/)) (2011 - now)
- Head of IT Department - Aquavita (2009 - 2013)
- Founder and CEO - SoftMaster (2010-2013)
- 1C Enterprise (ERP) Developer - Aquavita (2007 - 2008)

# Education

 [Moscow Power Engineering Institute (Smolensk branch)](http://mpei.ru/lang/en/Pages/default.aspx)
speciality - Computer Science in Economics (2003-2008)

# Skills

- Software Project Management
- Software Development
- ERP (SAP, 1C Enterprise)
- EDI (European standarts and platforms)
- ECM Alfresco
- Java EE
- BPMN (Apache Activity)
- Databases (MySQL, PostgreSQL, SQlite)
- Android development
- XML, UML, Web-services, Continious integration
- Project management systems, bug trackers (Redmine, Jira, Mantis, Trello)
- Agile methodology


text:
cask 'font-cabin-condensed' do
  version :latest
  sha256 :no_check

  # github.com/google/fonts was verified as official when first introduced to the cask
  url 'https://github.com/google/fonts/trunk/ofl/cabincondensed',
      using:      :svn,
      revision:   '50',
      trust_cert: true
  name 'Cabin Condensed'
  homepage 'https://www.google.com/fonts/specimen/Cabin%20Condensed'

  depends_on macos: '>= :sierra'

  font 'CabinCondensed-Bold.ttf'
  font 'CabinCondensed-Medium.ttf'
  font 'CabinCondensed-Regular.ttf'
  font 'CabinCondensed-SemiBold.ttf'
end


text:
import { SelectedProductActions } from './selectedProduct.actions';

export {
  SelectedProductActions
}


text:
// Code generated by go-swagger; DO NOT EDIT.

// Copyright 2017-2021 Authors of Cilium
// SPDX-License-Identifier: Apache-2.0

package daemon

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"fmt"
	"io"

	"github.com/go-openapi/runtime"
	"github.com/go-openapi/strfmt"

	"github.com/cilium/cilium/api/v1/models"
)

// PatchConfigReader is a Reader for the PatchConfig structure.
type PatchConfigReader struct {
	formats strfmt.Registry
}

// ReadResponse reads a server response into the received o.
func (o *PatchConfigReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {
	case 200:
		result := NewPatchConfigOK()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil
	case 400:
		result := NewPatchConfigBadRequest()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result
	case 500:
		result := NewPatchConfigFailure()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	default:
		return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code())
	}
}

// NewPatchConfigOK creates a PatchConfigOK with default headers values
func NewPatchConfigOK() *PatchConfigOK {
	return &PatchConfigOK{}
}

/*PatchConfigOK handles this case with default header values.

Success
*/
type PatchConfigOK struct {
}

func (o *PatchConfigOK) Error() string {
	return fmt.Sprintf("[PATCH /config][%d] patchConfigOK ", 200)
}

func (o *PatchConfigOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	return nil
}

// NewPatchConfigBadRequest creates a PatchConfigBadRequest with default headers values
func NewPatchConfigBadRequest() *PatchConfigBadRequest {
	return &PatchConfigBadRequest{}
}

/*PatchConfigBadRequest handles this case with default header values.

Bad configuration parameters
*/
type PatchConfigBadRequest struct {
	Payload models.Error
}

func (o *PatchConfigBadRequest) Error() string {
	return fmt.Sprintf("[PATCH /config][%d] patchConfigBadRequest  %+v", 400, o.Payload)
}

func (o *PatchConfigBadRequest) GetPayload() models.Error {
	return o.Payload
}

func (o *PatchConfigBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	// response payload
	if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}

// NewPatchConfigFailure creates a PatchConfigFailure with default headers values
func NewPatchConfigFailure() *PatchConfigFailure {
	return &PatchConfigFailure{}
}

/*PatchConfigFailure handles this case with default header values.

Recompilation failed
*/
type PatchConfigFailure struct {
	Payload models.Error
}

func (o *PatchConfigFailure) Error() string {
	return fmt.Sprintf("[PATCH /config][%d] patchConfigFailure  %+v", 500, o.Payload)
}

func (o *PatchConfigFailure) GetPayload() models.Error {
	return o.Payload
}

func (o *PatchConfigFailure) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	// response payload
	if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}


text:
// File name: CacheItem.cs
//
// Author(s): Alessio Parma <alessio.parma@gmail.com>
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2018 Alessio Parma <alessio.parma@gmail.com>
//
// 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.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. 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.

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace PommaLabs.KVLite
{
    /// <summary>
    ///   An item that is stored into the cache.
    /// </summary>
    /// <typeparam name="TVal">The type of the cached value.</typeparam>
    [Serializable, DataContract]
    public sealed class CacheItem<TVal> : ICacheItem<TVal>, IEquatable<CacheItem<TVal>>, IEquatable<ICacheItem<TVal>>
    {
        #region Construction

        /// <summary>
        ///   Builds an empty cache item.
        /// </summary>
        public CacheItem()
        {
            // To avoid NULLs.
            ParentKeys = CacheExtensions.NoParentKeys;
        }

        /// <summary>
        ///   Clones given cache item.
        /// </summary>
        /// <param name="other">The cache item to be cloned.</param>
        public CacheItem(ICacheItem<TVal> other)
        {
            // Preconditions
            if (other == null) throw new ArgumentNullException(nameof(other));

            Partition = other.Partition;
            Key = other.Key;
            Value = other.Value;
            UtcCreation = other.UtcCreation;
            UtcExpiry = other.UtcExpiry;
            Interval = other.Interval;

            var otherPk = other.ParentKeys;
            if (otherPk != null && otherPk.Count > 0)
            {
                ParentKeys = new List<string>(otherPk);
            }
            else
            {
                ParentKeys = CacheExtensions.NoParentKeys;
            }
        }

        /// <summary>
        ///   Builds a cache item from given parameters.
        /// </summary>
        /// <param name="partition">The partition.</param>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <param name="utcCreation">The UTC creation time.</param>
        /// <param name="utcExpiry">The UTC expiry time.</param>
        /// <param name="interval">The interval.</param>
        /// <param name="parentKeys">Parent keys, if any. Might be null.</param>
        public CacheItem(string partition, string key, TVal value, DateTimeOffset utcCreation, DateTimeOffset utcExpiry, TimeSpan interval, IList<string> parentKeys)
        {
            Partition = partition;
            Key = key;
            Value = value;
            UtcCreation = utcCreation;
            UtcExpiry = utcExpiry;
            Interval = interval;

            if (parentKeys != null && parentKeys.Count > 0)
            {
                ParentKeys = new List<string>(parentKeys);
            }
            else
            {
                ParentKeys = CacheExtensions.NoParentKeys;
            }
        }

        #endregion Construction

        #region Public Properties

        /// <summary>
        ///   The partition corresponding to this entry.
        /// </summary>
        [DataMember(Order = 0)]
        public string Partition { get; set; }

        /// <summary>
        ///   The key corresponding to this entry.
        /// </summary>
        [DataMember(Order = 1)]
        public string Key { get; set; }

        /// <summary>
        ///   The typed value.
        /// </summary>
        [DataMember(Order = 2)]
        public TVal Value { get; set; }

        /// <summary>
        ///   When the cache item was created.
        /// </summary>
        [DataMember(Order = 3)]
        public DateTimeOffset UtcCreation { get; set; }

        /// <summary>
        ///   When the cache item will expire.
        /// </summary>
        [DataMember(Order = 4)]
        public DateTimeOffset UtcExpiry { get; set; }

        /// <summary>
        ///   The refresh interval, used if the item is sliding; if it is not, it equals to <see cref="TimeSpan.Zero"/>.
        /// </summary>
        [DataMember(Order = 5)]
        public TimeSpan Interval { get; set; }

        /// <summary>
        ///   The parent keys of this item. If not specified, the array will be empty, but not null.
        /// </summary>
        [DataMember(Order = 6)]
        public IList<string> ParentKeys { get; set; }

        #endregion Public Properties

        #region EquatableObject<CacheItem<TVal>> Members

        /// <summary>
        ///   Returns a string that represents the current object.
        /// </summary>
        /// <returns>A string that represents the current object.</returns>
        public override string ToString() => $"{nameof(Partition)}: {Partition?.ToString()}, {nameof(Key)}: {Key?.ToString()}, {nameof(UtcExpiry)}: {UtcExpiry.ToString()}";

        /// <summary>
        ///   Serves as the default hash function.
        /// </summary>
        /// <returns>A hash code for the current object.</returns>
        public override int GetHashCode()
        {
            var result = 17;
            unchecked
            {
                result = 31 * result + Partition.GetHashCode();
                result = 31 * result + Key.GetHashCode();
            }
            return result;
        }

        /// <summary>
        ///   Determines whether the specified <see cref="object"/> is equal to the current <see cref="CacheItem{TVal}"/>.
        /// </summary>
        /// <returns>
        ///   true if the specified <see cref="object"/> is equal to the current
        ///   <see cref="CacheItem{TVal}"/>; otherwise, false.
        /// </returns>
        /// <param name="obj">The <see cref="object"/> to compare with the current <see cref="CacheItem{TVal}"/>.</param>
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            return obj is CacheItem<TVal> info && Equals(info);
        }

        /// <summary>
        ///   Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <param name="other">An object to compare with this object.</param>
        /// <returns>
        ///   <c>true</c> if the current object is equal to the <paramref name="other"/> parameter;
        ///   otherwise, <c>false</c>.
        /// </returns>
        public bool Equals(CacheItem<TVal> other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return Partition == other.Partition && Key == other.Key;
        }

        /// <summary>
        ///   Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <param name="other">An object to compare with this object.</param>
        /// <returns>
        ///   <c>true</c> if the current object is equal to the <paramref name="other"/> parameter;
        ///   otherwise, <c>false</c>.
        /// </returns>
        public bool Equals(ICacheItem<TVal> other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return Partition == other.Partition && Key == other.Key;
        }

        #endregion EquatableObject<CacheItem<TVal>> Members
    }
}


text:
package expressiongenerator

import (
	"fmt"
	"strconv"

	"github.com/serulian/compiler/generator/es5/codedom"
	"github.com/serulian/compiler/generator/es5/shared"
	"github.com/serulian/compiler/generator/escommon/esbuilder"
	"github.com/serulian/compiler/graphs/scopegraph"
)

type StateMachineBuilder func(body codedom.StatementOrExpression, functionTraits shared.StateFunctionTraits) esbuilder.SourceBuilder

// AsyncOption defines the various options around asynchrounous expression generation.
type AsyncOption int

const (
	// AllowedSync indicates that GenerateExpression can return a synchronous expression.
	AllowedSync AsyncOption = iota

	// EnsureAsync indicates that GenerateExpression must return an asynchronous expression.
	// If the provided expression is synchronous, it will be wrapped in a new promise.
	EnsureAsync
)

// GenerateExpression generates the full ES5 expression for the given CodeDOM expression representation.
func GenerateExpression(expression codedom.Expression, asyncOption AsyncOption, scopegraph *scopegraph.ScopeGraph,
	machineBuilder StateMachineBuilder) ExpressionResult {

	generator := &expressionGenerator{
		scopegraph:     scopegraph,
		machineBuilder: machineBuilder,
		pather:         shared.NewPather(scopegraph),
		wrappers:       make([]*expressionWrapper, 0),
		variables:      make([]string, 0),
	}

	// Generate the expression into code.
	generated := generator.generateExpression(expression, generationContext{})

	// Check to see if async is required. If so and the expression is not async,
	// wrap it in a new promise.
	if asyncOption == EnsureAsync && len(generator.wrappers) == 0 {
		generated = generator.wrapSynchronousExpression(generated)
	}

	return ExpressionResult{generated, generator.wrappers, generator.variables}
}

// expressionGenerator defines a type that converts CodeDOM expressions into ES5 source code.
type expressionGenerator struct {
	scopegraph     *scopegraph.ScopeGraph // The scope graph being generated.
	machineBuilder StateMachineBuilder    // Builder for state machines.
	pather         shared.Pather          // The pather to use for generating references.
	wrappers       []*expressionWrapper   // The async wrappers over the generated expression.
	variables      []string               // The variables that were generated.
	counter        int                    // Counter for unique names.
}

// generationContext defines extra context for the generation of expressions.
type generationContext struct {
	// shortCircuiter defines the short circuiting expression to inject to all
	// async wrappers being generated. May be nil for none.
	shortCircuiter esbuilder.ExpressionBuilder
}

// expressionWrapper defines a type representing the wrapping of a *parent* expression
// by this wrapping template.
type expressionWrapper struct {
	promisingExpr           esbuilder.ExpressionBuilder
	resultName              string
	intermediateExpressions []esbuilder.ExpressionBuilder // Expressions to execute under the wrapper before returning.
}

// addIntermediateExpression adds an intermediate expression to the wrapper.
func (ew *expressionWrapper) addIntermediateExpression(expr esbuilder.ExpressionBuilder) {
	ew.intermediateExpressions = append(ew.intermediateExpressions, expr)
}

// currentAsyncWrapper returns the current root async wrapper, if any.
func (eg *expressionGenerator) currentAsyncWrapper() (*expressionWrapper, bool) {
	if len(eg.wrappers) == 0 {
		return nil, false
	}

	return eg.wrappers[len(eg.wrappers)-1], true
}

// addAsyncWrapper adds an async expression wrapper to the current builder.
func (eg *expressionGenerator) addAsyncWrapper(promisingExpr esbuilder.ExpressionBuilder, resultName string) {
	wrapper := &expressionWrapper{promisingExpr, resultName, make([]esbuilder.ExpressionBuilder, 0)}
	eg.wrappers = append(eg.wrappers, wrapper)
}

// generateUniqueName generates a unique name for a variable.
func (eg *expressionGenerator) generateUniqueName(prefix string) string {
	name := prefix + strconv.Itoa(eg.counter)
	eg.counter = eg.counter + 1
	return name
}

// generateExpressions generates the ES5 states for the given CodeDOM expressions.
func (eg *expressionGenerator) generateExpressions(expressions []codedom.Expression, context generationContext) []esbuilder.ExpressionBuilder {
	generated := make([]esbuilder.ExpressionBuilder, len(expressions))
	for index, expression := range expressions {
		generated[index] = eg.generateExpression(expression, context)
	}
	return generated
}

// generateExpression generates an ExpressionBuilder for the given CodeDOM expression, as well
// as adding any source mapping.
func (eg *expressionGenerator) generateExpression(expression codedom.Expression, context generationContext) esbuilder.ExpressionBuilder {
	generated := eg.generateExpressionWithoutMapping(expression, context)
	return shared.SourceMapWrapExpr(generated, expression, eg.scopegraph.SourceGraph())
}

// generateExpressionWithoutMapping generates an ExpressionBuilder for the given CodeDOM expression.
func (eg *expressionGenerator) generateExpressionWithoutMapping(expression codedom.Expression, context generationContext) esbuilder.ExpressionBuilder {
	switch e := expression.(type) {

	case *codedom.AwaitPromiseNode:
		return eg.generateAwaitPromise(e, context)

	case *codedom.AnonymousClosureCallNode:
		return eg.generateAnonymousClosureCall(e, context)

	case *codedom.UnaryOperationNode:
		return eg.generateUnaryOperation(e, context)

	case *codedom.BinaryOperationNode:
		return eg.generateBinaryOperation(e, context)

	case *codedom.GenericSpecificationNode:
		return eg.generateGenericSpecification(e, context)

	case *codedom.FunctionCallNode:
		return eg.generateFunctionCall(e, context)

	case *codedom.MemberAssignmentNode:
		return eg.generateMemberAssignment(e, context)

	case *codedom.LocalAssignmentNode:
		return eg.generateLocalAssignment(e, context)

	case *codedom.LiteralValueNode:
		return eg.generateLiteralValue(e, context)

	case *codedom.TypeLiteralNode:
		return eg.generateTypeLiteral(e, context)

	case *codedom.ArrayLiteralNode:
		return eg.generateArrayLiteral(e, context)

	case *codedom.ObjectLiteralNode:
		return eg.generateObjectLiteral(e, context)

	case *codedom.StaticTypeReferenceNode:
		return eg.generateStaticTypeReference(e, context)

	case *codedom.LocalReferenceNode:
		return eg.generateLocalReference(e, context)

	case *codedom.DynamicAccessNode:
		return eg.generateDynamicAccess(e, context)

	case *codedom.NestedTypeAccessNode:
		return eg.generateNestedTypeAccess(e, context)

	case *codedom.MemberReferenceNode:
		return eg.generateMemberReference(e, context)

	case *codedom.StaticMemberReferenceNode:
		return eg.generateStaticMemberReference(e, context)

	case *codedom.MemberCallNode:
		return eg.generateMemberCall(e, context)

	case *codedom.RuntimeFunctionCallNode:
		return eg.generateRuntimeFunctionCall(e, context)

	case *codedom.FunctionDefinitionNode:
		return eg.generateFunctionDefinition(e, context)

	case *codedom.NativeAccessNode:
		return eg.generateNativeAccess(e, context)

	case *codedom.NativeMemberAccessNode:
		return eg.generateNativeMemberAccess(e, context)

	case *codedom.NativeAssignNode:
		return eg.generateNativeAssign(e, context)

	case *codedom.NativeIndexingNode:
		return eg.generateNativeIndexing(e, context)

	case *codedom.NominalWrappingNode:
		return eg.generateNominalWrapping(e, context)

	case *codedom.NominalUnwrappingNode:
		return eg.generateNominalUnwrapping(e, context)

	case *codedom.CompoundExpressionNode:
		return eg.generateCompoundExpression(e, context)

	case *codedom.TernaryNode:
		return eg.generateTernary(e, context)

	default:
		panic(fmt.Sprintf("Unknown CodeDOM expression: %T", expression))
	}
}


text:
! RUN: %f18_with_includes -fdebug-pre-fir-tree -fparse-only %s | FileCheck %s

! Test Pre-FIR Tree captures all the coarray related statements

! CHECK: Subroutine test_coarray
Subroutine test_coarray
  use iso_fortran_env, only: team_type, event_type, lock_type
  type(team_type) :: t
  type(event_type) :: done
  type(lock_type) :: alock
  real :: y[10,*]
  integer :: counter[*]
  logical :: is_master
  ! CHECK: <<ChangeTeamConstruct>>
  change team(t, x[5,*] => y)
    ! CHECK: AssignmentStmt
    x = x[4, 1]
  end team
  ! CHECK: <<EndChangeTeamConstruct>>
  ! CHECK: FormTeamStmt
  form team(1, t)

  ! CHECK: <<IfConstruct>>
  if (this_image() == 1) then
    ! CHECK: EventPostStmt
    event post (done)
  else
    ! CHECK: EventWaitStmt
    event wait (done)
  end if
  ! CHECK: <<EndIfConstruct>>

  ! CHECK: <<CriticalConstruct>>
  critical
    ! CHECK: AssignmentStmt
    counter[1] = counter[1] + 1
  end critical
  ! CHECK: <<EndCriticalConstruct>>

  ! CHECK: LockStmt
  lock(alock)
  ! CHECK: PrintStmt
  print *, "I have the lock"
  ! CHECK: UnlockStmt
  unlock(alock)

  ! CHECK: SyncAllStmt
  sync all
  ! CHECK: SyncMemoryStmt
  sync memory
  ! CHECK: SyncTeamStmt
  sync team(t)

  ! CHECK: <<IfConstruct>>
  if (this_image() == 1) then
    ! CHECK: SyncImagesStmt
    sync images(*)
  else
    ! CHECK: SyncImagesStmt
    sync images(1)
  end if
  ! CHECK: <<EndIfConstruct>>

  ! CHECK: <<IfConstruct>>
  if (y<0.) then
    ! CHECK: FailImageStmt
   fail image
  end if
  ! CHECK: <<EndIfConstruct>>
end


text:
'use strict';

var errorGenerator = function errorGenerator (message, code, status) {

	var error = new Error(message || 'Page not found');

	error.status = status || 404;
	error.code = code || '';

	return error;

};

module.exports = {

	age : function(req, res, next) {

		// Just testing the error handler
		return next(errorGenerator('Sorry, I cannot tell you may age.'));

	},

	style : function(req, res, next) {

		res.send('Shotokan Karate is my favourite style.');

	},

	weapon : function(req, res, next) {

		var response = 'Kusarigama is my favourite weapon.';
		response += req.ninja.filtered || ' - Unfiltered';
		response += req.ninja.validated || ' - Unvalidated';

		res.send(response);

	},

	legend : function(req, res, next) {

		res.send('I received the legend: ' + req.body.legend.trim());

	},

	timeout : function(req, res, next) {

		setTimeout(function() {
			if (!req.timedout) {
				res.status(200).end();
			}
		},  5000);

	}

};


text:
package jkind.api;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jkind.JKindException;
import jkind.api.results.JKindResult;
import jkind.api.workarounds.WorkaroundKind2ForwardReference;
import jkind.api.xml.XmlParseThread;
import jkind.lustre.Program;
import jkind.lustre.visitors.Kind2ArraysPrettyPrintVisitor;

import org.eclipse.core.runtime.IProgressMonitor;

/**
 * The primary interface to Kind2.
 */
public class Kind2Api extends KindApi {
	public static final String KIND2 = "kind2-arrays";
	private static final long POLL_INTERVAL = 100;

	/**
	 * Run Kind on a Lustre program
	 *
	 * @param program
	 *            Lustre program
	 * @param result
	 *            Place to store results as they come in
	 * @param monitor
	 *            Used to check for cancellation
	 * @throws jkind.JKindException
	 */
	@Override
	public void execute(Program program, JKindResult result, IProgressMonitor monitor) {
		program = WorkaroundKind2ForwardReference.program(program);
		Kind2ArraysPrettyPrintVisitor kind2Printer = new Kind2ArraysPrettyPrintVisitor();
		program.accept(kind2Printer);
		execute(kind2Printer.toString(), result, monitor);
	}

	/**
	 * Run Kind2 on a Lustre program
	 *
	 * @param lustreFile
	 *            File containing Lustre program
	 * @param result
	 *            Place to store results as they come in
	 * @param monitor
	 *            Used to check for cancellation
	 * @throws jkind.JKindException
	 */
	@Override
	public void execute(File lustreFile, JKindResult result, IProgressMonitor monitor) {
		debug.println("Lustre file", lustreFile);
		try {
			callKind2(lustreFile, result, monitor);
		} catch (JKindException e) {
			throw e;
		} catch (Throwable t) {
			throw new JKindException(result.getText(), t);
		}
	}

	private void callKind2(File lustreFile, JKindResult result, IProgressMonitor monitor)
			throws IOException, InterruptedException {
		ProcessBuilder builder = getKind2ProcessBuilder(lustreFile);
		debug.println("Kind 2 command: " + ApiUtil.getQuotedCommand(builder.command()));
		Process process = null;
		XmlParseThread parseThread = null;
		int code = 0;

		try {
			result.start();
			process = builder.start();
			parseThread = new XmlParseThread(process.getInputStream(), result, Backend.KIND2);
			parseThread.start();
			while (!monitor.isCanceled() && parseThread.isAlive()) {
				sleep(POLL_INTERVAL);
			}
		} finally {
			if (process != null) {
				process.destroy();
				code = process.waitFor();
			}

			if (parseThread != null) {
				parseThread.join();
			}

			if (monitor.isCanceled()) {
				result.cancel();
			} else {
				result.done();
			}
			monitor.done();

			if (code != 0 && !monitor.isCanceled()) {
				throw new JKindException("Abnormal termination, exit code " + code);
			}
		}

		if (parseThread.getThrowable() != null) {
			throw new JKindException("Error parsing XML", parseThread.getThrowable());
		}
	}

	private ProcessBuilder getKind2ProcessBuilder(File lustreFile) {
		List<String> args = new ArrayList<>();
		args.add(KIND2);
		args.addAll(getArgs());
		args.add(lustreFile.toString());

		ProcessBuilder builder = new ProcessBuilder(args);
		builder.redirectErrorStream(true);
		return builder;
	}

	protected List<String> getArgs() {
		List<String> args = new ArrayList<>();
		args.add("-xml");
		args.add("-v");
		if (timeout != null) {
			args.add("--timeout_wall");
			args.add(timeout.toString());
		}
		return args;
	}

	protected void sleep(long interval) {
		try {
			Thread.sleep(interval);
		} catch (InterruptedException e) {
		}
	}

	@Override
	public String checkAvailable() throws Exception {
		ProcessBuilder builder = new ProcessBuilder(KIND2, "--version");
		builder.redirectErrorStream(true);
		Process process = builder.start();

		String output = ApiUtil.readAll(process.getInputStream());
		if (process.exitValue() != 0) {
			throw new JKindException("Error running kind2: " + output);
		}
		return output;
	}
}


text:
package question_251;

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}


text:
Project-Magrathea-V3
====================

The Third Generation of the Project Magrathea Terrain Simulator


text:
import React from 'react';
import { Route, IndexRoute, Redirect } from 'react-router';

import CoreLayout from 'layouts/CoreLayout/CoreLayout';
import HomeView from 'views/HomeView/HomeView';
import QuestionView from 'views/QuestionView/QuestionView';
import NotFoundView from 'views/NotFoundView/NotFoundView';

export default (
  <Route path='/' component={CoreLayout}>
    <IndexRoute component={HomeView} />
    <Route path="/question/:name" component={QuestionView}/>
    <Route path='/404' component={NotFoundView} />
    <Redirect from='*' to='/404' />
  </Route>
);


text:
\hypertarget{Route_8hpp}{\section{framework/\-Route.hpp File Reference}
\label{Route_8hpp}\index{framework/\-Route.\-hpp@{framework/\-Route.\-hpp}}
}

A \hyperlink{classRoute}{Route} represents a series of Way Points to be traveled to.

{\ttfamily \#include $<$iostream$>$}\\*
{\ttfamily \#include $<$vector$>$}\\*
{\ttfamily \#include \char`\"{}Path.\-hpp\char`\"{}}\\*
{\ttfamily \#include \char`\"{}Way\-Point.\-hpp\char`\"{}}\\*
\subsection*{Classes}
\begin{DoxyCompactItemize}
\item
class \hyperlink{classRoute}{Route}
\begin{DoxyCompactList}\small\item\em A \hyperlink{classRoute}{Route} represents a series of Way Points to be traveled to. \end{DoxyCompactList}\end{DoxyCompactItemize}

\subsection{Detailed Description}
A \hyperlink{classRoute}{Route} represents a series of Way Points to be traveled to. \begin{DoxyCopyright}{Copyright}
(c) 2017 Mark R. Jenkins. All rights reserved.
\end{DoxyCopyright}
\begin{DoxyAuthor}{Author}
M\-Jenkins, E\-N\-P\-M 808\-X Spring 2017
\end{DoxyAuthor}
\begin{DoxyDate}{Date}
Mar 5, 2017 -\/ Creation
\end{DoxyDate}
Routes are planned as a series of Way Points indicating positions to be traveled to.


text:
namespace Singleton.Logger
{
    using System;
    using System.Collections.Generic;

    public sealed class Logger
    {
        private static readonly Logger logger = new Logger();

        public static Logger Instance
        {
            get
            {
                return logger;
            }
        }

        private List<LogEvent> Events;

        private Logger()
        {
            this.Events = new List<LogEvent>();
        }

        public void SaveToLog(string message)
        {
            this.Events.Add(new LogEvent(message));
        }

        public void PrintLog()
        {
            foreach (var ev in this.Events)
            {
                Console.WriteLine("Time: {0}, Event: {1}", ev.EventDate.ToShortTimeString(), ev.Message);
            }
        }
    }
}


text: __author__ = 'Oleksandr Rypiuk'