text:
module.exports = require('eden-class').extend(function() {
	/* Require
	-------------------------------*/
	/* Constants
	-------------------------------*/
	/* Public.Properties
	-------------------------------*/
	/* Protected Properties
	-------------------------------*/
	this._table 	= null;
	this._keys		= [];
	this._values	= {};
	this._returning	= [];

	/* Private Properties
	-------------------------------*/
	/* Magic
	-------------------------------*/
	this.___construct = function(table) {
		this.argument().test(1, 'string', 'undef');

		if(typeof table === 'string') {
			this.setTable(table);
		}
	};

	/* Public.Methods
	-------------------------------*/
	/**
	 * Returns the string version of the query
	 *
	 * @param  bool
	 * @return string
	 * @notes returns the query based on the registry
	 */
	this.getQuery = function() {
		var values = [], value;

		for(var i in this._values) {
			if(this._values.hasOwnProperty(i)) {
				if(Object.keys(this._values[i]).length !== this._keys.length) {
					continue;
				}

				value = [];

				for(var j = 0; j < this._keys.length; j++) {
					value.push(this._values[i][this._keys[j]]);
				}

				values.push('(' + value.join(', ') + ')');

			}
		}

		var returning = '';

		if(this._returning.length) {
			returning = ' RETURNING ' + this._returning.join(', ');
		}

		return 'INSERT INTO "{TABLE}" ({KEYS}) VALUES {VALUES}{RETURNING};'
			.replace('{TABLE}'		, this._table)
			.replace('{KEYS}'		, this._keys.join(', '))
			.replace('{VALUES}'		, values.join(', '))
			.replace('{RETURNING}'	, returning.trim());
	};

	/**
	 * Set the returning value is a common usecase
	 *
	 * @param string name
	 * @return this
	 */
	this.returning = function(columns) {
		//argument test
		this.argument().test(1, 'string', 'array');

		if(typeof columns === 'string') {
			columns = [columns];
		}

		this._returning = columns;
		return this;
	};

	/**
	 * Set clause that assigns a given field name to a given value.
	 * You can also use this to add multiple rows in one call
	 *
	 * @param string|object
	 * @param string|number|bool|null
	 * @param int
	 * @return this
	 * @notes loads a set into registry
	 */
	this.set = function(key, value, index) {
		//argument test
		this.argument()
			.test(1, 'string', 'object')							//Argument 1 must be a string
			.test(2, 'numeric', 'string', 'bool', 'null', 'undef')	//Argument 2 must be scalar or null
			.test(3, 'int', 'undef');

		index = index || 0;

		if(typeof key === 'object') {
			for(var i in key) {
				if(key.hasOwnProperty(i)) {
					this.set(i, key[i], value || 0);
				}
			}

			return this;
		}

		key = '"' + key + '"';

		if(this._keys.indexOf(key) === -1) {
			this._keys.push(key);
		}

		if(value === null) {
			value = 'NULL';
		} else if(typeof value === 'boolean') {
			value = value ? 1 : 0;
		} else if(typeof value === 'string'
		&& value !== '?'
		&& value.indexOf('$') !== 0) {
			value = "'" + value + "'";
		}

		if(typeof this._values[index] === 'undefined') {
			this._values[index] = {};
		}

		this._values[index][key] = value;

		return this;
	};

	/**
	 * Set the table name in which you want to delete from
	 *
	 * @param string name
	 * @return this
	 */
	this.setTable = function(table) {
		//argument test
		this.argument().test(1, 'string');

		this._table = table;
		return this;
	};

	/* Protected Methods
	-------------------------------*/
	/* Private Methods
	-------------------------------*/
}).register('eden/mysql/insert');


text:
package org.scalajs.testsuite.javalib.lang.ref

import org.junit.Test
import org.junit.Assert._

class ReferenceTest {

  @Test def should_have_all_the_normal_operations(): Unit = {
    val s = "string"
    val ref = new java.lang.ref.WeakReference(s)
    assertEquals(s, ref.get)
    assertEquals(false, ref.enqueue)
    assertEquals(false, ref.isEnqueued)
    ref.clear()
    assert(ref.get == null)
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.linecorp.armeria.common;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import org.junit.jupiter.api.Test;

import com.google.common.base.Stopwatch;

class HttpResponseTest {

    @Test
    void ofWithPlainContent() {
        // Using non-ascii to test UTF-8 conversion
        final HttpResponse res = HttpResponse.of("Armeriaはいろんな使い方がアルメリア");
        final AggregatedHttpResponse aggregatedRes = res.aggregate().join();
        assertThat(aggregatedRes.status()).isEqualTo(HttpStatus.OK);
        assertThat(aggregatedRes.contentUtf8())
                .isEqualTo("Armeriaはいろんな使い方がアルメリア");
    }

    @Test
    void ofWithPlainFormat() {
        // Using non-ascii to test UTF-8 conversion
        final HttpResponse res = HttpResponse.of(
                "%sはいろんな使い方が%s", "Armeria", "アルメリア");
        final AggregatedHttpResponse aggregatedRes = res.aggregate().join();
        assertThat(aggregatedRes.status()).isEqualTo(HttpStatus.OK);
        assertThat(aggregatedRes.contentUtf8())
                .isEqualTo("Armeriaはいろんな使い方がアルメリア");
    }

    @Test
    void ofWithContent() {
        // Using non-ascii to test UTF-8 conversion
        final HttpResponse res = HttpResponse.of(
                MediaType.PLAIN_TEXT_UTF_8, "Armeriaはいろんな使い方がアルメリア");
        final AggregatedHttpResponse aggregatedRes = res.aggregate().join();
        assertThat(aggregatedRes.status()).isEqualTo(HttpStatus.OK);
        assertThat(aggregatedRes.contentUtf8())
                .isEqualTo("Armeriaはいろんな使い方がアルメリア");
    }

    @Test
    void ofWithFormat() {
        // Using non-ascii to test UTF-8 conversion
        final HttpResponse res = HttpResponse.of(
                MediaType.PLAIN_TEXT_UTF_8,
                "%sはいろんな使い方が%s", "Armeria", "アルメリア");
        final AggregatedHttpResponse aggregatedRes = res.aggregate().join();
        assertThat(aggregatedRes.status()).isEqualTo(HttpStatus.OK);
        assertThat(aggregatedRes.contentUtf8())
                .isEqualTo("Armeriaはいろんな使い方がアルメリア");
    }

    @Test
    void shouldReleaseEmptyContent() {
        EmptyPooledHttpData data = new EmptyPooledHttpData();
        HttpResponse.of(HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8, data);
        assertThat(data.refCnt()).isZero();

        data = new EmptyPooledHttpData();
        HttpResponse.of(ResponseHeaders.of(200), data);
        assertThat(data.refCnt()).isZero();

        data = new EmptyPooledHttpData();
        HttpResponse.of(ResponseHeaders.of(200),
                        data,
                        HttpHeaders.of("some-trailer", "value"));
        assertThat(data.refCnt()).isZero();
    }

    @Test
    void statusOfResponseHeadersShouldNotBeInformational() {
        assertThatThrownBy(() -> HttpResponse.of(HttpStatus.CONTINUE, MediaType.PLAIN_TEXT_UTF_8,
                                                 HttpData.ofUtf8("bob")))
                .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("non-1xx");
    }

    @Test
    void ofRedirectTemporary() {
        final HttpResponse res = HttpResponse.ofRedirect("locationFor");
        final AggregatedHttpResponse aggregatedRes = res.aggregate().join();
        assertThat(aggregatedRes.status()).isEqualTo(HttpStatus.TEMPORARY_REDIRECT);
        assertThat(aggregatedRes.headers().get(HttpHeaderNames.LOCATION)).isEqualTo("locationFor");
    }

    @Test
    void ofRedirectTemporaryUsingFormat() {
        final HttpResponse res = HttpResponse.ofRedirect("location%s", "For");
        final AggregatedHttpResponse aggregatedRes = res.aggregate().join();
        assertThat(aggregatedRes.status()).isEqualTo(HttpStatus.TEMPORARY_REDIRECT);
        assertThat(aggregatedRes.headers().get(HttpHeaderNames.LOCATION)).isEqualTo("locationFor");
    }

    @Test
    void ofRedirectPermanently() {
        final HttpResponse res = HttpResponse.ofRedirect(HttpStatus.MOVED_PERMANENTLY, "locationFor");
        final AggregatedHttpResponse aggregatedRes = res.aggregate().join();
        assertThat(aggregatedRes.status()).isEqualTo(HttpStatus.MOVED_PERMANENTLY);
        assertThat(aggregatedRes.headers().get(HttpHeaderNames.LOCATION)).isEqualTo("locationFor");
    }

    @Test
    void ofRedirectPermanentlyUsingStringFormat() {
        final HttpResponse res = HttpResponse.ofRedirect(HttpStatus.MOVED_PERMANENTLY, "location%s", "For");
        final AggregatedHttpResponse aggregatedRes = res.aggregate().join();
        assertThat(aggregatedRes.status()).isEqualTo(HttpStatus.MOVED_PERMANENTLY);
        assertThat(aggregatedRes.headers().get(HttpHeaderNames.LOCATION)).isEqualTo("locationFor");
    }

    @Test
    void ofRedirectResponseCodeShouldBe300to307() {
        assertThatThrownBy(() -> HttpResponse.ofRedirect(HttpStatus.OK, "locationFor"))
            .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("expected: 300 .. 307");
    }

    @Test
    void ofRedirectParamsShouldNotBeNull() {
        //check redirect status
        assertThatThrownBy(() -> HttpResponse.ofRedirect(null, "locationFor"))
            .isInstanceOf(NullPointerException.class).hasMessageContaining("redirectStatus");

        //check location
        assertThatThrownBy(() -> HttpResponse.ofRedirect(null))
            .isInstanceOf(NullPointerException.class).hasMessageContaining("location");

        assertThatThrownBy(() -> HttpResponse.ofRedirect(HttpStatus.MOVED_PERMANENTLY, null))
            .isInstanceOf(NullPointerException.class).hasMessageContaining("location");

        //check args
        assertThatThrownBy(() -> HttpResponse.ofRedirect("locationFor", null))
            .isInstanceOf(NullPointerException.class).hasMessageContaining("args");

        assertThatThrownBy(() -> HttpResponse.ofRedirect(HttpStatus.MOVED_PERMANENTLY, "locationFor : %s",
            null))
            .isInstanceOf(NullPointerException.class).hasMessageContaining("args");
    }

    @Test
    void httpResponseUsingDeliveredExecutor() {
        final Supplier<HttpResponse> responseSupplier = () -> HttpResponse.of(HttpStatus.OK);
        final HttpResponse res = HttpResponse.from(responseSupplier,
                                                   Executors.newSingleThreadScheduledExecutor());

        assertThat(res.aggregate().join().status()).isEqualTo(HttpStatus.OK);
    }

    @Test
    void delayedHttpResponseWithAggregatedHttpResponseUsingCurrentEventLoopOrCommonPools() {
        final AggregatedHttpResponse aggregatedHttpResponse = AggregatedHttpResponse.of(HttpStatus.OK);
        final Stopwatch stopwatch = Stopwatch.createStarted();
        final HttpResponse res = HttpResponse.delayed(aggregatedHttpResponse, Duration.ofSeconds(1L));

        assertThat(res.aggregate().join().status()).isEqualTo(HttpStatus.OK);
        assertThat(stopwatch.elapsed(TimeUnit.SECONDS))
                .isGreaterThanOrEqualTo(1L);
    }

    @Test
    void delayedHttpResponseWithAggregatedHttpResponseUsingScheduledExecutorService() {
        final AggregatedHttpResponse aggregatedHttpResponse = AggregatedHttpResponse.of(HttpStatus.OK);
        final Stopwatch stopwatch = Stopwatch.createStarted();
        final HttpResponse res = HttpResponse.delayed(aggregatedHttpResponse,
                                                      Duration.ofSeconds(1L),
                                                      Executors.newSingleThreadScheduledExecutor());

        assertThat(res.aggregate().join().status()).isEqualTo(HttpStatus.OK);
        assertThat(stopwatch.elapsed(TimeUnit.SECONDS))
                .isGreaterThanOrEqualTo(1L);
    }

    @Test
    void delayedHttpResponseWithHttpResponseUsingCurrentEventLoopOrCommonPools() {
        final Stopwatch stopwatch = Stopwatch.createStarted();
        final HttpResponse res = HttpResponse.delayed(HttpResponse.of(HttpStatus.OK),
                                                      Duration.ofSeconds(1L));
        final AggregatedHttpResponse aggregatedHttpRes = res.aggregate().join();

        assertThat(aggregatedHttpRes.status()).isEqualTo(HttpStatus.OK);
        assertThat(stopwatch.elapsed(TimeUnit.SECONDS))
                .isGreaterThanOrEqualTo(1L);
    }

    @Test
    void delayedHttpResponseWithHttpResponseUsingScheduledExecutorService() {
        final Stopwatch stopwatch = Stopwatch.createStarted();
        final HttpResponse res = HttpResponse.delayed(HttpResponse.of(HttpStatus.OK),
                                                      Duration.ofSeconds(1L),
                                                      Executors.newSingleThreadScheduledExecutor());
        final AggregatedHttpResponse aggregatedHttpRes = res.aggregate().join();

        assertThat(aggregatedHttpRes.status()).isEqualTo(HttpStatus.OK);
        assertThat(stopwatch.elapsed(TimeUnit.SECONDS))
                .isGreaterThanOrEqualTo(1L);
    }

    @Test
    void delayedHttpResponseWithHttpResponseSupplierCurrentEventLoopOrCommonPools() {
        final Supplier<HttpResponse> responseSupplier = () -> HttpResponse.of(HttpStatus.OK);
        final Stopwatch stopwatch = Stopwatch.createStarted();
        final HttpResponse res = HttpResponse.delayed(responseSupplier,
                                                      Duration.ofSeconds(1L));
        final AggregatedHttpResponse aggregatedHttpRes = res.aggregate().join();

        assertThat(aggregatedHttpRes.status()).isEqualTo(HttpStatus.OK);
        assertThat(stopwatch.elapsed(TimeUnit.SECONDS))
                .isGreaterThanOrEqualTo(1L);
    }

    @Test
    void delayedHttpResponseWithHttpResponseSupplierUsingScheduledExecutorService() {
        final Supplier<HttpResponse> responseSupplier = () -> HttpResponse.of(HttpStatus.OK);
        final Stopwatch stopwatch = Stopwatch.createStarted();
        final HttpResponse res = HttpResponse.delayed(responseSupplier,
                                                      Duration.ofSeconds(1L),
                                                      Executors.newSingleThreadScheduledExecutor());
        final AggregatedHttpResponse aggregatedHttpRes = res.aggregate().join();

        assertThat(aggregatedHttpRes.status()).isEqualTo(HttpStatus.OK);
        assertThat(stopwatch.elapsed(TimeUnit.SECONDS))
                .isGreaterThanOrEqualTo(1L);
    }
}


text:
using System;
using NUnit.Framework;

namespace DevTyr.Gullap.Tests.With_Converter.For_Null
{
    [TestFixture]
    public class When_templater_is_null
    {
        [Test]
        public void Should_throw_argumentnullexception()
        {
            var options = new ConverterOptions {SitePath = "Test"};
            var converter = new Converter(options);
            Assert.Throws<ArgumentNullException>(() => converter.SetTemplater(null), "templater");
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <meta name="generator" content="pandoc" />
  <title>$name</title>

  <link rel="stylesheet" href="nitor.css" type="text/css" />

Presentation access

Run presentation

Follow presentation

Download slide images

Download small slide images

Download slide html

Presentation pdf


text:
package letter

// FreqMap stores the frequency of runes.
type FreqMap map[rune]int

// Frequency returns the FreqMap for one string.
func Frequency(s string) FreqMap {
	m := FreqMap{}
	for _, r := range s {
		m[r]++
	}
	return m
}

// ConcurrentFrequency returns FreqMap for one slice of strings.
func ConcurrentFrequency(i []string) FreqMap {
	c := make(chan FreqMap, 10)
	for _, s := range i {
		go func(c chan FreqMap, s string) {
			c <- Frequency(s)
		}(c, s)
	}
	f := <-c
	for x := 1; x < len(i); x++ {
		f.add(<-c)
	}
	return f
}

// add joins FreqMaps.
func (f FreqMap) add(a FreqMap) {
	for r, c := range a {
		f[r] += c
	}
}


text:
<!doctype html>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>react component</title>
<link href="../app.css" rel="stylesheet"/>


text:
package org.wso2.carbon.apimgt.usage.client.dto;

import java.util.ArrayList;
import java.util.List;

public class RegisteredAppUsersDTO {
    private String appName;
    private List<String> userArray = new ArrayList<String>();

    public String getAppName() {
        return appName;
    }

    public void setAppName(String appName) {
        this.appName = appName;
    }

    public List<String> getUserArray() {
        return userArray;
    }

    public void addToUserArray(String user) {
        this.userArray.add(user);
    }
}


text:
/****************************************************************************
 *
 * gxvalid is derived from both gxlayout module and otvalid module.
 * Development of gxlayout is supported by the Information-technology
 * Promotion Agency(IPA), Japan.
 *
 */

#include "gxvmorx.h"

  /**************************************************************************
   *
   * The macro FT_COMPONENT is used in trace mode.  It is an implicit
   * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log
   * messages during execution.
   */
#undef  FT_COMPONENT
#define FT_COMPONENT  gxvmorx

  FT_LOCAL_DEF( void )
  gxv_morx_subtable_type4_validate( FT_Bytes       table,
                                    FT_Bytes       limit,
                                    GXV_Validator  gxvalid )
  {
    GXV_NAME_ENTER( "morx chain subtable type4 "
                    "(Non-Contextual Glyph Substitution)" );

    gxv_mort_subtable_type4_validate( table, limit, gxvalid );

    GXV_EXIT;
  }

/* END */


text:
<!-- .slide: data-background="url(img/tiy.svg) no-repeat center" data-background-size="contain"-->

## What is this talk about?

## What are Web Components?

<!-- .slide: data-transition="fade" -->
* HTML Imports
* Templates
* Custom Elements
* Shadow DOM

<!-- .slide: data-transition="fade" -->
* HTML Imports
* Templates
* *Custom Elements!*
* *Shadow DOM!*

## Custom Elements

### Data is passed via attributes the Element/Component takes over from there

```html
<my-custom-element user-name="Bob">

</my-custom-element>
```

<input type="date">

# JS Frameworks

<!-- .slide: data-background="url(img/polymer.png) no-repeat center" data-background-size="contain"-->

<!-- .slide: data-background="url(img/react.png) no-repeat center" data-background-size="contain"-->

<!-- .slide: data-background="url(img/tomster.png) no-repeat center" data-background-size="contain"-->

<!-- .slide: data-background="url(img/danny.gif) no-repeat center" data-background-size="contain"-->

# COME PLAY WITH US

# We don't need a Single Page App

# We don't need a JS Framework

# What can we learn from web components?

## Small units with predictable inputs and predictable outputs are easier to support.

# Composability

# Maintanability

## What can web components teach us about composability on the server?

<!-- .slide: data-background="url(img/wireframe.svg) no-repeat center" data-background-size="contain"-->

# "LIVE CODING"
## [Code Examples](https://github.com/rtablada/refactoring-web-components-app)

<!-- .slide: data-background="url(img/bird.jpg) no-repeat center" data-background-size="contain"-->

# Put Some Javascript On It!

# Questions?
## Ryan Tablada ([@ryantablada](http://twitter.com/ryantablada))
## [Code Examples](https://github.com/rtablada/refactoring-web-components-app)
## Iron Yard


text:
#import "TGActor.h"

#import "ASWatcher.h"

@interface TGRevokeSessionsActor : TGActor <ASWatcher>

@property (nonatomic, strong) ASHandle *actionHandle;

- (void)revokeSessionsSuccess;
- (void)revokeSessionsFailed;

@end


text:
id: 5a661e0f1068aca922b3ef17
title: Access an Array's Contents Using Bracket Notation
challengeType: 1
forumTopicId: 301149
dashedName: access-an-arrays-contents-using-bracket-notation
---

# --description--

The fundamental feature of any data structure is, of course, the ability to not only store data, but to be able to retrieve that data on command. So, now that we've learned how to create an array, let's begin to think about how we can access that array's information.

When we define a simple array as seen below, there are 3 items in it:

```js
let ourArray = ["a", "b", "c"];
```

In an array, each array item has an <dfn>index</dfn>. This index doubles as the position of that item in the array, and how you reference it. However, it is important to note, that JavaScript arrays are <dfn>zero-indexed</dfn>, meaning that the first element of an array is actually at the ***zeroth*** position, not the first. In order to retrieve an element from an array we can enclose an index in brackets and append it to the end of an array, or more commonly, to a variable which references an array object. This is known as <dfn>bracket notation</dfn>. For example, if we want to retrieve the `a` from `ourArray` and assign it to a variable, we can do so with the following code:

```js
let ourVariable = ourArray[0];
```

Now `ourVariable` has the value of `a`.

In addition to accessing the value associated with an index, you can also *set* an index to a value using the same notation:

```js
ourArray[1] = "not b anymore";
```

Using bracket notation, we have now reset the item at index 1 from the string `b`, to `not b anymore`. Now `ourArray` is `["a", "not b anymore", "c"]`.

# --instructions--

In order to complete this challenge, set the 2nd position (index `1`) of `myArray` to anything you want, besides the letter `b`.

# --hints--

`myArray[0]` should be equal to the letter `a`

```js
assert.strictEqual(myArray[0], 'a');
```

`myArray[1]` should not be equal to the letter `b`

```js
assert.notStrictEqual(myArray[1], 'b');
```

`myArray[2]` should be equal to the letter `c`

```js
assert.strictEqual(myArray[2], 'c');
```

`myArray[3]` should be equal to the letter `d`

```js
assert.strictEqual(myArray[3], 'd');
```

# --seed--

## --seed-contents--

```js
let myArray = ["a", "b", "c", "d"];
// Only change code below this line

// Only change code above this line
console.log(myArray);
```

# --solutions--

```js
let myArray = ["a", "b", "c", "d"];
myArray[1] = "e";
```


text:
from django.views import View
from django.http import HttpResponse

class MyView(View):
    def get(self, request):
        """
        GZipMiddleware will NOT compress content if any of the following are true:
            * The content body is less than 200 bytes long.
            * The response has already set the Content-Encoding header.
            * The request (the browser) hasn't sent an Accept-Encoding header containing gzip.
        """
        response = HttpResponse('r' * 300)
        response['ETag'] = '"etag_value"'
        return response


text:
<?php

namespace Nfilin\Libs;

/**
 * Class BaseObject
 * @package Nfilin\Libs
 */
abstract class BaseObject
{
    use BaseTrait;
}


text:
import mock
import unittest

from .helper import _ResourceMixin

class AccountTest(_ResourceMixin, unittest.TestCase):

    def _getTargetClass(self):
        from .. import Account
        return Account

    def _makeOne(self):
        return self._getTargetClass().from_data({
            "object": "account",
            "location": "/account",
            "id": "acct_test",
            "email": None,
            "created": "2014-10-20T08:21:42Z",
            "chain_enabled": False
        })

    @mock.patch('requests.get')
    def test_retrieve(self, api_call):
        class_ = self._getTargetClass()
        self.mockResponse(api_call, """{
            "object": "account",
            "id": "acct_test",
            "email": null,
            "created": "2014-10-20T08:21:42Z"
        }""")

        account = class_.retrieve()
        self.assertTrue(isinstance(account, class_))
        self.assertEqual(account.id, 'acct_test')
        self.assertEqual(account.created, '2014-10-20T08:21:42Z')
        self.assertRequest(api_call, 'https://api.omise.co/account')

        self.mockResponse(api_call, """{
            "object": "account",
            "id": "acct_foo",
            "email": null,
            "created": "2014-10-20T08:21:42Z"
        }""")

        account.reload()
        self.assertEqual(account.id, 'acct_foo')
        self.assertRequest(api_call, 'https://api.omise.co/account')

    @mock.patch('requests.patch')
    def test_update(self, api_call):
        account = self._makeOne()
        class_ = self._getTargetClass()
        self.mockResponse(api_call, """{
          "object": "account",
          "id": "account_test_no1t4tnemucod0e51mo",
          "team": "acct_no1t4tnemucod0e51mo",
          "livemode": false,
          "location": "/account",
          "country": "TH",
          "currency": "THB",
          "email": "somchai.prasert@example.com",
          "created_at": "2019-12-31T12:59:59Z",
          "supported_currencies": [
            "THB",
            "JPY",
            "USD",
            "EUR",
            "GBP",
            "SGD",
            "AUD",
            "CHF",
            "CNY",
            "DKK",
            "HKD"
          ],
          "api_version": "2019-05-29",
          "auto_activate_recipients": true,
          "chain_enabled": true,
          "zero_interest_installments": true,
          "chain_return_uri": "https://omise-flask-example.herokuapp.com",
          "webhook_uri": "https://omise-flask-example.herokuapp.com/webhook",
          "metadata_export_keys": {
            "charge": [
              "color",
              "order_id"
            ]
          }
        }""")

        self.assertTrue(isinstance(account, class_))
        self.assertFalse(account.chain_enabled)
        account.update(chain_enabled=True)
        self.assertTrue(account.chain_enabled)
        self.assertRequest(
            api_call,
            'https://api.omise.co/account',
            {
                'chain_enabled': True,
            }
        )


text:
$plan = Get-WmiObject -Class win32_powerplan -Namespace root\cimv2\power | Where-Object {$_.IsActive -eq "True"}
$regex = [regex]"{(.*?)}$"
$planGuid = $regex.Match($plan.instanceID.Tostring()).groups[1].value
$power = powercfg -query $planGuid 238c9fa8-0aad-41ed-83f4-97be242c8f20
$sleep = powercfg -query $planGuid SUB_SLEEP STANDBYIDLE
$sleepValue = $sleep  | Select-String "Current AC Power Setting Index"
$hibernate = powercfg -query $planGuid SUB_SLEEP HIBERNATEIDLE
$hibernateValue = $hibernate| Select-String "Current AC Power Setting Index"
Write-Host "Sleep After:" $sleepValue.ToString().Split(":")[1]
Write-Host "Hibernate After:" $hibernateValue.ToString().Split(":")[1]


text:
/**
 * Provides FormatReader and FormatWriter classes in support of the bedrock package. JSON and
 * some basic formats might be facilitated by a registered file mime-type association, but
 * you can add your own association to a reader (and its configuration) by using something
 * like this:
 * {@code
 *    FormatReader.registerFormatReader ("MyCustomTypeName", false, (input) -> new FormatReaderFixed (input, new int[]{3, 3, 3, 4}));
 *    BagArray bagArray = BagArrayFrom.string (stringInput, "MyCustomTypeName");
 * }
 * @author Bretton Wade
 */
package com.brettonw.bedrock.bag.formats;


text:
package migrations

import "github.com/BurntSushi/migration"

func AddTeamIDToVolumes(tx migration.LimitedTx) error {
	_, err := tx.Exec(`
    ALTER TABLE volumes
      ADD COLUMN team_id integer
      REFERENCES teams (id)
      ON DELETE SET NULL;
	`)

	return err
}


text:
package cn.gaohongtao.expressweb;

import java.lang.reflect.Method;

import cn.gaohongtao.police.mobile.InterfaceService;
import cn.gaohongtao.police.mobile.controller.TaskController;
import cn.gaohongtao.police.mobile.interceptor.ServiceErrorInterceptor;
import cn.gaohongtao.police.mobile.model.EovaDepart;
import cn.gaohongtao.police.mobile.model.EovaDict;
import cn.gaohongtao.police.mobile.model.TFileInfo;
import cn.gaohongtao.police.mobile.model.TTask;
import com.eova.config.EovaConfig;
import com.eova.interceptor.LoginInterceptor;
import com.jfinal.config.Interceptors;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.JFinal;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;

/**
 * @author gaohongtao
 */
public class ExpressWebConfig extends EovaConfig {

    /**
     * 自定义路由
     *
     * @param me
     */
    @Override
    protected void route(Routes me) {
        // 自定义的路由配置往这里加。。。
        me.add("/service", InterfaceService.class);
        me.add("/police_task", TaskController.class);

        // 不需要登录拦截的URL
        LoginInterceptor.excludes.add("/init");

        InterfaceService.class.getMethods();
        for (Method method : InterfaceService.class.getMethods()) {
            LoginInterceptor.excludes.add("/service/" + method.getName());
        }
    }

    /**
     * 自定义Main数据源Model映射
     *
     * @param arp
     */
    @Override
    protected void mapping(ActiveRecordPlugin arp) {
        // 自定义的Model映射往这里加。。。
        arp.addMapping("t_file_info", TFileInfo.class);
        arp.addMapping("t_task", TTask.class);
    }

    protected void mappingEova(ActiveRecordPlugin arp) {
        super.mappingEova(arp);
        arp.addMapping("eova_depart", EovaDepart.class);
        arp.addMapping("eova_dict", EovaDict.class);
    }

    /**
     * 自定义插件
     */
    @Override
    protected void plugin(Plugins plugins) {
        // 添加数据源

        // 添加自动扫描插件

        // ...
    }

    @Override
    public void configInterceptor(Interceptors me) {
        super.configInterceptor(me);
        me.add(new ServiceErrorInterceptor());
    }

    /**
     * Run Server
     *
     * @param args
     */
    public static void main(String[] args) {
        JFinal.start("web", 8080, "/", 0);
    }

}


text:
(function (ang) {

	var app = ang.module('app');

	app.config(function ($resourcesProvider, $stateProvider, $urlRouterProvider) {

		// Router
			// $urlRouterProvider.otherwise("/");
			$stateProvider
				.state('stateX', {
					url: '/state-x',
					template: 'State X',
				})

	});

})(angular);


text:
package com.microsoft.azure.management.recoveryservices.backup.v2016_06_01.implementation;

import com.microsoft.azure.management.recoveryservices.backup.v2016_06_01.AzureIaaSVMProtectedItem;
import com.microsoft.azure.management.recoveryservices.backup.v2016_06_01.AzureSqlProtectedItem;
import com.microsoft.azure.management.recoveryservices.backup.v2016_06_01.BackupManagementType;
import com.microsoft.azure.management.recoveryservices.backup.v2016_06_01.DataSourceType;
import com.microsoft.azure.management.recoveryservices.backup.v2016_06_01.MabFileFolderProtectedItem;
import org.joda.time.DateTime;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.JsonSubTypes;

/**
 * The base class for backup items.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "protectedItemType")
@JsonTypeName("ProtectedItem")
@JsonSubTypes({
    @JsonSubTypes.Type(name = "AzureIaaSVMProtectedItem", value = AzureIaaSVMProtectedItem.class),
    @JsonSubTypes.Type(name = "MabFileFolderProtectedItem", value = MabFileFolderProtectedItem.class),
    @JsonSubTypes.Type(name = "Microsoft.Sql/servers/databases", value = AzureSqlProtectedItem.class)
})
public class ProtectedItemInner {
    /**
     * The backup managemenent type associated with the backup item. Possible
     * values include: 'Invalid', 'AzureIaasVM', 'MAB', 'DPM',
     * 'AzureBackupServer', 'AzureSql'.
     */
    @JsonProperty(value = "backupManagementType")
    private BackupManagementType backupManagementType;

    /**
     * The workload type for this item. Possible values include: 'Invalid',
     * 'VM', 'FileFolder', 'AzureSqlDb', 'SQLDB', 'Exchange', 'Sharepoint',
     * 'DPMUnknown'.
     */
    @JsonProperty(value = "workloadType")
    private DataSourceType workloadType;

    /**
     * The ID of the resource to be backed up.
     */
    @JsonProperty(value = "sourceResourceId")
    private String sourceResourceId;

    /**
     * The ID of the backup policy associated with this backup item.
     */
    @JsonProperty(value = "policyId")
    private String policyId;

    /**
     * The timestamp when the most recent backup copy was created for this
     * backup item.
     */
    @JsonProperty(value = "lastRecoveryPoint")
    private DateTime lastRecoveryPoint;

    /**
     * Get the backup managemenent type associated with the backup item. Possible values include: 'Invalid', 'AzureIaasVM', 'MAB', 'DPM', 'AzureBackupServer', 'AzureSql'.
     *
     * @return the backupManagementType value
     */
    public BackupManagementType backupManagementType() {
        return this.backupManagementType;
    }

    /**
     * Set the backup managemenent type associated with the backup item. Possible values include: 'Invalid', 'AzureIaasVM', 'MAB', 'DPM', 'AzureBackupServer', 'AzureSql'.
     *
     * @param backupManagementType the backupManagementType value to set
     * @return the ProtectedItemInner object itself.
     */
    public ProtectedItemInner withBackupManagementType(BackupManagementType backupManagementType) {
        this.backupManagementType = backupManagementType;
        return this;
    }

    /**
     * Get the workload type for this item. Possible values include: 'Invalid', 'VM', 'FileFolder', 'AzureSqlDb', 'SQLDB', 'Exchange', 'Sharepoint', 'DPMUnknown'.
     *
     * @return the workloadType value
     */
    public DataSourceType workloadType() {
        return this.workloadType;
    }

    /**
     * Set the workload type for this item. Possible values include: 'Invalid', 'VM', 'FileFolder', 'AzureSqlDb', 'SQLDB', 'Exchange', 'Sharepoint', 'DPMUnknown'.
     *
     * @param workloadType the workloadType value to set
     * @return the ProtectedItemInner object itself.
     */
    public ProtectedItemInner withWorkloadType(DataSourceType workloadType) {
        this.workloadType = workloadType;
        return this;
    }

    /**
     * Get the ID of the resource to be backed up.
     *
     * @return the sourceResourceId value
     */
    public String sourceResourceId() {
        return this.sourceResourceId;
    }

    /**
     * Set the ID of the resource to be backed up.
     *
     * @param sourceResourceId the sourceResourceId value to set
     * @return the ProtectedItemInner object itself.
     */
    public ProtectedItemInner withSourceResourceId(String sourceResourceId) {
        this.sourceResourceId = sourceResourceId;
        return this;
    }

    /**
     * Get the ID of the backup policy associated with this backup item.
     *
     * @return the policyId value
     */
    public String policyId() {
        return this.policyId;
    }

    /**
     * Set the ID of the backup policy associated with this backup item.
     *
     * @param policyId the policyId value to set
     * @return the ProtectedItemInner object itself.
     */
    public ProtectedItemInner withPolicyId(String policyId) {
        this.policyId = policyId;
        return this;
    }

    /**
     * Get the timestamp when the most recent backup copy was created for this backup item.
     *
     * @return the lastRecoveryPoint value
     */
    public DateTime lastRecoveryPoint() {
        return this.lastRecoveryPoint;
    }

    /**
     * Set the timestamp when the most recent backup copy was created for this backup item.
     *
     * @param lastRecoveryPoint the lastRecoveryPoint value to set
     * @return the ProtectedItemInner object itself.
     */
    public ProtectedItemInner withLastRecoveryPoint(DateTime lastRecoveryPoint) {
        this.lastRecoveryPoint = lastRecoveryPoint;
        return this;
    }

}


text:
from collections import Counter
import re

import math

class EmbeddingLookup(object):

    def __init__(self, top_n=None, use_tf_idf_importance=False):
        self._tokenizer = re.compile("\w+|\$[\d\.]+").findall
        self._top_n = top_n
        self._use_tf_idf = use_tf_idf_importance

        self._dictionary = None
        self._reverse = None
        self._unknown = "<unk>"

    def _get_top_n_tokens_tf_idf(self, corpus):
        # create set of tokens for each document
        doc_lookups = [set(self._tokenizer(document)) for document in corpus]

        inverse_df = []
        for i in range(len(corpus)):
            document = doc_lookups[i]

            # for each document, find all of the unique words
            # these will be counted up at the end (unique occurrences) to get document frequencies
            present_tokens = document.intersection(self._dictionary)
            inverse_df.extend(present_tokens)

        # compute the smooth TF-IDF values
        inverse_df = {k: math.log(1 + (1 + len(corpus)) / (1 + v)) for k, v in Counter(inverse_df).items()}
        total_dfs = sum(self._dictionary.values())
        tf_idf = {token: (self._dictionary[token] / total_dfs) * inverse_df[token] for token in inverse_df}

        # sort by TF-IDF values, descending, then build the dictionary using these tokens
        sort_terms = sorted(tf_idf.items(), key=lambda x: x[1], reverse=True)[:self._top_n]
        top = {item[0]: idx + 1 for idx, item in enumerate(sort_terms)}
        top[self._unknown] = len(top) + 1
        return top

    def _get_top_n_tokens(self):
        top = self._dictionary.most_common(self._top_n)
        top = {item[0]: idx + 1 for idx, item in enumerate(top)}
        top[self._unknown] = len(top) + 1
        return top

    def fit(self, corpus):
        tokens = [word for text in corpus for word in self._tokenizer(text.strip())]
        self._dictionary = Counter(tokens)

        if self._top_n is not None and self._top_n < len(self._dictionary):
            if self._use_tf_idf:
                self._dictionary = self._get_top_n_tokens_tf_idf(corpus)
            else:
                self._dictionary = self._get_top_n_tokens()
        else:
            self._dictionary = {item[0]: idx + 1 for idx, item in enumerate(self._dictionary.items())}

            # add the <unk> token to the embedding lookup
            size = len(self._dictionary)
            self._dictionary[self._unknown] = size + 1

        self._reverse = {v: k for k, v in self._dictionary.items()}
        return self

    def transform(self, corpus):
        if self._dictionary is None:
            raise AttributeError("You must fit the lookup first, either by calling the fit or fit_transform methods.")

        corpus = [
            [
                self._dictionary[word] if word in self._dictionary else self._dictionary[self._unknown]
                for word in self._tokenizer(text.strip())
            ] for text in corpus]
        return corpus

    def fit_transform(self, corpus):
        self.fit(corpus)
        return self.transform(corpus)

    def __getitem__(self, key):
        if not isinstance(self._dictionary, dict):
            raise TypeError("You must fit the lookup first, either by calling the fit or fit_transform methods.")
        return self._dictionary.get(key, None)

    @property
    def reverse(self):
        return self._reverse


text:
Thank you for your interest in contributing to the SlamEngine open source project.

This contributor agreement ("Agreement") describes the terms and conditions under which you may Submit a Contribution to Us. By Submitting a Contribution to Us, you accept the terms and conditions in the Agreement. If you do not accept the terms and conditions in the Agreement, you must not Submit any Contribution to Us.

This is a legally binding document, so please read it carefully before accepting the terms and conditions. If you accept this Agreement, the then-current version of this Agreement shall apply each time you Submit a Contribution. The Agreement may cover more than one software project managed by Us.

## 1. Definitions

"We" or "Us" means SlamData, Inc, a corporation registered in the state of Delaware, whose file number is 5368278 under request number 130885478 for authentication number 0591375.

"You" means the individual or entity who Submits a Contribution to Us.

"Contribution" means any work of authorship that is Submitted by You to Us in which You own or assert ownership of the Copyright. You may not Submit a Contribution if you do not own the Copyright in the entire work of authorship.

"Copyright" means all rights protecting works of authorship owned or controlled by You, including copyright, moral and neighboring rights, as appropriate, for the full term of their existence including any extensions by You.

"Material" means the work of authorship which is made available by Us to third parties. When this Agreement covers more than one software project, the Material means the work of authorship to which the Contribution was Submitted. After You Submit the Contribution, it may be included in the Material.

"Submit" means any form of electronic, verbal, or written communication sent to Us or our representatives, including but not limited to electronic mailing lists, electronic mail, source code control systems, pull requests, and issue tracking systems that are managed by, or on behalf of, Us for the purpose of discussing and improving the Material, but excluding communication that is conspicuously marked or otherwise designated in writing by You as "Not a Contribution."

"Submission Date" means the date on which You Submit a Contribution to Us.

"Effective Date" means the earliest date You execute this Agreement by Submitting a Contribution to Us.

## 2. Grant of Rights

### 2.1 Copyright License

2.1.1. You retain ownership of the Copyright in Your Contribution and have the same rights to use or license the Contribution which You would have had without entering into the Agreement.

2.1.2. To the maximum extent permitted by the relevant law, You grant to Us a perpetual, worldwide, non-exclusive, transferable, royalty-free, irrevocable license under the Copyright covering the Contribution, with the right to sublicense such rights through multiple tiers of sublicensees, to reproduce, modify, display, perform and distribute the Contribution as part of the Material; provided that this license is conditioned upon compliance with Section 2.3.

### 2.2 Patent License

For patent claims including, without limitation, method, process, and apparatus claims which You own, control or have the right to grant, now or in the future, You grant to Us a perpetual, worldwide, non-exclusive, transferable, royalty-free, irrevocable patent license, with the right to sublicense these rights to multiple tiers of sublicensees, to make, have made, use, sell, offer for sale, import and otherwise transfer the Contribution and the Contribution in combination with the Material (and portions of such combination). This license is granted only to the extent that the exercise of the licensed rights infringes such patent claims; and provided that this license is conditioned upon compliance with Section 2.3.

### 2.3 Outbound License

Based on the grant of rights in Sections 2.1 and 2.2, if We include Your Contribution in a Material, We may license the Contribution under any license, including copyleft, permissive, commercial, or proprietary licenses. As a condition on the exercise of this right, We agree to also license the Contribution under the terms of the license or licenses which We are using for the Material on the Submission Date.

### 2.4 Moral Rights.

If moral rights apply to the Contribution, to the maximum extent permitted by law, You waive and agree not to assert such moral rights against Us or our successors in interest, or any of our licensees, either direct or indirect.

### 2.5 Our Rights.

You acknowledge that We are not obligated to use Your Contribution as part of the Material and may decide to include any Contribution We consider appropriate.

### 2.6 Reservation of Rights.

Any rights not expressly licensed under this section are expressly reserved by You.

## 3. Agreement

You confirm that:

a. You have the legal authority to enter into this Agreement.

b. You own the Copyright and patent claims covering the Contribution which are required to grant the rights under Section 2.

c. The grant of rights under Section 2 does not violate any grant of rights which You have made to third parties, including Your employer. If You are an employee, You have had Your employer approve this Agreement or sign the Entity version of this document. If You are less than eighteen years old, please have Your parents or guardian sign the Agreement.

d. You have followed the instructions in, if You do not own the Copyright in the entire work of authorship Submitted.

## 4. Disclaimer

EXCEPT FOR THE EXPRESS WARRANTIES IN SECTION 3, THE CONTRIBUTION IS PROVIDED "AS IS". MORE PARTICULARLY, ALL EXPRESS OR IMPLIED WARRANTIES INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE EXPRESSLY DISCLAIMED BY YOU TO US. TO THE EXTENT THAT ANY SUCH WARRANTIES CANNOT BE DISCLAIMED, SUCH WARRANTY IS LIMITED IN DURATION TO THE MINIMUM PERIOD PERMITTED BY LAW.

## 5. Consequential Damage Waiver

TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT WILL YOU BE LIABLE FOR ANY LOSS OF PROFITS, LOSS OF ANTICIPATED SAVINGS, LOSS OF DATA, INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL AND EXEMPLARY DAMAGES ARISING OUT OF THIS AGREEMENT REGARDLESS OF THE LEGAL OR EQUITABLE THEORY (CONTRACT, TORT OR OTHERWISE) UPON WHICH THE CLAIM IS BASED.

## 6. Miscellaneous

6.1. This Agreement will be governed by and construed in accordance with the laws of the state of Colorado, in the United States of America, excluding its conflicts of law provisions. Under certain circumstances, the governing law in this section might be superseded by the United Nations Convention on Contracts for the International Sale of Goods ("UN Convention") and the parties intend to avoid the application of the UN Convention to this Agreement and, thus, exclude the application of the UN Convention in its entirety to this Agreement.

6.2. This Agreement sets out the entire agreement between You and Us for Your Contributions to Us and overrides all other agreements or understandings.

6.3. If You or We assign the rights or obligations received through this Agreement to a third party, as a condition of the assignment, that third party must agree in writing to abide by all the rights and obligations in the Agreement.

6.4. The failure of either party to require performance by the other party of any provision of this Agreement in one situation shall not affect the right of a party to require such performance at any time in the future. A waiver of performance under a provision in one situation shall not be considered a waiver of the performance of the provision in the future or a waiver of the provision in its entirety.

6.5. If any provision of this Agreement is found void and unenforceable, such provision will be replaced to the extent possible with a provision that comes closest to the meaning of the original provision and which is enforceable. The terms and conditions set forth in this Agreement shall apply notwithstanding any failure of essential purpose of this Agreement or any limited remedy to the maximum extent possible under law.


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="generator" content="NaanPlayableCharacter">
    <title>Archives: 2020/3 - NaanPlayableCharacter</title>
    <meta name="author" content="NaanPlayableCharacter">
    <meta name="theme-color" content="#1d1f21">
    <link rel="canonical" href="https://blog.prashantsinha.info/archives/2020/03/"/>

        <meta name="keywords" content="Guitar,Gaming,Programming,AI,Science,Music,">

        <link rel="shortcut icon" href="/assets/images/favicon.ico">

        <link rel="icon" type="image/png" href="/assets/images/favicon-16x16.png" sizes="16x16">

        <link rel="icon" type="image/png" href="/assets/images/favicon-32x32.png" sizes="32x32">

        <link rel="apple-touch-icon" sizes="180x180" href="/assets/images/apple-touch-icon.png">

        <link rel="manifest" href="/assets/images/manifest.json">

        <link rel="mask-icon" href="/assets/images/safari-pinned-tab.svg" color="#1d1f21">

        <meta name="msapplication-config" content="/assets/images/browserconfig.xml">

    <meta name="apple-mobile-web-app-title" content="NaanPlayableCharacter">
	<meta name="application-name" content="NaanPlayableCharacter">

        <link rel="alternate" type="application/atom+xml" title="RSS" href="/atom.xml">

    <meta name="description" content="About Music | Games | Programming | CGI | Science">
<meta property="og:type" content="blog">
<meta property="og:title" content="NaanPlayableCharacter">
<meta property="og:url" content="https://blog.prashantsinha.info/archives/2020/03/index.html">
<meta property="og:site_name" content="NaanPlayableCharacter">
<meta property="og:description" content="About Music | Games | Programming | CGI | Science">
<meta property="og:locale" content="en_US">
<meta property="article:author" content="NaanPlayableCharacter">
<meta property="article:tag" content="Guitar">
<meta property="article:tag" content="Gaming">
<meta property="article:tag" content="Programming">
<meta property="article:tag" content="AI">
<meta property="article:tag" content="Science">
<meta property="article:tag" content="Music">
<meta name="twitter:card" content="summary">
<meta name="twitter:creator" content="@fortytwoblog">
<meta property="fb:app_id" content="441349206213726">

        <link rel="publisher" href="https://plus.google.com/+PrashantSinhaFortyTwo">

            <meta property="fb:admins" content="160090960757109">

        	<meta property="twitter:image" content="https://blog.prashantsinha.info/assets/images/og-image.jpg">
            <meta property="og:image" content="https://blog.prashantsinha.info/assets/images/og-image.jpg">
			<meta property="og:image:height" content="313">
			<meta property="og:image:width" content="599">

<link rel="stylesheet" href="/assets/css/style.css">

        NaanPlayableCharacter

NaanPlayableCharacter

Prashant Sinha
Music | Games | Programming | CGI | Science
Subscribe

                        Home

                        Categories

                        Tags

                        Archives

                        Search

                        Mail

                        About

                        Youtube

                        GitHub

                        Facebook

                        Twitter

                        LinkedIn

                        RSS

                            Epic Guitar Riffs

    <time itemprop="datePublished" datetime="2020-03-21T19:58:16+05:30">

		    21 Mar, 2020

    </time>

        in

    Music

A playlist of some of the greatest guitar riffs and intros from all time, played by me.

                            Continue reading

page 1 of 1

Copyrights © 2020 NaanPlayableCharacter. All Rights Reserved.

NaanPlayableCharacter

Prashant Sinha
Music | Games | Programming | CGI | Science
Subscribe

Programmer | Graphic Designer | Animator

                by

            <form id="algolia-search-form">
                <input type="text" id="algolia-search-input" name="search"
                    class="form-control input--large search-input" placeholder="Search "
                    />
            </form>

no post found

May The Source Be With You!

                                    Jun 6, 2017

Here's why I am switching from 3DS Max to Blender as my primary 3D software.

Epic Guitar Riffs

                                    Mar 21, 2020

A playlist of some of the greatest guitar riffs and intros from all time, played by me.

                2 posts found


text:
package org.javacint.console;

import java.io.InputStream;
import java.io.PrintStream;
import org.javacint.gps.GpsManager;
import org.javacint.gps.GpsPosition;
import org.javacint.gps.GpsPositionListener;

/**
 * GPS Testing command.
 *
 * This command is only intended for testing.
 */
public class GPSTestCommand implements ConsoleCommand, GpsPositionListener {

    private final GpsManager gps;
    private PrintStream out;

    public GPSTestCommand() {
        this.gps = new GpsManager(this);
    }

    public boolean consoleCommand(String command, InputStream is, PrintStream out) {
        if (command.startsWith("gps ")) {
            command = command.substring(4);
            if ("start".equals(command)) {
                gps.start();
                this.out = out;
                return true;
            } else if ("stop".equals(command)) {
                gps.stop();
                return true;
            } else {
                out.println("[HELP] gps [start|stop]");
            }
        } else if (command.equals("help")) {
            out.println("[HELP] gps [start|stop]                 - GPS start/stop");
        }
        return false;
    }

    public void positionReceived(GpsPosition pos) {
        if (out != null) {
            out.println("[GPS POS] " + pos);
        }
    }

    public void positionAdditionnalReceived(String type, String value) {
        if (out != null) {
            out.println("[GPS LOG] " + type + " : " + value);
        }
    }
}


text:
echo "start exec"

# define variable
TEST_FILE_PATH=/Users/lianghe/github/shell-test/com.github.dunnohe/test

cd $TEST_FILE_PATH

cat /dev/null > test
echo "exec end"


text:
package org.camunda.bpm.model.bpmn.instance;

import org.camunda.bpm.model.bpmn.Query;
import org.camunda.bpm.model.bpmn.builder.AbstractFlowNodeBuilder;

import java.util.Collection;

/**
 * The BPMN flowNode element
 *
 * @author Sebastian Menski
 */
public interface FlowNode extends FlowElement {

  @SuppressWarnings("rawtypes")
  AbstractFlowNodeBuilder builder();

  Collection<SequenceFlow> getIncoming();

  Collection<SequenceFlow> getOutgoing();

  Query<FlowNode> getPreviousNodes();

  Query<FlowNode> getSucceedingNodes();

  boolean isCamundaAsyncBefore();

  void setCamundaAsyncBefore(boolean isCamundaAsyncBefore);

  boolean isCamundaAsyncAfter();

  void setCamundaAsyncAfter(boolean isCamundaAsyncAfter);

  boolean isCamundaExclusive();

  void setCamundaExclusive(boolean isCamundaExclusive);

  String getCamundaJobPriority();

  void setCamundaJobPriority(String jobPriority);

}


text:
layout: post
title: 'Upgrading Wordpress'
date: 2006-11-01 18:28
comments: true
categories : []
---

Well I finally got around to upgrading my wordpress installation from 2.0.1 to the latest greatest of 2.0.5. It was incredibly simple and here's a quick 5 step upgrade plan.

Step 1: Backup Database Tables and Files including .htaccess and wp-config.php
I used mysqldump to backup the tables and moved my .htaccess and wp-config.php files to a safe directory.
Step 2: Deactivate Plugins
Go to your WP Admin panel and manually deactivate all your plugins.
Step 3: Overwrite Files
Download and Unzip the latest version of Wordpress. The copy all the new files over to your current wordpress installation.
Step 4: Run the upgrade script
Run the upgrade script that should now be located at your local wordpress install. www.yourserver.com/path/to/wordpress/wp-admin/upgrade.php
Step 5: Reactivate Plugins one by one
Now all you have to do is reactivate your plugins and your upgrade should be complete.


text:
from zope.interface import Interface

class IDataTable(Interface):
    """
    Basic methods to deal with jQuery datatables with souper.soup
    """
    def column_info(self):
        """
        info about the avaiable columns. It is a list with a dictionary that contains
        information about each column

        col_info['label'] = is the columnheader displayed
        col_info['sortable'] = boolean value to describe if the column is sortable
        col_info['searchable'] = boolean value to describe if the column itself is searchable
        col_info['sortindex'] = default value is None. If none indexname equals the rowid
        else this index is taken for sorting.
        """

    def extract_parameters(self):
        """
        provides the default parameters for the columns, needed by jQuery
        They split up in the basic infos such as 'echo': '1', 'search': '',
        'slicelength': 10, 'slicestart': 0 and in the info for each column itself.
        These are stored like that:
        {0: {'dataprop': '0',        <-- first column
         'regex': False,
         'search': '',
         'searchable': True,
         'sortable': True},
         1: {'dataprop': '1',        <-- second column
         'regex': False,
         'search': '',
         'searchable': True,
         'sortable': True},          <-- and so on
        """

    def get_form(self):
        """
        get the form parameters as a dictionary
        """


text:
;(function(){

  "use strict";

  function EventEmitter() {
    this._listeners = {};
  }

  var addEventListener = function(emitter, event, callback, once) {
    emitter.listeners(event).push({
      callback: callback,
      once: Boolean(once)
    });

    return emitter;
  };

  EventEmitter.prototype.on = function(event, callback) {
    return addEventListener(this, event, callback, false);
  };

  EventEmitter.prototype.once = function(event, callback) {
    return addEventListener(this, event, callback, true);
  };

  EventEmitter.prototype.off = function(event, callback) {

    var result = [],
      listeners = this.listeners(event);

    if (!callback) {
      return delete(this._listeners[event]);
    }

    for (var i = 0; i < listeners.length; i++) {
      if (listeners[i].callback === callback) {
        continue;
      }

      result.push(listeners[i]);
    }

    this._listeners[event] = result;
  };

  EventEmitter.prototype.emit = function() {

    var obj,
      args = toArray(arguments),
      event = args.shift(),
      listeners = this.listeners(event);

    for (var i = 0; i < listeners.length; i++) {
      obj = listeners[i];
      obj.callback.apply(this, args);

      if(obj.once) {
        this.off(event, obj.callback);
      }
    }

  };

  EventEmitter.prototype.listeners = function(event) {
    return this._listeners[event] || (this._listeners[event] = []);
  };

  var toArray = function(args) {
    return args.length === 1 ? [args[0]] : Array.apply(null, args);
  };

  if (typeof module === "object" && module.exports){
    module.exports = EventEmitter;
  } else {
    if (typeof define === "function" && define.amd) {
      define([], function() {
        return EventEmitter;
      });
    } else {
      this.EventEmitter = EventEmitter;
    }
  }

})();


text:
/*
	Section: effects
*/
module Game {
	"use strict";

	/********************************************************************************
	 * Group: target selection
	 ********************************************************************************/
	/*
		Enum: TargetSelectionMethod
		Define how we select the actors that are impacted by an effect.

		ACTOR_ON_CELL - whatever actor is on the selected cell
		CLOSEST_ENEMY - the closest non player creature
		SELECTED_ACTOR - an actor manually selected
		ACTORS_RANGE - all actors close to the cell
		SELECTED_RANGE - all actors close to a manually selected position
	*/
	export const enum TargetSelectionMethod {
		ACTOR_ON_CELL,
		CLOSEST_ENEMY,
		SELECTED_ACTOR,
		ACTORS_IN_RANGE,
		SELECTED_RANGE
	}

	/*
		Class: TargetSelector
		Various ways to select actors
	*/
	export class TargetSelector implements Persistent {
		className: string;
		private _method: TargetSelectionMethod;
		private _range: number;
		private _radius: number;
		__selectedTargets: Actor[];
		/*
			Constructor: constructor

			Parameters:
			_method - the target selection method
			_range - *optional* for methods requiring a range
			_radius - *optional* for methods having a radius of effect
		*/
		constructor(_method: TargetSelectionMethod = undefined, _range?: number, _radius?: number) {
			this.className = "TargetSelector";
			this._method = _method;
			this._range = _range;
			this._radius = _radius;
		}

		/*
			Property: method
			The target selection method (read-only)
		*/
		get method() { return this._method; }

		/*
			Property: range
			The selection range (read-only)
		*/
		get range() { return this._range; }

		/*
			Property: radius
			Radius of effect around the selected position
		*/
		get radius() { return this._radius; }

		/*
			Function: selectTargets
			Populates the __selectedTargets field, or triggers the tile picker

			Parameters:
			owner - the actor owning the effect (the magic item or the scroll)
			wearer - the actor using the item
			cellPos - the cell where the effect applies (= the wearer position when used from inventory, or a different position when thrown)

			Returns:
			true if targets have been selected (else wait for TILE_SELECTED event, then call <onTileSelected>)
		*/
		selectTargets(owner: Actor, wearer: Actor, cellPos: Yendor.Position): boolean {
			this.__selectedTargets = [];
			var creatureIds: ActorId[] = Engine.instance.actorManager.getCreatureIds();
			var data: TilePickerEventData;
			switch (this._method) {
				case TargetSelectionMethod.ACTOR_ON_CELL :
					if ( cellPos ) {
						this.__selectedTargets = Engine.instance.actorManager.findActorsOnCell(cellPos, creatureIds);
					} else {
						this.__selectedTargets.push(wearer);
					}
					return true;
				case TargetSelectionMethod.CLOSEST_ENEMY :
					var actor = Engine.instance.actorManager.findClosestActor(cellPos ? cellPos : wearer, this.range, creatureIds);
					if ( actor ) {
						this.__selectedTargets.push(actor);
					}
					return true;
				case TargetSelectionMethod.ACTORS_IN_RANGE :
					this.__selectedTargets = Engine.instance.actorManager.findActorsInRange( cellPos ? cellPos : wearer, this.range, creatureIds );
					return true;
				case TargetSelectionMethod.SELECTED_ACTOR :
					log("Left-click a target creature,\nor right-click to cancel.", Constants.LOG_WARN_COLOR);
					data = {origin: new Yendor.Position(wearer.x, wearer.y), range: this._range, radius: this._radius};
					Engine.instance.eventBus.publishEvent(EventType.PICK_TILE, data);
					return false;
				case TargetSelectionMethod.SELECTED_RANGE :
					log("Left-click a target tile,\nor right-click to cancel.", Constants.LOG_WARN_COLOR);
					data = {origin: new Yendor.Position(wearer.x, wearer.y), range: this._range, radius: this._radius};
					Engine.instance.eventBus.publishEvent(EventType.PICK_TILE, data);
					return false;
			}
		}

		/*
			Function: onTileSelected
			Populates the __selectedTargets field for selection methods that require a tile selection
		*/
		onTileSelected(pos: Yendor.Position) {
			var creatureIds: ActorId[] = Engine.instance.actorManager.getCreatureIds();
			switch (this._method) {
				case TargetSelectionMethod.SELECTED_ACTOR :
					this.__selectedTargets = Engine.instance.actorManager.findActorsOnCell( pos, creatureIds);
				break;
				case TargetSelectionMethod.SELECTED_RANGE :
					this.__selectedTargets = Engine.instance.actorManager.findActorsInRange( pos, this._radius, creatureIds );
				break;
			}
		}
	}

	/********************************************************************************
	 * Group: conditions
	 ********************************************************************************/
	/*
		Enum: ConditionType

	 	CONFUSED - moves randomly and attacks anything on path
	 	STUNNED - don't move or attack, then get confused
	 	REGENERATION - regain health points over time
	 	OVERENCUMBERED - walk slower. This also affects all actions relying on walkTime.
	 	DETECT_LIFE - detect nearby living creatures
	*/
	export const enum ConditionType {
		CONFUSED,
		STUNNED,
		FROZEN,
		REGENERATION,
		OVERENCUMBERED,
		DETECT_LIFE,
	}

	export interface ConditionAdditionalParam {
		amount?: number;
		range?: number;
	}

	/*
	 	Class: Condition
	 	Permanent or temporary effect affecting a creature
	*/
	export class Condition implements Persistent {
		className: string;

		/*
	 		Property: time
	 		Time before this condition stops, or -1 for permanent conditions
		*/
		protected _time: number;
		protected _type: ConditionType;
		protected _initialTime: number;
		private static condNames = [ "confused", "stunned", "frozen", "regeneration", "overencumbered", "life detection" ];

		// factory
		static create(type: ConditionType, time: number, additionalArgs?: ConditionAdditionalParam): Condition {
			switch ( type ) {
				case ConditionType.REGENERATION :
					return new RegenerationCondition(time, additionalArgs.amount);
				case ConditionType.STUNNED :
					return new StunnedCondition(time);
				case ConditionType.FROZEN :
					return new FrozenCondition(time);
				case ConditionType.DETECT_LIFE :
					return new DetectLifeCondition(time, additionalArgs.range);
				default :
					return new Condition(type, time);
			}
		}

		constructor(type: ConditionType, time: number) {
			this.className = "Condition";
			this._initialTime = time;
			this._time = time;
			this._type = type;
		}

		get type() { return this._type; }
		get time() { return this._time; }
		get initialTime() { return this._initialTime; }
		getName() { return Condition.condNames[this._type]; }

		/*
			Function: onApply
			What happens when an actor gets this condition
		*/
		onApply(owner: Actor) {}
		/*
			Function: onApply
			What happens when this condition is removed from an actor
		*/
		onRemove(owner: Actor) {}

		/*
			Function: update
			What happens every turn when an actor has this condition

			Returns:
				false if the condition has ended
		*/
		update(owner: Actor): boolean {
			if ( this._time > 0 ) {
				this._time --;
				return (this._time > 0);
			}
			return true;
		}
	}

	/*
		Class: RegenerationCondition
		The creature gain health points over time
	*/
	export class RegenerationCondition extends Condition {
		private hpPerTurn: number;
		constructor(nbTurns: number, nbHP : number) {
			super(ConditionType.REGENERATION, nbTurns);
			this.className = "RegenerationCondition";
			this.hpPerTurn = nbHP / nbTurns;
		}

		update(owner: Actor): boolean {
			if (owner.destructible) {
				owner.destructible.heal(this.hpPerTurn);
			}
			return super.update(owner);
		}
	}

	/*
		Class: StunnedCondition
		The creature cannot move or attack while stunned. Then it gets confused for a few turns
	*/
	export class StunnedCondition extends Condition {
		constructor(nbTurns: number) {
			super(ConditionType.STUNNED, nbTurns);
			this.className = "StunnedCondition";
		}

		update(owner: Actor): boolean {
			if (! super.update(owner)) {
				if ( this.type === ConditionType.STUNNED) {
					// after being stunned, wake up confused
					this._type = ConditionType.CONFUSED;
					this._time = Constants.AFTER_STUNNED_CONFUSION_DELAY;
				} else {
					return false;
				}
			}
			return true;
		}
	}

	/*
		Class: DetectLifeCondition
		Detect creatures through walls
	*/
	export class DetectLifeCondition extends Condition {
		// above this range, creatures are not detected
		private _range: number;

		get range() { return this._range; }

		constructor(nbTurns: number, range: number) {
			super(ConditionType.DETECT_LIFE, nbTurns);
			this.className = "DetectLifeCondition";
			this._range = range;
		}
	}

	/*
		Class: FrozenCondition
		The creature is slowed down
	*/
	export class FrozenCondition extends Condition {
		private originalColor: Yendor.Color;
		constructor(nbTurns: number) {
			super(ConditionType.FROZEN, nbTurns);
			this.className = "FrozenCondition";
		}

		onApply(owner: Actor) {
			this.originalColor = owner.col;
			owner.col = Constants.FROST_COLOR;
		}

		onRemove(owner: Actor) {
			owner.col = this.originalColor;
		}

		update(owner: Actor): boolean {
			var progress = (this._time - 1) / this._initialTime;
			owner.col = Yendor.ColorUtils.add(Yendor.ColorUtils.multiply(Constants.FROST_COLOR, progress),
				Yendor.ColorUtils.multiply(this.originalColor, 1 - progress));
			return super.update(owner);
		}
	}

	/********************************************************************************
	 * Group: effects
	 ********************************************************************************/

	/*
		Interface: Effect
		Some effect that can be applied to actors. The effect might be triggered by using an item or casting a spell.
	*/
	export interface Effect extends Persistent {
		/*
			Function: applyTo
			Apply an effect to an actor

			Parameters:
			actor - the actor this effect is applied to
			coef - a multiplicator to apply to the effect

			Returns:
			false if effect cannot be applied
		*/
		applyTo(actor: Actor, coef: number): boolean;
	}

	/*
		Class: InstantHealthEffect
		Add or remove health points.
	*/
	export class InstantHealthEffect implements Effect {
		className: string;
		private _amount: number;
		private successMessage: string;
		private failureMessage: string;

		get amount() { return this._amount; }

		constructor( amount: number = 0, successMessage?: string, failureMessage?: string) {
			this.className = "InstantHealthEffect";
			this._amount = amount;
			this.successMessage = successMessage;
			this.failureMessage = failureMessage;
		}

		applyTo(actor: Actor, coef: number = 1.0): boolean {
			if (! actor.destructible ) {
				return false;
			}
			if ( this._amount > 0 ) {
				return this.applyHealingEffectTo(actor, coef);
			} else {
				return this.applyWoundingEffectTo(actor, coef);
			}
			return false;
		}

		private applyHealingEffectTo(actor: Actor, coef: number = 1.0): boolean {
			var healPointsCount: number = actor.destructible.heal( coef * this._amount );
			if ( healPointsCount > 0 && this.successMessage ) {
				log(transformMessage(this.successMessage, actor, undefined, healPointsCount));
			} else if ( healPointsCount <= 0 && this.failureMessage ) {
				log(transformMessage(this.failureMessage, actor));
			}
			return true;
		}

		private applyWoundingEffectTo(actor: Actor, coef: number = 1.0) : boolean {
			var realDefense: number = actor.destructible.computeRealDefense(actor);
			var damageDealt = -this._amount * coef - realDefense;
			if ( damageDealt > 0 && this.successMessage ) {
				log(transformMessage(this.successMessage, actor, undefined, damageDealt));
			} else if ( damageDealt <= 0 && this.failureMessage ) {
				log(transformMessage(this.failureMessage, actor));
			}
			return actor.destructible.takeDamage(actor, -this._amount * coef) > 0;
		}
	}

	/*
		Class: TeleportEffect
		Teleport the target at a random location.
	*/
	export class TeleportEffect implements Effect {
		className: string;
		private successMessage: string;

		constructor(successMessage?: string) {
			this.className = "TeleportEffect";
			this.successMessage = successMessage;
		}

		applyTo(actor: Actor, coef: number = 1.0): boolean {
			var x: number = Engine.instance.rng.getNumber(0, Engine.instance.map.width - 1);
			var y: number = Engine.instance.rng.getNumber(0, Engine.instance.map.height - 1);
			while (! Engine.instance.map.canWalk(x, y)) {
				x++;
				if ( x === Engine.instance.map.width ) {
					x = 0;
					y++;
					if ( y === Engine.instance.map.height ) {
						y = 0;
					}
				}
			}
			actor.moveTo(x, y);
			if ( this.successMessage) {
				log(transformMessage(this.successMessage, actor));
			}
			return true;
		}
	}

	/*
		Class: ConditionEffect
		Add a condition to an actor.
	*/
	export class ConditionEffect implements Effect {
		className: string;
		private type: ConditionType;
		private nbTurns: number;
		private message: string;
		private additionalArgs: ConditionAdditionalParam;
		constructor( type: ConditionType, nbTurns: number, message?: string, additionalArgs?: ConditionAdditionalParam ) {
			this.className = "ConditionEffect";
			this.type = type;
			this.nbTurns = nbTurns;
			this.message = message;
			if (additionalArgs) {
				this.additionalArgs = additionalArgs;
			}
		}

		applyTo(actor: Actor, coef: number = 1.0): boolean {
			if (!actor.ai) {
				return false;
			}
			actor.ai.addCondition(Condition.create(this.type, Math.floor(coef * this.nbTurns), this.additionalArgs),
				actor);
			if ( this.message ) {
				log(transformMessage(this.message, actor));
			}
			return true;
		}
	}

	export class MapRevealEffect implements Effect {
		className: string;
		constructor() {
			this.className = "MapRevealEffect";
		}

		applyTo(actor: Actor, coef: number = 1.0): boolean {
			if ( actor === Engine.instance.actorManager.getPlayer() ) {
				Engine.instance.map.reveal();
				return true;
			}
			return false;
		}
	}

	/*
	 	Class: Effector
	 	Combines an effect and a target selector. Can also display a message before applying the effect.
	*/
	export class Effector implements Persistent {
		className: string;
		private _effect: Effect;
		private targetSelector: TargetSelector;
		private message: string;
		private _coef: number;
		private destroyOnEffect: boolean;

		get effect() { return this._effect; }
		get coef() { return this._coef; }

		constructor(_effect?: Effect, _targetSelector?: TargetSelector, _message?: string, destroyOnEffect: boolean = false) {
			this.className = "Effector";
			this._effect = _effect;
			this.targetSelector = _targetSelector;
			this.message = _message;
			this.destroyOnEffect = destroyOnEffect;
		}

		/*
			Function: apply
			Select targets and apply the effect.

			Returns:
			false if a tile needs to be selected (in that case, wait for TILE_SELECTED event, then call <applyOnPos>)
		*/
		apply(owner: Actor, wearer: Actor, cellPos?: Yendor.Position, coef: number = 1.0): boolean {
			this._coef = coef;
			if (this.targetSelector.selectTargets(owner, wearer, cellPos)) {
				this.applyEffectToActorList(owner, wearer, this.targetSelector.__selectedTargets);
				return true;
			}
			return false;
		}

		/*
			Function: applyOnPos
			Select targets and apply the effect once a tile has been selected.

			Returns:
			false if no target has been selected
		*/
		applyOnPos(owner: Actor, wearer: Actor, pos: Yendor.Position): boolean {
			this.targetSelector.onTileSelected(pos);
			if ( this.targetSelector.__selectedTargets.length > 0 ) {
				this.applyEffectToActorList(owner, wearer, this.targetSelector.__selectedTargets);
				return true;
			} else {
				return false;
			}
		}

		private applyEffectToActorList(owner: Actor, wearer: Actor, actors: Actor[]) {
			var success: boolean = false;
			if ( this.message ) {
				log(transformMessage(this.message, wearer));
			}

			for (var i: number = 0, len: number = actors.length; i < len; ++i) {
				if (this._effect.applyTo(actors[i], this._coef)) {
					success = true;
				}
			}
			if ( this.destroyOnEffect && success && wearer && wearer.container ) {
				wearer.container.remove( owner, wearer );
				// actually remove actor from actorManager
			}
		}
	}
}


text:
package com.nkming.utils.str;

import java.util.Collection;

public class StrUtils
{
	/**
	 * Join multiple objects with toString(). @a glue will be inserted between
	 * each objects
	 *
	 * @param glue
	 * @param c
	 * @return
	 */
	public static <T> String Implode(String glue, Collection<T> c)
	{
		String product = null;
		for (T obj : c)
		{
			if (product == null)
			{
				product = obj.toString();
			}
			else
			{
				product += glue + obj.toString();
			}
		}
		return product;
	}
}


text:
require 'pathname'

Puppet::Type.newtype(:dsc_xspwebapplication) do
  require Pathname.new(__FILE__).dirname + '../../' + 'puppet/type/base_dsc'

  provide :powershell, :parent => Puppet::Type.type(:base_dsc).provider(:powershell) do
    defaultfor :operatingsystem => :windows
  end

  @doc = %q{
    The DSC xSPWebApplication resource type.
    Originally generated from the following schema.mof file:
      import/dsc_resources/xSharePoint/Modules/xSharePoint/DSCResources/MSFT_xSPWebApplication/MSFT_xSPWebApplication.schema.mof
  }

  validate do
      fail('dsc_name is a required attribute') if self[:dsc_name].nil?
    end

  newparam(:dscmeta_resource_friendly_name) do
    defaultto "xSPWebApplication"
  end

  newparam(:dscmeta_resource_name) do
    defaultto "MSFT_xSPWebApplication"
  end

  newparam(:dscmeta_import_resource) do
    newvalues(true, false)

    munge do |value|
      provider.munge_boolean(value.to_s)
    end

    defaultto true
  end

  newparam(:dscmeta_module_name) do
    defaultto "xSharePoint"
  end

  newparam(:dscmeta_module_version) do
    defaultto "0.3.1.0"
  end

  newparam(:name, :namevar => true ) do
  end

  ensurable do
    newvalue(:exists?) { provider.exists? }
    newvalue(:present) { provider.create }
    defaultto { :present }
  end

  # Name:         Name
  # Type:         string
  # IsMandatory:  True
  # Values:       None
  newparam(:dsc_name) do
    isrequired
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         ApplicationPool
  # Type:         string
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_applicationpool) do
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         ApplicationPoolAccount
  # Type:         string
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_applicationpoolaccount) do
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         Url
  # Type:         string
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_url) do
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         AllowAnonymous
  # Type:         boolean
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_allowanonymous) do
    validate do |value|
    end
    newvalues(true, false)
    munge do |value|
      provider.munge_boolean(value.to_s)
    end
  end

  # Name:         AuthenticationMethod
  # Type:         string
  # IsMandatory:  False
  # Values:       ["NTLM", "Kerberos"]
  newparam(:dsc_authenticationmethod) do
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
      unless ['NTLM', 'ntlm', 'Kerberos', 'kerberos'].include?(value)
        fail("Invalid value '#{value}'. Valid values are NTLM, Kerberos")
      end
    end
  end

  # Name:         DatabaseName
  # Type:         string
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_databasename) do
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         DatabaseServer
  # Type:         string
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_databaseserver) do
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         HostHeader
  # Type:         string
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_hostheader) do
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         Path
  # Type:         string
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_path) do
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         Port
  # Type:         string
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_port) do
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         InstallAccount
  # Type:         string
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_installaccount) do
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

end


text:
package org.github.sgoeschl.boon.extension.json;

import io.advantageous.boon.core.Lists;
import io.advantageous.boon.core.Predicate;
import io.advantageous.boon.primitive.CharBuf;

import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import static java.util.Arrays.asList;

/**
 * Pretty-print a Boon JSON map while filtering and sorting the entries.
 */
public final class FilteringJsonPrettyPrinter {

    private FilteringJsonPrettyPrinter() {}

    public static String print(Object object, String... skippedKeys) {
        return print(object, false, asList(skippedKeys));
    }

    public static String print(Object object, boolean sort) {
        return print(object, sort, new String[0]);
    }

    public static String print(Object object, boolean sort, String... skippedKeys) {
        return print(object, sort, asList(skippedKeys));
    }

    public static String print(Object object, boolean sort, Collection<String> skippedKeys) {
        return print(object, sort, new AcceptKeyPredicate(skippedKeys));
    }

    /**
     * Pretty-print the JSON object.
     *
     * @param object The JSON object to print
     * @param sort   Sort the JSON elements alphabetically or keep their natural order
     * @param filter Accept or skip JSON elements based on the key
     * @return the JSON string
     */
    private static String print(Object object, boolean sort, Predicate<String> filter) {
        final ModifyingCharBuf modifyingCharBuf = new ModifyingCharBuf(sort, filter);
        return modifyingCharBuf.prettyPrintObject(object, sort, 0).toString();
    }

    /**
     * Some ugly and intrusive hack using a lot of
     * internal knowledge to get it working.
     */
    private static class ModifyingCharBuf extends CharBuf {

        private final boolean sort;
        private final Predicate filter;

        private ModifyingCharBuf(boolean sort, Predicate filter) {
            this.sort = sort;
            this.filter = filter;
        }

        @Override
        public CharBuf prettyPrintMap(Map map) {
            return this.prettyPrintMap(map, 0);
        }

        @Override
        @SuppressWarnings("unchecked")
        public CharBuf prettyPrintMap(Map source, int indent) {

            if (source == null) {
                return null;
            }

            Map map = createMap(source, sort, filter);
            return super.prettyPrintMap(map, indent);
        }

        private Map createMap(Map<String, Object> map, boolean sort, Predicate<String> predicate) {

            final List<String> keys = Lists.filterBy(map.keySet(), predicate);
            final Map<String, Object> result = (sort ? new TreeMap<String, Object>() : new LinkedHashMap<String, Object>());

            for (String key : keys) {
                result.put(key, map.get(key));
            }

            return result;
        }
    }

    private static final class AcceptKeyPredicate implements Predicate<String> {

        private final Set<String> skippedKeys;

        public AcceptKeyPredicate(Collection<String> skippedKeys) {
            this.skippedKeys = new HashSet<>(skippedKeys);
        }

        @Override
        public boolean test(String input) {
            return input != null && !skippedKeys.contains(input);
        }
    }
}


text:
require 'active_support/concern'

# This class makes it possible to provide helper methods in a module that will
# be included inside the main Swift::Playground::CLI module.
#
# It's unfortunately a little magical, but its difficult to work around this
# due to the way the GLI dsl is not designed to use anywhere except at the top
# level (or at best, inside a module) and not in a class.
module Swift::Playground::CLI
  module Definition
    # Include ActiveSupport::Concern methods, so this module behaves like
    # ActiveSupport::Concern for any other module or class that extends it:
    include ActiveSupport::Concern

    def self.extended(mod)
      # Use the behaviour of the ActiveSupport::Concern modules `self.extended`
      # implementation:
      ActiveSupport::Concern.extended(mod)
    end

    def definition(&block)
      self.included do
        # The use of `extend(self)` here makes sure that a module that extends
        # the Definition module will have access to its methods from within
        # the GLI command actions it defines. It will define these commands
        # inside the block it passes to its call of the `definition` method.
        extend(self)
        self.class_eval(&block)
      end
    end
  end
end


text:
CREATE TABLE [dbo].[MonthlySales]
(
  [ID] INT NOT NULL PRIMARY KEY IDENTITY,
  [ShopID] INT NOT NULL,
  [SalesMonth] DATETIME NOT NULL,
  [Sales] DECIMAL NOT NULL
)