text:
---
layout: page
#
# Content
#
subheadline: "Rails and Javascript"
header: false
title: "Adding Javascript to my first rails app"
teaser: "See some of the asynchronous functionality I added to my first rails app"
categories:
  - blog
#tags:
#  -
---

My first rails application, humorously titled Tummy Topics, features a way for users to list their favorite recipes as well as rate and comment on other user's recipes.

Through the use of the popular gems, Devise and CanCan, as well as setting up some complex model associations, I was able to create a fairly functional application that possessed the authentication, authorization and overall features I desired of this basic app.

There was still something missing though. Asynchronous functionality. Whenever a comment was written, a rating was given, or a recipe was edited, a new page would have to be loaded. I wanted a more seamless user experience and therefore would have to utilize javscript to manipulate the DOM (Document Object Model).

## Comments on the fly

The first Asynchronous functionality I wanted to introduce was the ability to create a comment and see it appended to the DOM immediately after submission. I conciously decided to use the rails pattern, 'data-remote=true', to create this funtionality. When you add the data-remote=true attribute to a rails form or link it submits an AJAX request via the jQuery-UJS (unobstrusive javascript) library and prevents the usual page reload of a request. You can view the source for jQuery-UJS [here](https://github.com/rails/jquery-ujs/blob/master/src/rails.js). I wanted to try to employ this convention as it's a much cleaner way of making an AJAX request. Rather than adding a script like this to your view:

{% highlight js%}
$('form').on('submit', function (e) {
	e.preventDefault();
	var values = $(this).serialize()
	$.post('/exampleUrl', values).done(function(data) {
	// some response code here
	});
})
{% endhighlight js%}
Note: the [jQuery.serialize()](https://api.jquery.com/serialize/) method changes a form element into a URL-encoded string.

You can simply add this to your html form element:

{% highlight html%}
<form data-remote='true' action='/exampleurl' >
{% endhighlight%}

The implementation in my Tummy Topics app is as follows:

{% highlight erb %}

	<%= form_for @recipe.comments.build, remote: true, action: comments_path, method: 'post' do |f| %>
		<%= f.hidden_field :recipe_id, value: @recipe.id %>

			<%= f.label "Add a comment" %>
			<%= f.text_area :content, cols: 55, rows: 5, class: "form-control" %>

		<%= f.submit class: "btn btn-primary" %>
	<% end %>

{% endhighlight %}

Rails.js has a script that sets up a listener that responds to the data-remote=true tag and sends an AJAX request to the desired action, in this case `action: /comments` with a `method: POST`. The request is made via Javascript format. Rails leaves it up to you how you'd like to deal with the response, but since javaScript objects can't be rendered in html format, we need to create a format to handle the response.

{% highlight ruby %}
# controllers/comments_controller.rb

def create
	@comment = current_user.comments.build(comment_params)

	respond_to do |f|
		if @comment.save
			f.html { redirect_to recipe_path(@comment.recipe)}
			f.js {}
		else
			f.html { redirect_to :back, alert: "please properly fill in comment field" }
			f.js { render json: @comment.errors, status: :unprocessable_entity }
		end
	end
end

{% endhighlight %}

Here we use the Rails' `respond_to` block which allows responses to be made with different formats. Conventionally Rails responds with html unless otherwise instructed.

You'll notice the curly braces following the js format in the<EMAIL_ADDRESS>section of the `respond_to` block. This makes use of another rails convention which looks for a controller action's corresponding view. Instead of explicity having to tell Rails what template to render like this:

{% highlight ruby %}
# controllers/comments_controller.rb
f.js { action: :create, status: :created, location: @comment }
{% endhighlight %}

We rely on the defaults and create a new corresponding view in the `views/comments` folder titled `create.js.erb`. In `create.js.erb` we can use javaScript to handle the server response:

{% highlight js %}
// views/comments/create.js.erb

html = '<%= j (render @comment) %>'

$('div#comments_display').append(html);
$('#new_comment')[0].reset();
$("#dialog").dialog('open');
{% endhighlight %}

If you're wondering what `j` is, it's an alias for the `escape_javascript` method, which escapes javascript characters so that the corresponding `_comments.html.erb` template being rendered can be properly processed by the html file it's being inserted into.

Note: The [$.dialog()](http://api.jqueryui.com/dialog/) function is a part of the jQuery-UI library and dialog widget. It renders an alert box that can be nicely formatted and comes with some handy built-in features.

Now that I had the ability to save comments to the database and append them to the DOM with ever having to reload the page, I knew there were other parts of my app where I wanted to add the same logic.

## Adding ingredients to a recipe

In my original version of the Tummy Topics app, a user was instructed to enter each ingredient into a text box that looked something like this:

![recipe ingredients image]({{ site.urlimg }}ingredient_shot.png)

Then the custom method `ingredients_attributes=()` I made would parse the input and insert a new row into the `recipe_ingredients` table while creating a new row in the `ingredients` table if it didn't already exist.

{% highlight ruby %}
def ingredient_attributes=(ingredient_attributes)
	ingredient_attributes[:ingredients].split(/\r\n/).each do |ingredient|

		x = ingredient.split("-")
		measurment = x.first.strip
		ingr_name = x.last.strip

		i = Ingredient.find_or_create_by(name: ingr_name.downcase.singularize)

		if !self.ingredients.include?(i)
			self.recipe_ingredients.build(ingredient: i, measurement: measurment, name: ingr_name)
		end
	end
end
{% endhighlight %}

This worked well enough, but left lots of room for error if the directions for adding a '-' and skipping a line weren't followed explicitly by the user. I therefore wanted a way to add ingredient fields as needed. As I've intended to use this app as a way for me to learn, I decided to use plain jQuery rather than Rails' data-remote='true' pattern. To achieve this, I needed to create a separate template and route to be able to pull from and append to my `recipes/new.html.erb` file. I created a button:

{% highlight html %}

<button class='btn btn-primary' id='button' data-url="/recipes/ingredients/new">add another ingredient</button>
{% endhighlight %}

and a template `ingredients/new.html.erb` with the raw html I wanted to append to the `recipes/new` page:

{% highlight html %}

<input class="form-control comment col-md-6" type="text" name="recipe[ingredients_attributes][name]" id="recipe_ingredients_attributes_name" placeholder="Name">
<input class="form-control comment col-md-6 col-md-offset-1" type="text" name="recipe[ingredients_attributes][measurement]" id="recipe_ingredients_attributes_measurement" placeholder="Measurement">
{% endhighlight %}

Using the data attribute introduced in HTML5 is was able to store arbitrary data in the button to be referenced within the jQuery call I would be making to the server like so:

{% highlight js %}
$("button#button").click(function(e) {
	$.get($(this).data('url'), function(response) {
		$('#new-form').append(response);
	});
	e.preventDefault();
});
{% endhighlight %}

This AJAX get request to the route `/recipes/ingredients/new` grabs the raw html stored in the `ingredients/new/html.erb` template and appends it to the DOM, creating a new field to enter an ingredient and measurement into.

Note: In the `ingredients_controller` I made sure to add `layout: false` to the `render` method in the `new` route to make sure the only code I was grabbing was the raw html stored in the `ingredients/new.html.erb` template.

{% highlight ruby %}
# ingredients_controller.rb
def new
	render :new, layout: false
end
{% endhighlight %}

Lastly, I had to change some of my code to account for multiple fields. Using the Rails `fields_for` form helper and a link to the `ingredients/_fields.html.erb` partial, I was able to achieve this. Rails' `fields_for` usually handles the creation of nested forms for you, but in this case, because I was customly adding raw html to the DOM, I had to tell erb directly to store each set of inputs in an array within the params hash being passed to the associated controller upon form submission. So within the input fields I added a `[]` so that erb would recognize more than one set of inputs.

{% highlight html %}

<input class="form-control comment col-md-6" type="text" name="recipe[ingredients_attributes][name]" id="recipe_ingredients_attributes_name" placeholder="Name">
{% endhighlight %}

became:

{% highlight html %}

<input class="form-control comment col-md-6" type="text" name="recipe[ingredients_attributes][][name]" id="recipe_ingredients_attributes_name" placeholder="Name">
{% endhighlight %}

Now if I added multiple fields to the DOM using using javascript, the new fields would still be recognized by Rails and stored correctly in the params hash.

I still had to handle a few more things. Firstly, I needed to white list my `ingredients_attributes` attribute for mass assignment like so:

{% highlight ruby %}
# controllers/recipes_controller.rb
def recipe_params
	params.require(:recipe).permit(:name, :user_id, :description, :directions, :image, ingredients_attributes: [:name, :measurement])
end
{% endhighlight %}

and I needed to make a few changes to the `ingredients_attributes=()` method in my recipes model:

{% highlight ruby %}
# models/recipes.rb
def ingredients_attributes=(ingredients)
		recipe_ingredients.destroy_all if persisted?

		ingredients.each do |ingredient|
			unless ingredient[:name].blank?
				ingr_name = ingredient[:name]
				measurement = ingredient[:measurement]

				i = Ingredient.find_or_create_by(name: ingr_name.downcase.singularize)

				if !ingredients.include?(i)
					recipe_ingredients.build(ingredient: i, measurement: measurement, name: ingr_name)
				end
			end
		end
	end
{% endhighlight %}

After all this, I was able to add new ingredient fields with one click and leave less room for user error:

![ingredients-fields image]({{ site.urlimg }}ingredient-fields.png)

## Scroll and Load

To further add to user experience, I wanted to be able to load recipes on the main index page without having to paginate or click on a link to load more. If this site were ever to actually be populated with a large number of recipes, the index page would take far too long loading the whole list of recipes in one request.

Once again, AJAX to the rescue. I wanted a user to see 9 recipes initially and then be able to scroll to the bottom of the page and have 9 more loaded and so on. To achieve this, I knew I'd have to send a data element to be processed by the controller at which point it could query the database and return the desired amount of recipes.

Before I could do anything though, I realized I'd have to make objects on the client side to be properly parsed and appended to the dom. First, I set up a recipe object that mirrored the recipe model I already had set up in Rails:

{% highlight js %}
// javascripts/recipes.js
function Recipe(id, name, directions, description, user, postDate, comments = null, ratings = null, image) {
	this.id = id
	this.name = name
	this.directions = directions
	this.description = description
	this.user = user
	this.postDate = postDate
	this.comments = comments
	this.ratings = ratings
	this.image = image
}
{% endhighlight %}
Note: notice `comments = null` and `ratings = null`. Settings null options to be passed to an object is a new feature of ECMAScript6.

Then I set up serializers using the `active_model_serializers` gem so that I could retrieve serialized json from the server.

{% highlight ruby %}
# serializers/recipe_serializer.rb
class RecipeSerializer < ActiveModel::Serializer
  attributes :id, :name, :description, :directions, :post_date, :image
  has_many :ratings
  has_many :comments
  has_one :user

  def image
  	object.image.url.tap do |image|
  		if image.match(/default_recipe_image|placeholder_image/)
  			return "/assets/#{image}"
  		end
  	end
  end
end
{% endhighlight %}
Note: I had to set up serializers for my other models to be able to associate them to the recipe serializer which I didn't explicitly show here. You also have the ability to set up custom methods that you can pass to the `attributes` method for serialization, which you can see in my `image` method.

Then I added a `respond_to` block to my `recipes_controller` to handle the json response:

{% highlight ruby %}
# controllers/recipes_controller.rb
def index

	...

	respond_to do |f|
		f.html { render :layout => 'recipe_index' }
	  f.json { render json: @recipes }
	end
end
{% endhighlight %}

which resulted in a json object that I'd be able to pull data from:

{% highlight js %}
// recipes.json
{
	id: 33,
	name: "Chicken stew",
	description: "This is my favorite chicken stew recipe. It's been in the family for years and I really love it!",
	directions: "roast the chicken cut the vegetables cook it up!",
	post_date: "05/06/2016",
	image: "/assets/original/default_recipe_image.jpg",
	ratings: [
		{
			id: 53,
			score: 3
		}
	],
	comments: [ ],
	user: {
		id: 11,
		email<EMAIL_ADDRESS>		thumb: "/system/users/avatars/000/000/011/thumb/brett.jpeg?1463692192",
		email_name: "Brett"
	}
}
{% endhighlight %}

Now that I had a properly formatted json object to pull from, I needed to create some functions that would be able to grab the data from the json response, format it, and properly append it to the DOM.

The most difficult thing to figure out was how to format the response and be able to make it look exactly like the recipe objects that already existed in the DOM. Since these were formatted using Rails methods and erb, I had to find a way to create a template that would mirror these objects. I decided to use `Handlebars.js` which is a great formatting tool. I won't go into it in too much detail here, but it lets you dynamically add variables to html in a similar way erb allows you to add Ruby variables to your views.

So I created a template to pull from in my `recipes/index.html.erb` file:

{% highlight html %}
{% raw %}

			{{name}}

Posted on: {{recipe.postDate}}

			{{#if rating}}

 ({{ratingLength}})

			{{/if}}
			{{#if recipe.comments}}
				<button name="button" type="submit" class="see-comments btn btn-default collapsed" data-id="{{recipe.id}}" data-toggle="collapse" data-target="#collapse{{recipe.id}}" aria-expanded="false">See Comments</button>

					{{#each recipe.comments}}

{{this.content}}

Posted on: {{this.post_date}}

								By: {{this.commenter.email_name}}

					{{/each}}

			{{/if}}

				Recipe by: {{user.email_name}}

{% endraw %}
{% endhighlight %}

Note: The double curly braces denote Handlebars syntax that act as variables or boolean/iteration blocks. You can read the handlebars docs [here](http://handlebarsjs.com/)

So in my `recipe.js` file I set up functions to format and append the new recipe object I created from each json response to the DOM:

{% highlight js %}
// javascripts/recipes.js

// create new recipe object from json
function createRecipe(recipe) {
	var newRecipe = new Recipe(
				recipe.id,
				recipe.name,
				recipe.directions,
				recipe.description,
				recipe.user,
				recipe.post_date,
				recipe.comments,
				recipe.ratings,
				recipe.image
	);
	return newRecipe;
}

// format the new recipe object to be inserted into template. This includes assigning key/value pairs to be used within the handlebars template
// I created the openRow and closeRow variables for bootstrap formatting. This allowed me to dynamically set rows of three for displaying the recipes.
function formatForTemplate(recipe, openRow = false, closeRow = false) {
	var values = {
		name: recipe.name.titleize(),
		recipe: recipe,
		user: recipe.user
	};

	if (recipe.ratings.length > 0) {
		values["rating"] = recipe.ratingAvg();
		values["ratingLength"] = recipe.ratings.length;
	};
	if (openRow === true) {
		values["open"] = true;
	};
	if (closeRow === true) {
		values["close"] = true;
	};
	return values;
};

// take all recipes from json response, parse them, and append them to the DOM via a handlebars template
function parseAndDisplay(recipes) {
	inGroupsOf(recipes, 3).forEach(function(group) {
		var source = $("#recipe-template").html();
		var template = Handlebars.compile(source);
		var recipeRow = '
';
		group.forEach(function(recipe) {
			if (recipe !== null) {
				var rec = createRecipe(recipe);

				recipeRow += template(formatForTemplate(rec));
			}
		});
		recipeRow += '
';
		$('#recipes').append(recipeRow);
		displayRating();
	});
}
{% endhighlight %}

Then I created a script to request 9 recipes at a time when scrolling to the bottom of the page:

{% highlight js %}
// recipes.index.html.erb

// script in the recipes/index view that requests 9 recipe objects upon scrolling to the bottom of the page and then appends them to the DOM
var data = { limit: 0 };
$(window).scroll(function() {
	if ($('#recipes').data('is-searched') === false) {
    if($(window).scrollTop() + $(window).height() == $(document).height()) {
     	data["limit"] += 9;
      getMoreRecipes(data);
    }
  };
});

function getMoreRecipes(data) {
	$.get('/recipes.json', data, function(response) {
		var recipes = response.recipes;
		parseAndDisplay(recipes);
	});
}
{% endhighlight %}

and the corresponding call in the `recipes_controller`

{% highlight ruby %}
# controllers/recipes_controller.rb
def index
	if params[:user_id]
		@recipes = User.find(params[:user_id]).recipes.alphabetized
	else
		@recipes = Recipe.alphabetized.limit(9).offset(params[:limit])
	end
	respond_to do |f|
		f.html { render :layout => 'recipe_index' }
	  f.json { render json: @recipes }
	end
end
{% endhighlight %}

This created a much smoother user experience. Instead of having to paginate, the user simply scrolls to the bottom and the next set of recipes appears on the page.

## Errors

I found the most difficult part of using AJAX calls to be the error handling. As Rails usually does this for you by adding a `.field_with_errors` class to the form and appending error messages for you, I had to figure out how to do this with plain javaScript calls.

After reading a few tutorials, I found the best way to do this was to set up a universal event listener pertaining to the javaScript events fired during an AJAX call. In the event of an error, the `ajaxError` event would be triggered and I'd be able to parse the response and append it to the form. In the case of creating a comment I added this event listener:

{% highlight js %}
// javascripts/recipes.js

//look for ajax response. if success fire event clear error message if any, if error, fire event and append error message to form
$(document).bind('ajaxSuccess','form#new_comment', function(event, xhr, settings) {
	if (settings.url === '/comments') {
		$('.form-group.has-error').each(function(){
	    $('.help-block', $(this)).html('');
	    $(this).removeClass('has-error');
	  });
	}
})
.bind('ajaxError','form#new_comment', function(event, xhr, settings) {
	if (settings.url === '/comments') {
		$('.alert').remove();
		if (xhr.status === 500) {
			$("#comment_form").children('.panel-body').prepend('
<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>Please sign in to create a comment!
');
		} else {
			$('textarea#comment_content').closest(".form-group").addClass('has-error')
			.find('.help-block').html($.parseJSON(xhr.responseText).content);
		};
	}
})
{% endhighlight %}

I believe in rails you can bind directly to the events triggered via jQuery-UJS. Hence,

{% highlight js %}
$(document).bind('ajaxError','form#new_comment', function(event, xhr, settings) {});
{% endhighlight %}

could become

{% highlight js %}
$('form#new_comment').bind('ajax:error', function(event, xhr, settings) {});
{% endhighlight %}

but in this case the first version worked well for me, so I stuck with it.

## Thoughts and TODOs

This was an immensly helpful project that really expanded my knowledge of javaScript and how to add asynchronous functionality to an application. I've gained a new respect and interest for javaScript and hope to learn more ways to incorporate it's functionality into my projects.

I still feel that my app has a few things left to be improved. Firstly, I was able to create functionality for lazily loading recipes on the index page, but I ran into an issue when using the search function within the index page. I had to insert a data attribute that would keep arbitrary recipes from being loaded upon page scroll after a certain search query was made. For now this works because I have so few recipes to search through, but if there were a much larger dataset, I'd want to create functionality that allowed for lazily loading results of a query as well, rather than just appending all the results at once.

I also want to improve the search functionality I created. It's not very accurate and I'd love to incorporate auto-complete functionality for a better user experience. I tried to use the rails `auto-complete` gem but had difficulty getting the results to render correctly due to the way I have my associations set up.

Creating this app was a great experience and I can't wait to work more with javaScript and it's exciting libraries and frameworks!


text:
# mac_nonet
Disable access to networking for certain group

To test, clone the repo and run `make && make load` in the module directory.  The load action require root permissions.

Set gid that shouldn't access the network: `sysctl security.mac.nonet.gid=31337` and enable enforcing:
`sysctl security.mac.nonet.enabled=1`.  Any call to `socket(2)` from user in this group will end with `EPERM`.

You can also select group that can access only `AF_UNIX` sockets with `security.mac.nonet.local_gid`.

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
---
num: "h02"
desc: "Variables and assignments, input/output, data types and expressions, simple flow control"
ready: true
assigned: 2018-07-03 08:00:00.00-7:00
due: 2018-07-10 11:00:00.00-7:00
reading: "Section 1.3, Sections 2.1 - 2.4"
---

Reading: {{page.reading}}

(10 pts) Fill in the information in the header. The following are required to get the 10 "participation" points.

Filling in your name and umail address.

Also: For paper submission PLEASE submit on ONE SHEET OF PAPER, double-sided if at all possible. If you must submit on two printed sheets write name on BOTH sheets and no staples, paperclips, or folded corners.

 (9 pts) The author describes the difference between "syntax errors" and "logic errors", and also the difference between syntax errors that produce an "error message" vs. those that produce a "warning message".  Briefly explain each of the items below in a way that makes the DIFFERENCES among them clear:

  i. Syntax errors that result in an error message:

  ii. Syntax errors that result in an warning message:

  iii. Logic errors:

 (2 pts) If the following statement were in a C++ program, what would it do? Write the correct statement if there is a syntax error.

cout >> "I love oranges and apples";

 (2 pts) If the following statement were in a C++ program, what would it do? Write the correct statement if there is a syntax error.

cout << "The world goes round and round"

 (4 pts) Show 2 different ways to initialize variables in C++?

 (4 pts) Is this variable declaration statement in C++ a good one? Why or why not?

`double int = 30;`

 (4 pts) How do you write the following in ONE LINE in C++: Subtract a from b and add that sum to c, then divide that result by d, and store the final result in e? Assume all variables are of type double.

 (5 pts) Explain via an example what a "type mismatch" is. Also explain how compilers handle C++ statements that have a type mismatch?

 (6 pts) Write an if-else statement that outputs the string "Grade is B" if the variable score is between 80 and 90 inclusively. Otherwise the if-else statement should output "Grade is not B"?

 (4 pts) What is the output of the following C++ statements? Explain why.

```
int x = 20, y = 5;

bool v, w;

v = (x != y);

w = ((x /= y) == 4);

cout << x << " " << y << " " << v << " " << w << endl;

```

license: MIT

gha_license_id: MIT


text:
## List notes

### List project wall notes

Get a list of project wall notes.

```
GET /projects/:id/notes
```

```json
[
  {
    "id": 522,
    "body": "The solution is rather tricky",
    "author": {
      "id": 1,
      "username": "john_smith",
      "email"<EMAIL_ADDRESS>      "name": "John Smith",
      "blocked": false,
      "created_at": "2012-05-23T08:00:58Z"
    },
    "created_at": "2012-11-27T19:16:44Z"
  }
]
```

Parameters:

+ `id` (required) - The ID of a project

### List merge request notes

Get a list of merge request notes.

```
GET /projects/:id/merge_requests/:merge_request_id/notes
```

Parameters:

+ `id` (required) - The ID of a project
+ `merge_request_id` (required) - The ID of an merge request

### List issue notes

Get a list of issue notes.

```
GET /projects/:id/issues/:issue_id/notes
```

Parameters:

+ `id` (required) - The ID of a project
+ `issue_id` (required) - The ID of an issue

### List snippet notes

Get a list of snippet notes.

```
GET /projects/:id/snippets/:snippet_id/notes
```

Parameters:

+ `id` (required) - The ID of a project
+ `snippet_id` (required) - The ID of a snippet

## Single note

### Single wall note

Get a wall note.

```
GET /projects/:id/notes/:note_id
```

Parameters:

+ `id` (required) - The ID of a project
+ `note_id` (required) - The ID of a wall note

### Single issue note

Get an issue note.

```
GET /projects/:id/issues/:issue_id/:notes/:note_id
```

Parameters:

+ `id` (required) - The ID of a project
+ `issue_id` (required) - The ID of a project issue
+ `note_id` (required) - The ID of an issue note

### Single snippet note

Get a snippet note.

```
GET /projects/:id/issues/:snippet_id/:notes/:note_id
```

Parameters:

+ `id` (required) - The ID of a project
+ `snippet_id` (required) - The ID of a project snippet
+ `note_id` (required) - The ID of an snippet note

## New note

### New wall note

Create a new wall note.

```
POST /projects/:id/notes
```

Parameters:

+ `id` (required) - The ID of a project
+ `body` (required) - The content of a note

Will return created note with status `201 Created` on success, or `404 Not found` on fail.

### New issue note

Create a new issue note.

```
POST /projects/:id/issues/:issue_id/notes
```

Parameters:

+ `id` (required) - The ID of a project
+ `issue_id` (required) - The ID of an issue
+ `body` (required) - The content of a note

Will return created note with status `201 Created` on success, or `404 Not found` on fail.

### New snippet note

Create a new snippet note.

```
POST /projects/:id/snippets/:snippet_id/notes
```

Parameters:

+ `id` (required) - The ID of a project
+ `snippet_id` (required) - The ID of an snippet
+ `body` (required) - The content of a note

Will return created note with status `201 Created` on success, or `404 Not found` on fail.

repository: dasbh/gitlabhq

repo_name: dasbh/gitlabhq


text:
---
title: How to speed up a slow SSH login
author: Kev
layout: post
permalink: /how-to-speed-up-a-slow-ssh-login/
redirect_from: /2013/10/10/how-to-speed-up-a-slow-ssh-login/
dsq_needs_sync:
  - 1
categories:
  - Cloud
  - Linux
tags:
  - login
  - server
  - ssh
---
I recently started using the excellent digital ocean for some of my cloud server hosting. When logging into my servers there was quite a delay, often a minute or more, before the password prompt appeared. I was getting the same delay when I use SSH keys for authentication too.

I've had to solve this problem before on several occasions, but I always end up re-investigating the cause. So this time I thought it was about time I made a note of how  to fix the problem.

Right! First off let's see where the delay is by logging on the the server with the ssh debugging enabled. This is done by using the -v switch:
{% highlight bash %}
ssh -v root@server-ip-address
{% endhighlight %}

This shows conversation that the ssh client is having with the server as it negotiates a suitable authentication method.

For me, whenever I see long pauses in the login it's always because ssh hangs whenever it checks for GSSAPI. Apparently GSSAPI stands for Generic Security Service Application Program Interface.

So, the ssh debug info generally scrolls by pretty swiftly until it gets to:

{% highlight console %}
debug1: Next authentication method: gssapi-with-mic
{% endhighlight %}

Then ssh just hangs for a while before reporting something along the lines of
{% highlight console %}
debug1: Unspecified GSS failure
{% endhighlight %}

The fix is to simple disable GSSAPI as an ssh authentication option. This is done by editing the ssh server configuration file:
{% highlight bash %}
/etc/ssh/sshd_config
{% endhighlight %}

Search for the line:
{% highlight console %}
GSSAPIAuthentication yes
{% endhighlight %}

and change yes to no; i.e.:
{% highlight console %}
GSSAPIAuthentication no
{% endhighlight %}

After applying and saving the above change you'll need to restart the sshd daemon. On most systems this can be done by typing:
{% highlight bash %}
service sshd restart
{% endhighlight %}

Now next time you connect to your server with ssh, it should all happen much faster.

Update – Alternative (client side work-around)
An alternative to fixing the server side, you also switch GSSAPIAuthentication off as an authentication option every time you connect. Note that this will only affect that single connection, so you'll need to specifiy the option every time you connect.
{% highlight bash %}
ssh -o GSSAPIAuthentication=no root@server-ip-address
{% endhighlight %}


text:
### Postgres Tree: ActiveRecord tree structures using PostgreSQL.

Include PostgresTree::ActiveRecordConcern in your models along with a parent_id field and get access to ancestors or descendents in one query.

[![Build Status](https://travis-ci.org/dyson/postgres_tree.svg?branch=master)](https://travis-ci.org/dyson/postgres_tree) [![Coverage Status](https://img.shields.io/coveralls/dyson/postgres_tree.svg)](https://coveralls.io/r/dyson/postgres_tree?branch=master) [![Gem Version](https://badge.fury.io/rb/postgres_tree.svg)](http://badge.fury.io/rb/postgres_tree)

----

#### Requirements

Gems:
* rails ~> 4.0
* pg

#### Installation

##### Gemfile

Add to your Gemfile:

```ruby
gem 'postgres_tree'
```

Or lock it to the current backwards compatible version:

```ruby
gem 'postgres_tree', '~> 0.0.2'
```

##### Migration

Add a parent_id field to your model via a migration. For example, a roles table:

```ruby
class AddParentIdToRoles < ActiveRecord::Migration
  def change
    change_table :roles do |t|
      t.integer :parent_id
    end

    add_index :roles, [:parent_id]
  end
end
```

##### Model

```ruby
class Role < ActiveRecord::Base

  include PostgresTree::ActiveRecordConcern

  # Add some extra (optional) associations if you want to use them
  belongs_to :parent, class_name: "Role"
  has_many :children, class_name: "Role", foreign_key: 'parent_id'

end

```

#### Methods

* role.**ancestors** - Get all ancestors.
* role.**self_and_ancestors** - Get all ancestors and include self in the returned result.
* role.**descendents** - Get all descendents.
* role.**self_and_descendents** - Get all descendents and include self in the returned result.

There is also an **_include?** method missing which returns **true** of **false**:

* role.**ancestors_include?** (object of same type)
* role.**self_and_ancestors_include?** (object of same type)
* role.**descendents_include?** (object of same type)
* role.**self_and_descendents_include?** (object of same type)

Using the self referencing belongs and has_many as above, you also get get the parent and children:

* role.**parent**
* role.**children**
* role.**children_include?**

#### Scopes

A named scope called tree_roots is also added to the model to obtain all root records:

```ruby
root_roles = Role.tree_roots
```

#### Usage example

```ruby
irb(main):001:0> parent = Role.find 2
=> #<Role id: 2, name: "Parent", parent_id: 1>

irb(main):002:0> parent.ancestors
=> [#<Role id: 1, name: "Grandparent", parent_id: nil>]

irb(main):003:0> parent.self_and_ancestors
=> #<ActiveRecord::Relation [#<Role id: 1, name: "Grandparent", parent_id: nil>, #<Role id: 2, name: "Parent", parent_id: 1>]>

irb(main):004:0> parent.descendents
=> [#<Role id: 3, name: "Child", parent_id: 2>]

irb(main):005:0> parent.self_and_descendents
=> #<ActiveRecord::Relation [#<Role id: 2, name: "Parent", parent_id: 1>, #<Role id: 3, name: "Child", parent_id: 2>]>

irb(main):006:0> child = Role.find 3
=> #<Role id: 3, name: "Child", parent_id: 2>

irb(main):007:0> parent.descendents_include? child
=> true

irb(main):008:0> parent.self_and_descendents_include? child
=> true

irb(main):009:0> parent.ancestors_include? child
=> false

irb(main):010:0> parent.self_and_ancestors_include? child
=> false
```

#### License

The MIT License (MIT)

Copyright 2014 Dyson Simmons

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

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

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


text:
---
layout: post
title: hoW this jeKYLL thing WorkZZZ!
---

update the site
====

you can update your site name, avatar and other options using the _config.yml file in the root of your repository (shown below).

![_config.yml]({{ site.baseurl }}/images/config.png)

The easiest way to make your first post is to edit this one. Go into /_posts/ and update the Hello World markdown file. For more instructions head over to the [Jekyll Now repository](https://github.com/barryclark/jekyll-now) on GitHub.

how to files
====
Assuming you have your gallery images in a structure like

    -img
      -gallery
        -image1.png
        -image2.png

    etc.

you can access 'img/gallery' them in a collection or page like this:

    {% for image in site.static_files %}
    {% if image.path contains 'img/gallery' %}

{{image.path}} - {{image.modified_time}}

    {% endif %}
    {% endfor %}

Start images:

{% for image in site.static_files %}
{% if image.path contains 'img/gallery' %}

{{image.path}} - {{image.modified_time}}

{% endif %}
{% endfor %}

Stop images:

This goes through all static files and check for a certain path (img/gallery in this example).

Than you can access the static file metadata for that file. (I named it 'image' in this example but you can name it whatever you want after the for keyword).

I think it doesn't make too much sense to put something like this in a blog post but rather in a page or a collection.

gha_language: CSS


text:
# Class: Relationship

URI: [ks:Relationship](https://w3id.org/linkml/tests/kitchen_sink/Relationship)

## Inheritance

* **Relationship**
    * [FamilialRelationship](FamilialRelationship.md)

## Slots

| Name | Range | Cardinality | Description  | Info |
| ---  | --- | --- | --- | --- |
| [started_at_time](started_at_time.md) | [date](date.md) | 0..1 | None  | . |
| [ended_at_time](ended_at_time.md) | [date](date.md) | 0..1 | None  | . |
| [related_to](related_to.md) | NONE | 0..1 | None  | . |
| [type](type.md) | NONE | 0..1 | None  | . |

## Usages

## Identifier and Mapping Information

## LinkML Specification

<!-- TODO: investigate https://stackoverflow.com/questions/37606292/how-to-create-tabbed-code-blocks-in-mkdocs-or-sphinx -->

### Direct

<details>
```yaml
name: Relationship
from_schema: https://w3id.org/linkml/tests/kitchen_sink
slots:
- started at time
- ended at time
- related to
- type

```
</details>

### Induced

<details>
```yaml
name: Relationship
from_schema: https://w3id.org/linkml/tests/kitchen_sink
attributes:
  started at time:
    name: started at time
    from_schema: https://w3id.org/linkml/tests/core
    slot_uri: prov:startedAtTime
    alias: started_at_time
    owner: Relationship
    range: date
  ended at time:
    name: ended at time
    from_schema: https://w3id.org/linkml/tests/core
    slot_uri: prov:endedAtTime
    alias: ended_at_time
    owner: Relationship
    range: date
  related to:
    name: related to
    from_schema: https://w3id.org/linkml/tests/kitchen_sink
    alias: related_to
    owner: Relationship
  type:
    name: type
    from_schema: https://w3id.org/linkml/tests/kitchen_sink
    alias: type
    owner: Relationship

```
</details>

repository: linkml/linkml

branch_name: refs/heads/main

gha_language: Python

repo_name: linkml/linkml


text:
# A Hitchhiker's Guide To Quantum Computing PESU I/O

> Create a seperate directory/folder named after you and submit all assignments in that directory *only.* Send a PR for the same.

## For writeups on specific topics, follow the below mentioned naming convention for your files:
`name_week-no._write-up.pdf`
Make sure all your submissions for writeups are in `pdf` format.

## For coding assignments, do the following:
Your filename should be in the format: `name_week-no._code.py`


text:
  My portfolio website

Built with React, Gatsby and animated with React Spring.

## 🚀 To start

1.  **Yarn**

    I used yarn as my package manager. Use the yarn command in the terminal to install all dependencies.

    ```sh
      cd portfolio/
      yarn
    ```

1.  **Start developing.**

    Start using the yarn start command. I've also added a "yarn pull-content" command if you have made updates on the CMS this will pull down the content changes and refresh the cache, avoiding issues with gatsby-image.

    ```sh
    yarn start
    ```

    or

    ```sh
    yarn pull-content
    ```

repository: nitro-neal/portfolio

repo_name: nitro-neal/portfolio


text:
<img height="100px" width="100px" src="https://rawgithub.com/benatespina/amptwigtheme/master/docs/logo.jpg" align="right"/>

# AMP Twig Theme
> AMP oriented theme for Twig template engine

[![Build Status](https://travis-ci.org/benatespina/AMPTwigTheme.svg?branch=master)](https://travis-ci.org/benatespina/AMPTwigTheme)
[![Total Downloads](https://poser.pugx.org/benatespina/amp-twig-theme/downloads)](https://packagist.org/packages/benatespina/amp-twig-theme)
[![Latest Stable Version](https://poser.pugx.org/benatespina/amp-twig-theme/v/stable.svg)](https://packagist.org/packages/benatespina/amp-twig-theme)
[![Latest Unstable Version](https://poser.pugx.org/benatespina/amp-twig-theme/v/unstable.svg)](https://packagist.org/packages/benatespina/amp-twig-theme)

## Requirements
PHP >= 7.0

## Installation
The easiest way to install this bundle is using [Composer][2]
```bash
$ composer require benatespina/amp-twig-theme
```

## Documentation
All the documentation is stored in the `docs` folder.

[Show me the docs!](docs/index.md)

## Tests
You can easily start a simple application based on Symfony framework to test the AMP Twig theme.
```bash
$ cd tests/Application
$ bin/console assets:install --symlink --relative
$ bin/console --docroot=public
$ open http://<IP_ADDRESS>:8000
```

## Contributing
This library follows Twig coding standards, so pull requests need to execute the Allocine's [TwigCs][1]. In order
to simplify we provide a Composer script that wraps all the commands related with this process.
```bash
$ composer run-script cs
```

There is also a policy for contributing to this bundle. Pull requests must be explained step by step to make the
review process easy in order to accept and merge them.

## Credits
This theme is created by:
>
**@benatespina** - [benatespina<EMAIL_ADDRESS>
## Licensing Options
[![License](https://poser.pugx.org/benatespina/amp-twig-theme/license.svg)](https://github.com/benatespina/AMPTwigTheme/blob/master/LICENSE)

[1]: https://github.com/allocine/twigcs
[2]: http://getcomposer.org

repository: elbakerino/AMPTwigTheme

repo_name: elbakerino/AMPTwigTheme


text:
## QuickStarts

QuickStarts is a series of examples to get you started deploying and running applications with Fabric8.

The examples is categorized into a beginner section, and sections for experienced users. New users to Fabric8 is recommended to start with the beginner quickstarts.

Each QuickStart is documented as follows:

1. A brief description of the example
1. System requirements
1. How to build the example
1. How to run the example either using the command line or using the web console
1. How to try the example
1. How to uninstall the example
1. Optional suggested readings

### Beginner QuickStarts

The beginner quickstarts is located at

* [beginner](https://github.com/fabric8io/fabric8/tree/master/quickstarts/beginner)

First time users of Fabric is recommended to try the [Camel Content Based Router](https://github.com/fabric8io/fabric8/tree/master/quickstarts/beginner/camel-cbr) quickstart.

### WebService and REST QuickStarts

There is a set of web service and REST quickstart that comes with and without security enabled.

* [SOAP](https://github.com/fabric8io/fabric8/tree/master/quickstarts/soap) - A SOAP web servie
* [SOAP secure](https://github.com/fabric8io/fabric8/tree/master/quickstarts/secure-soap) - A secured SOAP web servie

* [REST](https://github.com/fabric8io/fabric8/tree/master/quickstarts/rest) - A SOAP web servie
* [REST secure](https://github.com/fabric8io/fabric8/tree/master/quickstarts/secure-rest) - A secured SOAP web servie

There is also a REST quickstart deployable as a WAR into web containers such as Apache Tomcat, Jetty, or JBoss WildFly.

* [REST WAR](https://github.com/fabric8io/fabric8/tree/master/quickstarts/rest-war)

### JMS QuickStarts

There is a JMS example demonstrating using pure JMS Client API to connect to an existing A-MQ broker running in the fabric.

* [JMS Client](https://github.com/fabric8io/fabric8/tree/master/quickstarts/jms)


text:
# Three Short Words

![screenshot](fuzzy_thesaurus_screenshot.png)

## Premise

I often find online thesauri to be frustrating because every word generates a huge number of synonym results, with the same words each occuring several times in different tenses and contexts. Usually when I use a thesaurus I have some additional information about the meaning or context that I am going for, but no way to include it in the search. This is an early prototype of a more flexible thesaurus that looks for the intersection of two words.

## Live

http://www.threeshortwords.com

## Deployment Instructions

### Get a WordsAPI key

Currenntly this app is set up to use the WordsAPI(www.wordsapi.com) as its reference, which requires the server to submit an API key. [API keys are available through the Mashape Marketplace.](https://market.mashape.com/wordsapi/wordsapi/pricing) They are free for up to 2500 API calls per day but do require a credit card to set up.

Add the API key to an environment variable

```
echo 'export WORDS_API_KEY="your individual api key"' >> ~/.bashrc
source ~/.bashrc
```
### Setup Server

```
git clone https://github.com/rasnom/threeshortwords.git
cd threeshortwords
bundle install
rails db:create
rails db:migrate
rails server
```

## API

This is not a CRUD app so a REST API is not necessarily appropriate. Instead the API focuses on simple usability for the few specific use cases. Calls to /thesaurus accept a list of words as a parameter and return a list of shared synonyms. The full documentaion is available in OpenAPI format in [openapi.yaml](openapi.yaml).

## Tech Stack

* Ruby (2.3.1)
* Rails (5.1.3)
* [WordsAPI](www.wordsapi.com)

## Next Steps

* ~~Account for unknown and misspelled words~~
* ~~Basic API~~
* Second draft layout and styling
 * Create stand alone client side app that uses the API
* Contextual routing
* Refactor for cleanliness
* Broaden scope of API calls if necessary (add more fuzzyness until you get a reasonable set of results)
* Cache API call results

## Licensing

This project is licensed under [MIT license](./LICENSE)

repository: rasnom/threeshortwords

gha_language: Ruby

repo_name: rasnom/threeshortwords


text:
# Astrobox
This project is a space sandbox game written in C++ using the SFML library. I am a beginner to C++ and the only C++ project I have created before this one was very small. I have a good amount of comments in the source code right now so if you are interested in programming or experienced feel free to explore. I hope to have friends contribute to this in the future, although right now I don't know what I could have other people help with. Feel free to fork the repository and explore or make changes, though.

[Just download the exe file](https://github.com/Jayx20/Astrobox/raw/master/Astrobox/build/Astrobox.exe)
Sadly this game is Windows only at the moment, as much as I love Linux it is easier to work with just Windows.

/src holds the source code
/lib and /include house the sfml libraries

The Astrobox folder is for my codeblocks setup and holds the exe


text:
# language-model-converter

This is a tool to convert language files defined in yaml language model into the [LUIS](http://luis.ai) internal JSON representation.

### The language model
This is a [yaml](http://www.yaml.org/) format file that is conveted to a [JSON file](https://dev.projectoxford.ai/docs/services/56d95961e597ed0f04b76e58/operations/56f8a55119845511c81de480) that LUIS can undestand

Words preceed by `#` are comments, and its purpose is to leave some insights to people that will help on understanding whats going on. These words will be removed when training luis, so feel free to add as much as you want to help next colleagues that will manage the file

```yaml

list.${examples}:  # Defines a example list to make substitutions in the utterances
  - heaven
  - hell

tef.intent.info: # Defines a Luis Intent
  - Tell me about the purgatory # Simple utterance
  - What is ${examples} # Substitution with list: Will generate for you "What is heaven" and "What is hell"

tef.intent.go: # Defines a Luis Intent
  - Go to [purgatory:tef.places] # Defines an entity "tef.places" giving "purgatory" as an example. The example is mandatory
  - Head to [${examples}:tef.places] # You can make substitution in the entity examples too!
  - We will go to [hell:tef.places] from [january 1:tef.date::start] until [december 31:tef.date::enf] # Hierarchical Entities are supported also

phraselist:
  aksforinfo: # ex: How to ask for something synonims:
    words:
      - Tell me about
      - What is

  tef.places: # ex: Place examples here for training entities
    words:
      - heaven
      - hell
      - purgatory
      - home
  # if you want no have a not-exangeable phraselist, add the property `mode: false` to it. Example:
  # tef.relations
  #   mode: false
  #   words:
  #     - leader
  #     - area
  # more info: https://github.com/Microsoft/Cognitive-Documentation/issues/97#issuecomment-265738124

builtin: # LUIS builtin entities that should be used
  - age
  - datetime
  - dimension
  - encyclopedia
  - geography
  - money
  - number
  - ordinal
  - percentage
  - temperature
```

The list of **builtin** entities can be found in the [LUIS Help](https://www.luis.ai/Help#PreBuiltEntities) and/or the [Cognitive Services Help](https://www.microsoft.com/cognitive-services/en-us/luis-api/documentation/pre-builtentities)
Please, read carefully about what entities are available for the target language you are writting utterances to, as
> Unless otherwise noted, each pre-built entity is available in all LUIS application locales (cultures).

_Note: maybe the doc page [is not actualized with all the entities](https://github.com/Microsoft/Cognitive-Documentation/issues/96)_

You dont need to declare with brackets the builtin entities. They are recognized by default on LUIS. I.E:
```yaml
# DONT DO THIS
tef.intent.money:
  - It's worth [$30:builtin.money]

# DO THIS
builtin:
  - money

tef.intent.money:
  - It's worth $30
```

### Limitations
As of writing this doc, the following limitations apply in LUIS Service
 * Max of 40 intents (`tef.intent.info` + `tef.intent.go` = 2)
 * Max of 50 chars for the intent name (`tef.intent.info` = 15)
 * Max of 10 phraselists (`askforinfo` + `tef.places` = 2)
 * Max of 10 entities ([something:`tef.places`]) _You can provide as much examples as you want for the entities_
 * Max of 10 children entities per parent ([something:`tef.date::start`])

## Usage examples

```sh
npm install -g @telefonica/language-model-converter
language-model-converter --help

  Usage: language-model-converter [options] <files>

  Convert language files defined to LUIS format

  Options:

    -h, --help               output usage information
    -c, --culture <culture>  Culture code this files belongs to (ex. "en-us")
    -n, --ner                Generate a model compatible with NER

  Examples:

    Convert all files in 'models' and its subfolders, starting with 'en',
    setting the locale to en-us
      $ language-model-converter ./models/**/en*.yaml -c en-us
```

Notice that you can use [luis-cli](https://github.com/Telefonica/luis-cli) to import or update the generated LUIS models.

## USE IT PROGRAMMATICALLY
You can also use this module from code:

```typescript
import { LanguageModelParser, culture } from '@telefonica/language-model-converter';

let parser = new LanguageModelParser();
let files = 'model.yaml';
try {
    let luisModel = parser.parse(files, 'en-us' as culture);
    // Do something with the LUIS model
} catch (err) {
    // Manage errors
}
```

## LICENSE

Copyright 2016 [Telefónica I+D](http://www.tid.es)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

repository: digideskio/language-model-converter

repo_name: digideskio/language-model-converter


text:
---
layout: post
title: "DevOps Tips for Impatient Developers - Ep 31"
summary: "In this special episode of The Toolbox, I talk to Michael Jenkins about something every full stack developer should master...DevOps, plus the importance of volunteering, the magic of the cloud and wether GitHub Actions can deliver a professional CI/CD pipeline. The Pace of the web is relentless...and that's why you need, The Toolbox."
hideDesc: true
video: -Azr_5hNruQ
hero: /images/toolbox/episode31.jpg
thumb: /images/toolbox/episode31_tn.jpg
category: toolbox
type: post
---

Hello everyone this is Ray Villalobos and I stream about front-end and full stack tools Wednesdays at 1pm Eastern • 10am Pacific. Follow me and subscribe on LinkedIn and YouTube for more content. If you want to watch any past episodes, make sure you take a look at my blog raybo.org.

You can find an article for Today's episode and all the links for the show.

## Turn on the Bell Icon
Also, make sure you check out my [my profile](https://www.linkedin.com/in/planetoftheweb/) and click on the bell icon. You can't see it on your own profile, but if you follow me, it's where the bell icon is. I'll go to [michael's profile](https://www.linkedin.com/in/michaelpjenkins/) to show you.
[]()
## Industry News

Lets quickly review some of the latest industry news:

### Git Merge 2022

[Git Merge 2022](https://github.blog/2022-08-23-the-full-lineup-for-git-merge-2022-revealed/) If you can't wait for the big GitHub Universe conference in November, you might want to check out this smaller conference in Chicago September 14-15. The workshops look really good with some beginner as well as a monorepo spring cleaning talk. Almost a third of the speakers work at GitHub.

### GitHub Pages, now with actions
[GitHub Pages](https://github.blog/2022-08-10-github-pages-now-uses-actions-by-default/) A small, but important change with GitHub pages is that they now use GitHub Actions by default. So this is now under your [settings under pages](https://github.com/planetoftheweb/slides_jsfunctions/settings/pages)

You now have the classic option that let you use either the docs folder from a specific branch, but now when you choose GitHub actions, it will let you use pre-built actions for Jekyll or server a static HTML page. The interesting bit is that you can create your workflow. So far, I've been using this awesome [action from James Ives](https://github.com/JamesIves/github-pages-deploy-action) that publishes your build process to a separate branch and then lets you deploy that branch to GitHub Pages.

If you've ever watched any of my courses, you know that I use my own variant of Reveal.js called RayVealjs to serve [markdown slides](https://raybo.org/slides_jsfunctions). I've been really working hard on an update that uses this process to make the whole thing easier to build, so look for a big update soon based on this actions based deploy method.

They also provide a set of workflows for [popular build tools](https://github.com/actions/starter-workflows/tree/main/pages), although I don't see one for vite yet.

## Vite

When Vite first came out, I was already looking for a better tooling solution for building sites. I went through a process of analysing all the existing options and noticed it was the new thing. As soon as I tried it, I went right to it, so it's great that it's got a new version.

If you haven't used it before, what I love about it is how much you get out of the box and how intuitive it is. It has all the modern features like Hot Module Reloading, which makes rebuids are super fast, even when you reconfigure something while in development. Support for Sass, JSX, TypeScript.

It's made by the folks who gave us Vue.js, which I thought always had the best CLI experience. I recently updated my slides app to version 3 and I didn't have to change anything. If you take a peek at [the changelog](https://vitejs.dev/) for version 3, you'll notice some minor things like port changes, dropping support for older versions of node.

I really love their [meta.glob](https://vitejs.dev/blog/announcing-vite3.html) improvements. This allows you to import whole folders of content and it's now way more flexible allowing you to make an array of imports at once. If you want to read about their new features, check out their [blog post](https://vitejs.dev/blog/announcing-vite3.html).

### Unplugin Icons

Lately, I've been using the [Bootstrap Icon library](https://icons.getbootstrap.com/) for most of my icon needs, but even with more than 1600 icons, often I can't find what I need, so the concept of this library is to give you access to more than 100 different icon libraries and easily call in a single icon into a module. It works with regular JS, Vite and all the frameworks the cool kids are using. You can even load up your own custom icons. That seems like a great idea.

## Patterns Book

Finally, Addy Osmani has had this book on [JavaScript patterns](https://www.patterns.dev/) for quite a while and now he's updated it with Lydia Hallie with tons of examples, code sandboxes and animations. If you want to learn some beginner to advanced JavaScript patterns you should totally check this out.

## Toolbox Talks

So, I've been talking to a lot industry professionals recently on something I'm calling [Toolbox Talks](https://www.youtube.com/playlist?list=PL1ezw_kTxXOm-x2kWZBRI5MMMxNDGHM4v) so far, I've interviewed Carlos Solis, Ronnie Sheer and Christina Truong.

This week, I'm continuing that talking to Michael Jenkins, a super talented technologist who started out with as a serious electronics engineer, before he discovered the power of DevOps.

Let's Listen In

## Q&A

## Goodbye
I have to go right into course production next, so I might be gone for a couple of weeks, then I other interviews in the works. Let me know what you want me to cover in the comments

## Links
- [Git Merge](https://github.blog/2022-08-23-the-full-lineup-for-git-merge-2022-revealed/)
- [GitHub Pages](https://github.com/planetoftheweb/slides_jsfunctions/settings/pages)
- [Pages Deploy Action](https://github.com/JamesIves/github-pages-deploy-action)
- [Markdown Slides Project](https://raybo.org/slides_jsfunctions)
- [Starter GitHub Action Workflows](https://github.com/actions/starter-workflows)
- [Vite 3](https://vitejs.dev/)
- [Vite Improvements](https://vitejs.dev/blog/announcing-vite3.html)
- [Bootstrap Icons](https://icons.getbootstrap.com/)
- [JavaScript Patterns](https://www.patterns.dev/)
- [Toolbox Talks](https://www.youtube.com/playlist?list=PL1ezw_kTxXOm-x2kWZBRI5MMMxNDGHM4v)
- [DevOps Tips](https://go.raybo.org/9s02)
- [Advanced Actions](https://go.raybo.org/9s1-)
- [Nailing Your DevOps Interview](https://go.raybo.org/9s2V)
- [Michael's Profile](https://www.linkedin.com/in/michaelpjenkins/)
- [Michael's Courses on LinkedIn](https://go.raybo.org/9s2V)
- [Michael on Twitter](https://twitter.com/managedkaos)
- [Ray's Blog](https://raybo.org)
- [Ray on LinkedIn](https://www.linkedin.com/in/planetoftheweb)

gha_language: Nunjucks


text:
# flora

> __flora-tmpl__ on npm.

[![Flora Finch, silent film actress](https://user-images.githubusercontent.com/361671/31864759-7ce1b858-b731-11e7-9984-0b60ba9ff9bd.jpg)](https://en.wikipedia.org/wiki/Flora_Finch)

Streaming templates.

![Streaming HTML](https://user-images.githubusercontent.com/361671/32578154-2abd05a6-c4aa-11e7-95bd-1dc39729c8fc.gif)

# Why

HTML is a format that can be streamed. Meaning the browser can start parsing and showing parts of a web page before the full thing has been downloaded. Your application probably has things it needs to do that take some time; like make database requests.

Parts of your page depend on this data, but much of it does not. Flora allows you to write templates that get to the client as quickly as possible, because only the parts that need to wait, do wait.

## Install

```shell
yarn add flora-tmpl
```

## Usage

```js
const { html, map } = require('flora-tmpl');
const streamArray = require('stream-array');

function template({items}) {
  return html`
    <h1>Todos</h1>
    <ul>
      ${map(items, item => (
        html`<li>Item ${item}</li>`
      ))}
    </ul>
  `;
}

template({
  items: streamArray([1, 2, 3])
})
.pipe(...)
```

## License

BSD 2 Clause

repository: matthewp/flora

gha_language: JavaScript

repo_name: matthewp/flora


text:
# GAUSS-01321 -- GAUSS-01330

GAUSS-01321: "nextval: reached minimum value of sequence '%s' \(%s\)"

SQLSTATE: 55000

Description: The minimum sequence value is reached.

Solution: Internal system error. Contact technical support.

GAUSS-01323: "lastval is not yet defined in this session"

SQLSTATE: 55000

Description: The  **LASTVAL**  of the sequence is not defined in this session.

Solution: Ensure that the  **LASTVAL**  of the sequence is defined in this session.

GAUSS-01324: "setval: value %s is out of bounds for sequence '%s' \(%s..%s\)"

SQLSTATE: 22003

Description: The configured sequence value is out of the valid range.

Solution: Ensure that the configured sequence value is within the range.

GAUSS-01325: "GTM error, could not obtain sequence value"

SQLSTATE: 08006

Description: A GTM error occurs, resulting in a failure in obtaining the sequence value.

Solution: Run  **gs\_om -t status --detail**  to check GTM status. If the GTM is abnormal, troubleshoot it as described in the  _Troubleshooting Guide_  and create a sequence again.

GAUSS-01326: "bad magic number in sequence '%s': %08X"

SQLSTATE: XX000

Description: Internal system error. The magic number in the opened sequence table is different from expected.

Solution: The sequence table may be abnormal. Contact technical support.

GAUSS-01327: "INCREMENT must not be zero"

SQLSTATE: 22023

Description: Ensure that the increment in the sequence is not 0.

Solution: The increment in the sequence cannot be 0.

GAUSS-01328: "MINVALUE \(%s\) must be less than MAXVALUE \(%s\)"

SQLSTATE: 22023

Description: The minimum sequence value must be less than the maximum value.

Solution: Ensure that the minimum sequence value is less than the maximum value.

GAUSS-01329: "START value \(%s\) cannot be less than MINVALUE \(%s\)"

SQLSTATE: 22023

Description: The minimum sequence value must be less than the maximum value.

Solution: Ensure that the initial sequence value is greater than or equal to the minimum value.

GAUSS-01330: "START value \(%s\) cannot be greater than MAXVALUE \(%s\)"

SQLSTATE: 22023

Description: The initial sequence value cannot be greater than the maximum value.

Solution: Ensure that the initial sequence value is less than the maximum value.


text:
---
layout: post
title: "Merlise Clyde Receives Zellner Medal"
date: 2016-06-07 08:43:59
author: ISBA
categories: News
tags: news
cover: "/assets/Zellner-Medal.jpg"
---

At the International Society for
Bayesian Analysis 2016 World Meeting in Sardinia, Italy, Merlise Clyde
was presented with the Zellner Medal for her outstanding
contributions, sustained impact and legacy in ISBA leadership; and in
recognition of her career impact in development of Bayesian analysis
as a research, educational and professional leader.

The Zellner Medal honors Arnold Zellner, one of the founders of ISBA
and ISBA’s first president. The purpose of the Zellner Medal is to
recognize ISBA members who have rendered exceptional and distinguished
service to ISBA over an extended period of time, and whose
contributions have had an impact on the society beyond the time of his
or her incumbency.

[ISBA Bulletin June 2016](https://bayesian.org/sites/default/files/fm/bulletins/1606.pdf)

repository: merliseclyde/homepage

extension: markdown

repo_name: merliseclyde/homepage


text:
# The Determined Guide to Developing PyTorchTrial

"Most of PyTorchTrial is simple.  But the Horovod / AMP / Gradient Aggregation
combo is not."

## Basics of PyTorch

### The forward pass

Calculate an error in an autodifferentiable way.  Each step in the calculation
leaves some traceable path of autodiff magic on the tensors which you pass
through.

### The backward pass

Once you have arrived at the loss you want to minimize, follow the magic
traceable autodiff path backward to calculate the gradient.  The gradients are
left in-place on the tensors to which they apply.

### `optimizer.step()`

Gather up all of the gradients for the tensors this optimizer is responsible for
tuning, and apply the `gradient * learning_rate` to each weight.  Now you have
new weights, congratulations!

## Horovod optimizer

The horovod optimizer calculates gradient updates on each worker, then
aggregates the updates across each worker before updating the weights in the
model on each worker.

### `loss.backward()`

Horovod registers backward hooks on all of the `hvd_optimizer`'s parameter
tensors; each backward pass starts an asynchronous allreduce of the gradient
updates for parameters from that loss tensor.  The use of backward hooks makes
this API-transparent to users.

### `hvd_optimizer.synchronize()`

Gather the results of the asynchronous allreduce of gradient updates between
workers (don't apply any gradient updates).  This is useful if you need to
process the gradients before applying them to the model weights, such as for
gradient clipping or gradient scaling.

### `hvd_optimizer.step()`

First call .synchronize(), then apply the allreduced gradient updates by
calling .step() on the wrapped optimizer.  This is the most vanilla way to use
horovod.

### `with hvd_optimizer.skip_synchronize():`

Any call to `hvd_optimizer.step()` within this context manager will skip the
.synchronize() step, which is useful if you already called
`hvd_optimizer.synchronize()`.

### `hvd_optimizer.backward_passes_per_step`

Modifies the backward hooks to only start the asynchronous allreduce every
`backward_passes_per_step` steps.  This value is useful for either gradient
aggregation (multiple batches per optimizer.step()) or if you plan on calling
loss.backward() multiple times.

Note that in Determined, the option named `backward_passes_per_step` is only
for calling loss.backward() multiple times, and we multiply that value by the
gradient aggregation frequency to get the `backward_passes_per_step` that we
actually pass to Horovod.

### optimizer.compression=hvd.Compression.fp16

This is not AMP, and it does not behave like the GradScaler.  It just blindly
casts gradient update tensors to fp16 for network communication and blindly
casts them back to fp32 afterwards.

## Gradient Aggregation:

Gradient aggregation by a factor of N is just like multiplying the batch size
by N, except it saves on GPU memory because you process two batches and average
their gradients before you apply the gradients.  This makes sense in
distributed training because of the high communication cost of the allreduce.
(There are some cases where it's not "just like multiplying batch size by N",
such as with batch norm).

The only operation required for gradient aggregation are:

* do N forward/backward passes before doing anything with the gradients that
  result from those backward passes.  Those in-place gradients will add
  together naturally.

* Divide the gradients by N to match the behavior of an N-times-larger batch
  size.

* Call optimizer.step() after every N batches to act on the aggregated
  gradients.

## PyTorch-Native AMP:

"AMP" stands for "automatic mixed precision", where certain calculations happen
in half-precision math (fp16).  This is normally only meaningful with GPUs
enabled, because Nvidia GPUs have special vector instructions for making fp16
math go really freaking fast.

### `with autocast():`

Choose certain parts of a model to be executed with fp16 math, based on some
rules that don't concern us here.  But with autocast(), you'll need to have a
GradScaler for stable training.

### The `GradScaler`

Multiply a loss by some factor before the backward pass, so that fp16 gradient
calculations don't overflow or underflow.  This scale factor is automatically
tuned in a pretty dumb control loop to keep it in a useful region.

### scaler.scale(loss):

Multiply the loss by the current scale factor.

### scaler.step(optimizer):

Check if the gradients which resulted caused an overflow/underflow.  If not,
step the optimizer.

### scaler.update():

Call the dumb control loop: if there was an overflow, decrease the scale
factor.  If there was an underflow, increase it.

Note that the `GradScaler` is designed to be one-per-training loop.  If there
are multiple optimizers involved, there should only be one `scaler.update()`
call after all `scaler.step(opt)` calls are made for a given batch.

## Nvidia apex AMP

### `model, optimizer = amp.initialize(model, optimizer)`

This is kind of like calling `with autocast()` for the forward pass or
something.  I'm guessing the reason that the optimizer is included is so that
the calls to optimizer.step() with underflown/overflown gradients can be safely
skipped, and at some point they must also trigger the scale factor control
loop.

### `with amp.scale_loss(loss, optimizer):`

Example:

```python
with amp.scale_loss(loss, optimizer) as scaled_loss:
    scaled_loss.backward()
```

This context manager is going to scale the loss by the current scale factor,
then unscale after the context manager exits.  Gradients are only accumulated
into tensors that this optimizer is responsible for.

Normally, apex.amp is fully capable of both gradient aggregation and dtrain.
That might look like this:

```python
# N-1 passes: don't unscale yet
with amp.scale_loss(loss, optimizer, defer_unscale=True) as scaled_loss:
    scaled_loss.backward()

# Nth pass: unscale now
with amp.scale_loss(loss, optimizer, defer_unscale=False) as scaled_loss:
    scaled_loss.backward()
    # synchronize before unscaling
    optimizer.synchronize()
```

However, our PyTorchTrial API doesn't allow that, because when
`context.backward(loss)` is called, we don't actually know what optimizer the
user intends to associate with that loss.

We definitely want to support apex.amp with dtrain, so we actually just "guess"
the optimizer by synchronizing all of the optimizers.  To ensure this "guess"
is correct, we only allow one optimizer with apex.amp.

This decision was made since long-term we expect the PyTorch-native API to
dominate and it is a much more flexible API which does not have the same API
limitations (needing to know the optimizer when calling `scale_loss`).

## The Laws of PyTorchTrial

* Horovod optimizer:
  * call .synchronize() zero or one times per optimizer.step().  If you do call
    it, wrap the .step() in a `with optimizer.skip_synchronize()` call.
  * always synchronize before gradient clipping; otherwise each worker clips
    differently
  * always synchronize before scaler.step(optimizer); otherwise each worker
    steps differently
  * you could scaler.scale(loss) before or after optimizer.synchronize(), that
    doesn't matter

* Gradient aggregation (by a factor of N):
  * do a forward and backward pass on each batch
  * average the summed gradients by dividing them by N (or equivalently, divide
    the loss by N before each backward pass)
  * set `hvd_optimizer.backward_passes_per_step` to N (aggregation frequency)
  * only synchronize/step optimizer every N batches
  * always call `scaler.scale(loss)` with the same scale factor for each batch in
    a grouping of N batches (only call `scaler.update()` every N batches); this
    ensures that the gradient aggregation is valid.

* PyTorch-native AMP:
  * (repeated from above) always call `scaler.step(optimizer)` *after*
    `optimizer.synchronize()`
  * (repeated from above) only call `scaler.update()` after each grouping of N
    batches.

* Nvidia apex AMP:
  * with horovod, you must call optimizer.synchronize() *before* the
    `amp.scale_loss()` context manager exits, because the underflow/overflow
    checks happen in that context manager's exit; otherwise each worker would
    step differently.
  * since the `context.backward(loss)` API does not specify an optimizer, and
    because `amp.scale_loss()` requires us to take actions on the correct
    optimizer, we do not allow multiple optimizers; we have to know that the
    our one optimizer is the correct optimizer to pass to scale_loss().

* PyTorch Distributed:
  * PyTorch Distributed wraps models in a `DistributedDataParallel` wrapper,
  which must be done after initializing APEX AMP.
  * PyTorch DDP synchronizes losses during the backwards pass
  * Since gradients are automatically synchronized during each backwards pass,
    each N-1 step must be wrapped in a `no_sync` context manager to avoid
    inefficiencies of syncing gradients at every step during gradient
    aggregation
  * DDP broadcasts parameters on model instantiation with
    `DistributedDataParallel()`, during which the `state_dict` from rank 0 is
    broadcast to all other ranks in the group. This is done automatically,
    unlike horovod's explicit use of `broadcast_parameters`

repository: determined-ai/determined

gha_language: Go

repo_name: determined-ai/determined


text:
![image](https://user-images.githubusercontent.com/64470404/134016170-6270b15d-6029-4b86-9f64-8c6145591e18.png)

# _______________________TYPES OF VIRTUALISATION_______________________

There're 5 types of virtualisation, namely:
1. Server virtualisation
2. Application Virtualisation
3. Network virtualistion
4. Processor and memory virtualisation, and
5. Data and storage virtualisation.

Here's the description about ``Application Virtualisation``

### 2. APPLICATION VIRTUALISATION:

- Application virtualisation encapsulates applications on underlining of physical computer system.

- It improves managebility and portability of an application.

- This is a virtualisation layer which is inserted between an application and os.

- It allows the running of legacy apps, enables cross-platform operations, prevents conflicts with other virtualized apps.

- It runs software from a remote server and is able to remove software installation procedure and creates virtual software.

- It reduces application conflicts and centralises application updates as a whole, in addition, it also speed ups application deployement as compared to other.

- It needs no reboots and uninstallations.

- It runs on both 32 and 64 bit windows plaform.

- In addition this is also being hosted on cloud, like aws cloud, which means, we can access it from anywhere and from any workig device.

### USE CASES AND ADVANTAGES:

- ``application virtualisation makes our work wasy by linking a file in network in the workstation. ``

 - ``It gives us application mobility and Secures remote access capability  ``

 - ``Makes migration and handling of software and files more easier and simplified magnification ``

 - ``virtualisation of any software reduces cost and space of the real software and thus benefits us in lot of way  ``

 - ``Simple installation and easy deployement also it makes portable applications which is also easier to cleanup  ``

 - ``Reduced conflicts between two or more application, in addition it is easy ti rollback, and update``

 - `` Independent of operating system``

 - ``It gives security to the application and software``

gha_language: Jupyter Notebook


text:
# MJML
MJML preview, lint, compile for Visual Studio Code.

[![GitHub license][license-img]][license-url]

## Features

* Live preview for MJML files. Preview updates as you type.
* Inline errors (squiggle underlines). Linter based on [atom-linter-mjml](https://github.com/mjmlio/atom-linter-mjml).
* Generate HTML file from MJML.

## It looks like this

![MJML Preview](https://raw.githubusercontent.com/attilabuti/vscode-mjml/master/images/mjml-preview.gif)

![MJML Lint](https://raw.githubusercontent.com/attilabuti/vscode-mjml/master/images/mjml-lint.gif)

## Installation

Press `F1`, type `ext install vscode-mjml`.

## Usage

Start command palette (with `Ctrl+Shift+P` or `F1`) and start typing `MJML`.

## Available commands

The following command is available:
* **MJML: Open Preview** Opens a preview in a column alongside the current document.
* **MJML: Generate HTML** Generate HTML file from MJML.

## Settings

| Name | Default | Description |
| --- | --- | --- |
| `mjml.lintEnable` | `true` | Enable/disable MJML linter (requires restart). |

## Change Log

### 0.0.1
 - This is the initial release of this extension.

## Issues

Submit the [issues](https://github.com/attilabuti/vscode-mjml/issues) if you find any bug or have any suggestion.

## Contribution

Fork the [repo](https://github.com/attilabuti/vscode-mjml) and submit pull requests.

## License

This extension is licensed under the [MIT License][license-url].

[license-img]: https://img.shields.io/github/license/mashape/apistatus.svg?style=flat-square
[license-url]: https://raw.githubusercontent.com/attilabuti/vscode-mjml/master/LICENSE

repository: matijagaspar/vscode-mjml

repo_name: matijagaspar/vscode-mjml


text:
# UnityShaderBall
![](https://github.com/Pseudopode/UnityShaderBall/blob/master/Screenshots/screenshot0.jpg)
This repository contain a **3D model shaderball (CC0 licensed)** and a demo **Unity 2017.X project (MIT licensed)**.

The 3D model is an attempt to recreate the one that can be seen is scientific papers (like this one - Figure 3, page 5: http://old.cescg.org/CESCG-2010/papers/ElekOskar.pdf)

The ball was modeled in Blender. Starting from a cube, subdivision modifiers are iteratively added.
A ring selection is applied on all axis to model the crease. After the 6 creases are set, the model is further subdivided to be smoothed.

The UV unwrap should be clean, and an AO map (baked in Blender) is also provided.

The ball is provided in various formats (3D, OBJ, DAE, FBX), and the original Blender file is in the repository.

The associated project is done in Unity 2017.3.1f1, but should be compatible with all the 2017.X/2018 branch (and should be also retro-compatible with the 5.X branch).

The camera and the angles are roughly set to match the paper.

All ameliorations to both of them are welcomed.

repository: Pseudopode/UnityShaderBall

repo_name: Pseudopode/UnityShaderBall


text:
---
layout: book
title: "Our Newsletter"
description: "Trailblazer is a high-level architecture for Ruby. The newsletter broadcasts hottest changes about its gems: Cells, Reform, Representable, Roar, Disposable, and more."
---

            <form action="//trailblazerb.us8.list-manage.com/subscribe/post?u=bbe5021ab6fbdc94a16f0d036&id=a69f6e4652" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Subscribe to our newsletter!

                  <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Your email">

<input type="text" name="b_bbe5021ab6fbdc94a16f0d036_a69f6e4652" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

            </form>

TRB Newsletter

Everything you need to know!

            The TRB Newsletter is a monthly email full of release notes, comments, recipes and cool tricks about all gems Trailblazer: Cells, Reform, Disposable, Representable and Roar, Trailblazer, and more.

            Please subscribe to the newsletter and never miss any new feature!

Archive

March 2016 Talks about coercion in Reform using Dry-Types, the nilify feature, compositional aspects in operations and presentations in Europe in Feburary.

January 2016 January 2016 newsletter talks about Formular (new form builder for Ruby), dry-validation in Reform, Sinatra/TRB, cool but unknown features in Reform and upcoming talks in Europe and Australia.

branch_name: refs/heads/beast


text:
# knife-azure Change Log

## Last release: 1.5.0 (2015/05/20)
* [knife-azure #213](https://github.com/chef/knife-azure/pull/213) Typo in fetch_thumbprint method
* [knife-azure #215](https://github.com/chef/knife-azure/pull/215) Added --delete-chef-config option in knife azure server create
* [knife-azure #204](https://github.com/chef/knife-azure/pull/204) Properly configure WinRM for bootstrapping; Fixes [#203](https://github.com/chef/knife-azure/pull/203)
* [knife-azure #197](https://github.com/chef/knife-azure/pull/197) Add custom json attributes to chef extension
* [knife-azure #211](https://github.com/chef/knife-azure/pull/211) Allow user to specify chef extension version by using knife_rb
* [knife-azure #202](https://github.com/chef/knife-azure/pull/202) knife-windows 1.0.0+ compat fixes
* [knife-azure #198](https://github.com/chef/knife-azure/pull/198) Adding winrm_ssl_verify_mode to bootstrap config
* [knife-azure #196](https://github.com/chef/knife-azure/pull/196) Update Rubies; remove Chef-unsupported versions from matrix
* [knife-azure #195](https://github.com/chef/knife-azure/pull/195) Showing thumbprint with Server show command
* [knife-azure #188](https://github.com/chef/knife-azure/pull/188) Winrm port should not be configured if --bootstrap-protocol=cloud-api

## Release: 1.4.0 (2015/02/09)
* [knife-azure #189](https://github.com/chef/knife-azure/issues/189) Server Create failing for some custom sysprepped images
* [knife-azure #184](https://github.com/chef/knife-azure/pull/184) Disable certificate generation code for ssl transport until supported by knife-windows
* [knife-azure #102](https://github.com/chef/knife-azure/pull/102) User specified ssh/winrm port 22/5985 instead of random port with --azure-connect-to-existing-dns option for server creation
* [knife-azure #179](https://github.com/chef/knife-azure/pull/179) Enable creation of new vnets
* [knife-azure #169](https://github.com/chef/knife-azure/pull/169) Enable automatic update of the Chef extension the Azure VM Chef Extension --auto-update-client
* [knife-azure #167](https://github.com/chef/knife-azure/pull/167) Include custom VM images in knife azure image list
* [knife-azure #171](https://github.com/chef/knife-azure/pull/171) EXPERIMENTAL: Support for unreleased knife-windows 1.0.0 configuration option winrm\_authentication\_protocol
* [knife-azure #163](https://github.com/chef/knife-azure/pull/163) Remove the az prefix from DNS name when VM name is specified and DNS name is not specified
* [knife-azure #160](https://github.com/chef/knife-azure/pull/160) Support for adding winrm SSL certificate, for winrm ssl communication
* [knife-azure #157](https://github.com/chef/knife-azure/pull/157) Add integration tests
* [knife-azure #162](https://github.com/chef/knife-azure/pull/162) Documentation fix to remove extraneous dash and use real example of VM image
* [knife-azure #153](https://github.com/chef/knife-azure/pull/153) Resource extension support through knife-azure plugin -- cloud-api bootstrap without network transport
* [knife-azure 146](https://github.com/chef/knife-azure/pull/146) Virtual machine state 'provisioning' not reached after 5 minutes

## Release: 1.3.0 (2014/07/31)
* Update specs to rspec 3
* [KNIFE-472] - clean up knife-azure gemspec dependencies
* Fixed wrong command in README
* server create should not delete storage account in cleanup - unless created storage account
* knife-azure server create is missing -j switch for json at first chef-client run.

## Previous  Release: 1.2.2 (2014/02/07)

**See source control commit history for earlier changes.**

repository: rreyes/knife-azure

repo_name: rreyes/knife-azure


text:
# Go - Atlas Engine
## Introduction
This project provides an interface between the [Atlas Engine](https://github.com/tippesi/Atlas-Engine) and Go.
## Set up
1. Download [Go](https://golang.org/).
2. Download [Python](https://www.python.org/) for post-build script support.
3. Download engine dependencies (folder *cwrapper/engine/dependencies*)
4. Download [MSYS2](http://www.msys2.org/). (Windows only)
5. Update MSYS2 with *pacman -Syu*. (Windows only)
6. Download MingGW64 with *pacman -S mingw-w64-x86_64-toolchain*. (Windows only)
7. Add *C:/msys64/mingw64/bin/* to PATH. (Windows only)
8. Compile C++ code using Clion and gcc.
9. Have fun

repository: tippesi/Go-Atlas-Engine

detected_licenses: MIT Zlib BSD-3-Clause

gha_language: C

gha_license_id: NOASSERTION

repo_name: tippesi/Go-Atlas-Engine


text:
---
layout: default
---

# 1996-07-23 - DAM_lin

## Header Data

From<EMAIL_ADDRESS>(John Young)

To<EMAIL_ADDRESS>Message Hash: 489093ee6c1dd270dd25e07024451c3ebd9fb71314edcbf6aba30eab82ad7a61

Message ID<EMAIL_ADDRESS>Reply To: _N/A_

UTC Datetime: 1996-07-23 19:06:11 UTC

Raw Date: Wed, 24 Jul 1996 03:06:11 +0800

## Raw message

```
{% raw  %}From<EMAIL_ADDRESS>(John Young)
Date: Wed, 24 Jul 1996 03:06:11 +0800
To<EMAIL_ADDRESS>Subject: DAM_lin
Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

   7-23-96, WaPo:

   "The Cryptography Wars." Op-Ed By Kenneth W. Dam and
   Herbert S. Lin

      In a June 10 editorial The Post disagreed with the NRC
      report, suggesting that law enforcement and national
      security interests require that current restrictions on
      cryptography be maintained. The Post asserted that it is
      "too soon" to accept that encryption can help law
      enforcement and national security.

      But arguing that it is premature to believe some uses of
      encryption do benefit law enforcement and national
      security simply denies reality. We emphatically reject
      The Post's implication that we "sacrificed" law
      enforcement and national security considerations in
      favor of economic interests. Indeed, only a fully open
      and inclusive public discussion can lead to the national
      consensus upon which any successful cryptography policy
      will depend.

   -----

   http://jya.com/damlin.txt  (6 kb)

   DAM_lin

{% endraw %}
```

## Thread

+ Return to [July 1996](/archive/1996/07)

+ Return to<EMAIL_ADDRESS>(John Young)](/authors/jya_at_pipeline_com_john_young_)"

+ 1996-07-23 (Wed, 24 Jul 1996 03:06:11 +0800) - DAM_lin -<EMAIL_ADDRESS>(John Young)_


text:
# 计算机网络实验 lab4

姓名：李沛尧

学号：1712901

## Q1

问题：

1. Select one UDP packet from your trace. From this packet, determine how many fields there are in the UDP header. (You shouldn’t look in the textbook! Answer these questions directly from what you observe in the packet trace.) Name these fields.
2. By consulting the displayed information in Wireshark’s packet content field for this packet, determine the length (in bytes) of each of the UDP header fields.
3. The value in the Length field is the length of what? (You can consult the text for this answer). Verify your claim with your captured UDP packet.
4. What is the maximum number of bytes that can be included in a UDP payload? (Hint: the answer to this question can be determined by your answer to 2. above)
5. What is the largest possible source port number? (Hint: see the hint in 4.)
6. What is the protocol number for UDP? Give your answer in both hexadecimal and decimal notation. To answer this question, you’ll need to look into the Protocol field of the IP datagram containing this UDP segment (see Figure 4.13 in the text, and the discussion of IP header fields).
7. Examine a pair of UDP packets in which your host sends the first UDP packet and the second UDP packet is a reply to this first UDP packet. (Hint: for a second packet to be sent in response to a first packet, the sender of the first packet should be the destination of the second packet). Describe the relationship between the port numbers in the two packets.

答案：

1. 4个，Sourse Port，Destination Port，Length，Checksum

    ![Q1-1](./images/Q1-1.png)

2. 16bits

    ![Q2](./images/Q2.png)

3. 数据包的长度

    如图所示，UDP包带上包头共有51*8bit的数据，而长度刚好是51

    ![Q3](./images/Q3.png)

4. 最大是65528*8bit的数据，理由如下

    由于Length头占16bit，2^16=65536，减去4个包头，还有65528

5. 65535，因为2^16-1=65535

6. 17（10进制），0x11（16进制）

    ![Q6](./images/Q6.png)

7. 发送时和接受时UDP端口号刚好相反

    ![Q7-1](./images/Q7-1.png)

    ![Q7-2](./images/Q7-2.png)

repository: Youggls/ComputerNetworkHomework

repo_name: Youggls/ComputerNetworkHomework


text:
[Minutest](README.md)

# com.oneeyedmen.minutest

Minutest was previously published as `com.oneeyedmen.minutest`. I have recently (2019-02-08) moved to its own domain `dev.minutest`, but in the process have lost the previous versions published on Bintray.

Because of limitations with Bintray I cannot completely rectify this situation. Instead I have published version 0.43.0 (the last under com.oneeyedmen) with the Maven coordinates `dev.minutest:minutest:0.43.0` but the old `com.oneeyedmen.minutest` package.

If you are using Minutest prior to version 0.45.0 please update your build to reference `testImplementation "dev.minutest:minutest:0.43.0"` and that should get you back building. Then update to reference `testImplementation "dev.minutest:minutest:+"` and `s/com.oneeyedmen.minutest/dev.minutest/minutest/g` in your Kotlin source.

I'm really sorry about the hassle - I screwed up. If you need help migrating, or want to how it happened and how to prevent it happening to you, please ask on the [#minutest channel on the Kotlin Slack](https://kotlinlang.slack.com/messages/CCYE00YM6).

repository: dmcg/minutest

gha_language: Kotlin

repo_name: dmcg/minutest


text:
This document was used to inform the current design and current documents. Look at those instead, OK?

# Protocol Binding (no associated types)
One of the language features in swift is protocols, which are more or less akin to C# interfaces.
At present we do a 1:1 mapping for each protocol. We implement a swift object that implements the protocol and vectors each of the methods through a vtable that has function pointers from C# that receive the call and marshal it into a C# object.

This works, but it has a limitation - it only works for one protocol at a time. To understand this limitation, I’m going to dive into the concrete implementation of protocols in swift.

Any type can implement a protocol and, unlike C#, Swift has the ability to adopt the protocol on any type via retroactive modeling. Because of this, the implementation for the protocol can’t be part of the object itself. Swift manages this will a structure called a Protocol Witness Table. A Protocol Witness Table is essentially a vtable that lives outside of the type. Any protocol witness table is described with two types, the implementing type and the protocol. For example, “protocol witness table for Swift.Int : Comparable”.  Witness tables can be compiled into the code statically, or in Swift 5 and later, they’re gotten through an accessor function that generates one as needed.

When representing a type that is a protocol type, swift uses a type of box called an existential container. An existential container consists of the following:

| Field                  | Offset (in pointers) |
| ---------------------- | -------------------- |
| Payload 0              | 0                    |
| Payload 1              | 1                    |
| Payload 2              | 2                    |
| Type Metadata          | 3                    |
| Protocol Witness Table | 4+                   |

The first 3 words are the data payload for the box. If the type is a value type and fits in the first 3 pointers, then it gets blitted into place. If it doesn’t fit then a heap-allocated blob gets allocated and the value type gets blotted into that space.

After the payload is a pointer to the type metadata for the type contained in the payload. The type metadata is used for information on how to manipulate the payload (how big is it? How do I move it from point a to point b and abide by ARC, etc).

Finally is a pointer to the protocol witness table. But this is a half-truth that I believed in my heart of hearts, but it turned out to be wrong, which is purpose of this document.

Based on my incorrect belief, I modeled the existential container as a block of 5 pointers always. This turns out not to be the case. There are two special cases and 1 general case that break this.

The first special case is the type `Swift.Any`, which is used in place of any type in swift. It is an existential container as above except that it has no protocol witness table. `Swift.Any` is the empty protocol and it does nothing. There is no protocol witness table, so it contains just 4 pointers. And make no mistake, Swift is fairly strict about treating it as a protocol.

The second special case is `Swift.AnyObject`, which is used in place of any class instance. Like `Swift.Any` it is also an empty protocol, but it is a special case because it isn’t represented by an existential container. This is because `Swift.AnyObject` is a class instance, so the type metadata is attached to the ISA pointer and we always know the ARC rules for it.

The general case in swift that breaks this is the protocol list type. I can declare a function like this:

    public func foo (a: Proto1 & Proto2 & Proto3) {
    }

and the type of a some type that implements all three of those protocols. In C#, this would be represented like this:

    public void Foo<PR> (PR a) where PR: IProto1, IProto2, IProto3 {
    }

The representation under the hood for this in Swift is an existential container with 3 protocol witness table slots, one for each protocol implemented.

Previously, to implement a protocol, SoM would write a class in swift that implements the protocol and defers each method into a vtable entry.

In C# there was a class that would map onto the swift class and receive all of it’s vtable calls, diverting them to the C# interface implementation. It works and works pretty well. Except for protocol list types that it can’t handle at all. The problem is that there is a 1:1 mapping of swift adapter onto swift protocol and it doesn’t work for more than one protocol at a time. This class also served double duty in that it was both a representation of a swift protocol as well as a proxy for types that don’t belong in the swift world, but still implement the equivalent C# interface.

To fix this, there will be a universal adapter which will live in swift glue, which will probably look something like this:

    public class EveryProtocol {
        public init(handle: OpaquePointer) { // don't know if the handle is needed.
            self.handle = handle
        }
        public var handle: OpaquePointer
    }

Then when given a protocol like this:

    public protocol Uppy {
       func addOne()
    }

We’ll write the following:

    internal struct Uppy_vtable {
        public var func0: @convention(c)((UnsafeRawPointer)->()?) = nil
    }
    internal vt: Uppy_vtable
    public func setUppy_vtable(ptr: UnsafeRawPointer) {
        let p:UnsafeMutablePointer<Uppy_vtable> = fromIntPtr(ptr)
        vt = p.pointee
    }
    public extension EveryProtocol : Uppy {
        public func addOne() {
            vt.func0!(toIntPtr(self))
        }
    }

    public func xam_FooDUppy(this: UnsafeMutablePointer<Uppy>) {
        this.pointee.Uppy()
    }

So now when we want to represent a C# type as an `Uppy` in swift, we just need to make an instance of `EveryProtocol` and use that as a proxy. And since `EveryProtocol` can act as a proxy for every protocol, we can now use it in protocol list types.

The only thing about this that will break the overall model is that `type(of:)` will violate the principal of least astonishment in that when used from within swift from a type exposed in C#, it will always return `XamGlue.EveryProtocol` instead of something representing the actual type. There’s not much we can do about this.

repository: xamarin/binding-tools-for-swift

gha_language: C#

repo_name: xamarin/binding-tools-for-swift


text:
# puppet-ip_in_range

[![Actions Status](https://github.com/deanwilson/puppet-ip_in_range/workflows/Ruby/badge.svg)](https://github.com/deanwilson/puppet-ip_in_range/actions)
[![Puppet Forge](https://img.shields.io/puppetforge/v/deanwilson/ip_in_range.svg)](https://forge.puppetlabs.com/deanwilson/ip_in_range)

A Puppet function to determine if an IPv4 address is within the IPv4 CIDR

`ip_in_range` returns true if the ipaddress is within the given CIDRs

    usage: ip_in_range(<IPv4 Address>, <IPv4 CIDR>)

or when you want to check against more than one CIDR and return
true if the IP address is contained in any of them.

    $ranges = ['<IP_ADDRESS>/24', '<IP_ADDRESS>/24']
    $valid_ip = ip_in_range('<IP_ADDRESS>', $ranges) # $valid_ip == true

There are a couple of commonly used patterns -

    $valid_ip = ip_in_range('<IP_ADDRESS>', '<IP_ADDRESS>/24') # $valid_ip == true

or using the check as part of a conditional -

    if ip_in_range($ipaddress, '<IP_ADDRESS>/24') == true {
      notify { 'Do subnet based resources here': }
    }

This module has a dependency on `puppetlabs-stdlib`.

## Installation

You can install this module from [PuppetForge](https://forge.puppet.com/):

    puppet module install deanwilson-ip_in_range

### License

Apache 2.0 - [Dean Wilson](https://www.unixdaemon.net)


text:
# Model Selection & Boosting

Welcome to Part 9 - Model Selection & Boosting!

After we built our Machine Learning models, some questions remained unanswered:

1. How to deal with the bias variance tradeoff when building a model and evaluating its performance ?

2. How to choose the optimal values for the hyperparameters (the parameters that are not learned) ?

3. How to find the most appropriate Machine Learning model for my business problem ?

In this part we will answer these questions thanks to Model Selection techniques including:

1. k-Fold Cross Validation

2. Grid Search

Eventually we see one of the most powerful Machine Learning model, that has become more and more popular: XGBoost.

url: https://raw.githubusercontent.com/Bhagya11/Machine-Learning-Codes-And-Templates/f36e92e9e103fa96549596e38be4c5fa29b2765d/Part 9 - Model Selection & Boosting/README.md


text:
Java custom application that creates an output file with a specific format from another input file also with a specific format.

========================
BUILD OUTPUT DESCRIPTION
========================

To run the project from the command line, go to the dist folder and
type the following:

java -jar "OpenLdapToBiostar.jar"

Input file name:ldap-UID.txt
Output file name: UsersToImportIntoBiostar2.csv

Sample input file

uid: root
gecos: Netbios Domain Administrator
uid: nobody
uid: joindomain
gecos: GenericJoinDomain
uid: tecnico
gecos: TecnicoClickControl
uid: onlyprint
gecos: Solo Impresion
uid: scanrepro
gecos: scanrepro
uid: al036000
gecos: fulanito y sotanito

repository: alfredodemiguel/Proyectos

repo_name: alfredodemiguel/Proyectos


text:
# FinalProject

Important steps for finish Final Project

As a user, 1. git clone

As a user, 2.CD into FAQ and run composer install

As a user, 3.laravel and database setup

As a user, 4.Built Branches respectively

As a user, 5.Created Profile, Question, and Answer files and directories
(migration, Tableseeder, Factory and Test unit)

As a user, 6.Reivse and updated web.php

As a user, 7.Created files in views directory
(profile, profileForm, Question, QuestionForm, Answer, AnswerForm)

As a user, 8.commit and push.

repository: LiSunNJIT/FinalProject

repo_name: LiSunNJIT/FinalProject


text:
# Cirlos SDK

## The official library for creating Cirlos addons.
### Create plugins using JavaScript and JSX or TypeScript and TSX
### Create themes and style plugins using CSS, SASS, or SCSS

# Getting started
### First download the package, and install its dependencies
    npm i

### Then try out the example plugin
    npm start --plugin=ExamplePlugin

### You should see an "output" folder has appeared; we need to set our SDK output path to this in the Cirlos app `config.json`
### Ensure Cirlos is closed, and navigate to `%AppData%/Cirlos` and open `config.json`
### Under `"sdk"`, you should see `"enabled"` and `"sdkOutputPath"`
### Set `"enabled"` to `true`, and `"sdkOutputPath"` to your "output" folder from before
### Now open Cirlos, and a toast should appear that says `ExamplePlugin started`
### You're all set to start coding! Feel free to read all of the examples in `src` to get a grasp of the basics

# Building your plugin
### In order to build your plugin, simply run `npm run build --plugin=YourPluginName`
### This will build your plugin to a `release` folder, and if all is set up correctly, Cirlos should open a prompt for publishing your addon

######This library and page is a work in progress, check back later for more

repository: Metalloriff/cirlos-sdk

repo_name: Metalloriff/cirlos-sdk