text:
describe('rate behaviours', function (){

    it('should be able to initialize', function (){
        var r = rate();
        expect(r).not.toBe(null);
    });

    it('should be able to calculate df acccording to time', function(){
        var r = rate(),
            t = 2.234;
            r.val = .02;
        expect(r.discount(t) <= 1).toBe(true);
    });

    it('Array should should be able to sum', function(){
        expect ([0.1, 0.2].sum()).toBe(0.3);
    });
});

describe ("basic requirements for optimizers", function (){

	it("should be able to the zero of a function", function f(){
		var optimise = optimisers.dichotomy,
		    cubic     = function cubic(x){
				return x*x*x - 1;
		    };
		var expected = 1,
		    lower = -13,
		    upper = 13,
		    target = 0,
		    precision = 0.0001,
		    result =  optimise(cubic, target, lower, upper);
		console.log("found result after "+ result.numberOfIterations + " iterations");
		console.log("the result is "+ result.res);

		expect(Math.abs(result.res- expected) < precision).toBe(true);
	});

    it("using optimisers to get a target value", function (){
        var optimise = optimisers.dichotomy,
            cubic = function(x) { return x*x*x - 1;},
            expected = 2,
            lower = -13,
            upper = 13,
            target = 7,
            precision = 0.0001,
            result = optimise(cubic, target, lower, upper);
        expect(Math.abs(result.res -expected) < precision).toBe(true);
    });

});

redpajama_set_name: RedPajamaGithub


text:
package Google::Ads::GoogleAds::V12::Services::BillingSetupService;

use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseService);

sub mutate {
  my $self         = shift;
  my $request_body = shift;
  my $http_method  = 'POST';
  my $request_path = 'v12/customers/{+customerId}/billingSetups:mutate';
  my $response_type =
'Google::Ads::GoogleAds::V12::Services::BillingSetupService::MutateBillingSetupResponse';

  return $self->SUPER::call($http_method, $request_path, $request_body,
    $response_type);
}

1;


text:
import csv
import traceback

import sys, os,traceback

def getLearningText(data,lang):

    transDict = {}
    f = open(os.path.join(os.getcwd(),'translations/learn_translations_text.csv'),'r')
    for line in f.readlines():
      text = line.split('|')
      if lang == 2:
        transDict[str(text[0])] = text[1]
      else:
        transDict[str(text[0])] = text[2]

    learningintro_txt = transDict['1']
    source_txt = transDict['7']+transDict['10']
    angexpln_txt = transDict['13']
    schgph_txt = transDict['14']

    data['learningintro_txt'] = learningintro_txt
    data['source_txt'] = source_txt
    data['angexpln_txt'] = angexpln_txt
    data['schgph_txt'] = schgph_txt

    schassess_txt = transDict['2'] + '' + str(data['sch_assess_bang_cnt']) + ''
    schassess_txt = schassess_txt + transDict['3'] + '' + str(data['sch_assess_cnt']) + ''
    schassess_txt = schassess_txt + transDict['11'] + '' + str(data['sch_assess_stucnt']) + ''
    data['schassess_txt'] = schassess_txt

    angassess_intro_txt = transDict['4']
    angassess_txt = transDict['5'] + '' + str(data['ang_assess_bang_cnt']) + ''
    angassess_txt = angassess_txt + transDict['6'] + '' + str(data['ang_assess_cnt']) + ''
    angassess_txt = angassess_txt + transDict['12'] + '' + str(data['ang_assess_stucnt']) + ''

    data['angassess_txt'] = angassess_intro_txt
    data['angassessmore_txt'] = angassess_txt

    return data

def formatIndian(inputNum) :
  prefStr = ''
  outputString = ''
  minus = ''
  suf = ''
  lastThree = ''
  try:
    inputString = str(inputNum)
    if '.' in inputString:
      numberArray = inputString.split('.', 2)
      pref = int(numberArray[0])
      suf = numberArray[1]
    else:
      pref = inputString
      suf = ''
    outputString = ''
    minus = ''
    if pref < 0:
      minus = '-'
    prefStr = str(pref)
    if len(prefStr) > 3 :
      lastThree = prefStr[len(prefStr)-3: len(prefStr)]
      prefStr = prefStr[0: len(prefStr)-3]
    if len(prefStr) % 2 > 0 :
      outputString = outputString + prefStr[0:1] + ','
      prefStr = prefStr[1: len(prefStr)]

    while (len(prefStr) >= 2) :
      outputString = outputString +  prefStr[0:2] + ','
      prefStr = prefStr[2:len(prefStr)]

    outputString = minus + outputString +  lastThree + suf
    return outputString
  except:
    print 'Error occurred'
    print "Unexpected error:", sys.exc_info()
    traceback.print_exc(file=sys.stdout)
    return 'NaN'


text:
<?php

namespace Draggy\Autocode\Templates;

interface TemplateInterface
{
    public function setIndentation($indentation);

    public function getIndentation();

    public function setIndentationCount($indentationCount);

    public function getIndentationCount();

    public function setEol($eol);

    public function getEol();

    public function __toString();

    public function setTemplate(TemplateInterface $template);

    public function getTemplate();

    public function getIndentationPrefix($times = 1);

    public function convertLinesToCode(array $lines);

    public function getBlurbLines();

    public function getBlurb();

    public function getHashBlurbLines();

    public function getHashBlurb();
}


text:
const gulp = require('gulp');
var bower = require('gulp-bower');
var changed = require('gulp-changed');
var htmlmin = require('gulp-htmlmin');
var imagemin = require('gulp-imagemin');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var minify = require('gulp-minify-css');

gulp.task('js', function(){
   gulp.src('src/scripts/*.js')
   .pipe(concat('main.js'))
   .pipe(uglify())
   .pipe(gulp.dest('dist/js/'));
});

gulp.task('css', function(){
   gulp.src('src/css/*.css')
   .pipe(concat('main.css'))
   .pipe(minify())
   .pipe(gulp.dest('dist/css/'));
});

gulp.task('imagemin', function() {
   var imgSrc = 'src/img/*.+(png|jpg|gif)',
   imgDst = 'dist/img';

   gulp.src(imgSrc)
   .pipe(changed(imgDst))
   .pipe(imagemin())
   .pipe(gulp.dest(imgDst));
});

gulp.task('htmlmin', function() {
  return gulp.src('src/*.html')
    .pipe(htmlmin({collapseWhitespace: true}))
    .pipe(gulp.dest('dist/'));
});

gulp.task('copyfonts', function() {
   gulp.src('bower_components/materialize/dist/fonts/roboto/*.{woff2,eot,ttf,woff,eof,svg}')
   .pipe(gulp.dest('dist/fonts'));
});

gulp.task('copymisc', function() {
   gulp.src('src/*.{png,xml,ico,txt}')
   .pipe(gulp.dest('dist/'));
});

gulp.task('bower', function() {
  return bower();
});

gulp.task('default',['bower','js','css','imagemin','htmlmin','copyfonts','copymisc'],function(){
});


text:
/*
* Alert Message
* (C) 2004-2006,2011,2012 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#ifndef BOTAN_TLS_ALERT_H_
#define BOTAN_TLS_ALERT_H_

#include <botan/secmem.h>
#include <string>

namespace Botan {

namespace TLS {

/**
* SSL/TLS Alert Message
*/
class BOTAN_PUBLIC_API(2,0) Alert final
   {
   public:
      /**
      * Type codes for TLS alerts
      */
      enum Type {
         CLOSE_NOTIFY                    = 0,
         UNEXPECTED_MESSAGE              = 10,
         BAD_RECORD_MAC                  = 20,
         DECRYPTION_FAILED               = 21,
         RECORD_OVERFLOW                 = 22,
         DECOMPRESSION_FAILURE           = 30,
         HANDSHAKE_FAILURE               = 40,
         NO_CERTIFICATE                  = 41, // SSLv3 only
         BAD_CERTIFICATE                 = 42,
         UNSUPPORTED_CERTIFICATE         = 43,
         CERTIFICATE_REVOKED             = 44,
         CERTIFICATE_EXPIRED             = 45,
         CERTIFICATE_UNKNOWN             = 46,
         ILLEGAL_PARAMETER               = 47,
         UNKNOWN_CA                      = 48,
         ACCESS_DENIED                   = 49,
         DECODE_ERROR                    = 50,
         DECRYPT_ERROR                   = 51,
         EXPORT_RESTRICTION              = 60,
         PROTOCOL_VERSION                = 70,
         INSUFFICIENT_SECURITY           = 71,
         INTERNAL_ERROR                  = 80,
         INAPPROPRIATE_FALLBACK          = 86,
         USER_CANCELED                   = 90,
         NO_RENEGOTIATION                = 100,
         MISSING_EXTENSION               = 109, // RFC 8446
         UNSUPPORTED_EXTENSION           = 110,
         CERTIFICATE_UNOBTAINABLE        = 111,
         UNRECOGNIZED_NAME               = 112,
         BAD_CERTIFICATE_STATUS_RESPONSE = 113,
         BAD_CERTIFICATE_HASH_VALUE      = 114,
         UNKNOWN_PSK_IDENTITY            = 115,
         CERTIFICATE_REQUIRED            = 116, // RFC 8446

         NO_APPLICATION_PROTOCOL         = 120, // RFC 7301

         // pseudo alert values
         NULL_ALERT                      = 256
      };

      /**
      * @return true iff this alert is non-empty
      */
      bool is_valid() const { return (m_type_code != NULL_ALERT); }

      /**
      * @return if this alert is a fatal one or not
      *
      * Note:
      *    RFC 8446 6.
      *       In TLS 1.3, the severity is implicit in the type of alert being sent,
      *       and the "level" field can safely be ignored.
      *    Everything is considered fatal except for USER_CANCELED and CLOSE_NOTIFY (RFC 8446 6.1)
      */
      bool is_fatal() const { return m_fatal; }

      /**
      * @return type of alert
      */
      Type type() const { return m_type_code; }

      /**
      * @return type of alert
      */
      std::string type_string() const;

      /**
      * Serialize an alert
      */
      std::vector<uint8_t> serialize() const;

      /**
      * Deserialize an Alert message
      * @param buf the serialized alert
      */
      explicit Alert(const secure_vector<uint8_t>& buf);

      /**
      * Create a new Alert
      * @param type_code the type of alert
      * @param fatal specifies if this is a fatal alert
      */
      Alert(Type type_code, bool fatal = false) :
         m_fatal(fatal), m_type_code(type_code) {}

      Alert() : m_fatal(false), m_type_code(NULL_ALERT) {}
   private:
      bool m_fatal;
      Type m_type_code;
   };

}

}

#endif


text:
Front end (in progress) for Visitor app uses JSX, React Router, Browserify and SASS.

The idea for the app is to have a simple way to keep track of fun things as you do them so that when you are looking for inspiration or someone is visiting you, you already have a personalized and curated list of things to do with them. Save activities to different people's lists, see them on a map, etc.

### Usage

- `npm install`
- `npm start`

### License

MIT


text:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class ResultSearch
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()>
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()>
    Private Sub InitializeComponent()
        Me.Label1 = New System.Windows.Forms.Label()
        Me.Label2 = New System.Windows.Forms.Label()
        Me.Label3 = New System.Windows.Forms.Label()
        Me.Label4 = New System.Windows.Forms.Label()
        Me.ComboBox1 = New System.Windows.Forms.ComboBox()
        Me.TextBox1 = New System.Windows.Forms.TextBox()
        Me.Button1 = New System.Windows.Forms.Button()
        Me.Button2 = New System.Windows.Forms.Button()
        Me.Label6 = New System.Windows.Forms.Label()
        Me.Label5 = New System.Windows.Forms.Label()
        Me.ComboBox2 = New System.Windows.Forms.ComboBox()
        Me.ComboBox3 = New System.Windows.Forms.ComboBox()
        Me.ComboBox4 = New System.Windows.Forms.ComboBox()
        Me.ListBox1 = New System.Windows.Forms.ListBox()
        Me.FlowLayoutPanel1 = New System.Windows.Forms.FlowLayoutPanel()
        Me.SuspendLayout()
        '
        'Label1
        '
        Me.Label1.AutoSize = True
        Me.Label1.Location = New System.Drawing.Point(129, 22)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(94, 13)
        Me.Label1.TabIndex = 0
        Me.Label1.Text = "Search for Results"
        '
        'Label2
        '
        Me.Label2.AutoSize = True
        Me.Label2.Location = New System.Drawing.Point(318, 170)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(74, 13)
        Me.Label2.TabIndex = 1
        Me.Label2.Text = "Recent Meets"
        '
        'Label3
        '
        Me.Label3.AutoSize = True
        Me.Label3.Location = New System.Drawing.Point(339, 115)
        Me.Label3.Name = "Label3"
        Me.Label3.Size = New System.Drawing.Size(23, 13)
        Me.Label3.TabIndex = 2
        Me.Label3.Text = "OR"
        '
        'Label4
        '
        Me.Label4.AutoSize = True
        Me.Label4.Location = New System.Drawing.Point(121, 51)
        Me.Label4.Name = "Label4"
        Me.Label4.Size = New System.Drawing.Size(74, 13)
        Me.Label4.TabIndex = 3
        Me.Label4.Text = "Name of Meet"
        '
        'ComboBox1
        '
        Me.ComboBox1.FormattingEnabled = True
        Me.ComboBox1.Location = New System.Drawing.Point(196, 202)
        Me.ComboBox1.Name = "ComboBox1"
        Me.ComboBox1.Size = New System.Drawing.Size(304, 21)
        Me.ComboBox1.TabIndex = 6
        '
        'TextBox1
        '
        Me.TextBox1.Location = New System.Drawing.Point(42, 67)
        Me.TextBox1.Name = "TextBox1"
        Me.TextBox1.Size = New System.Drawing.Size(235, 20)
        Me.TextBox1.TabIndex = 7
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(317, 253)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(75, 23)
        Me.Button1.TabIndex = 8
        Me.Button1.Text = "Search"
        Me.Button1.UseVisualStyleBackColor = True
        '
        'Button2
        '
        Me.Button2.Location = New System.Drawing.Point(317, 70)
        Me.Button2.Name = "Button2"
        Me.Button2.Size = New System.Drawing.Size(75, 23)
        Me.Button2.TabIndex = 9
        Me.Button2.Text = "Search"
        Me.Button2.UseVisualStyleBackColor = True
        '
        'Label6
        '
        Me.Label6.AutoSize = True
        Me.Label6.Location = New System.Drawing.Point(318, 51)
        Me.Label6.Name = "Label6"
        Me.Label6.Size = New System.Drawing.Size(57, 13)
        Me.Label6.TabIndex = 10
        Me.Label6.Text = "AND / OR"
        '
        'Label5
        '
        Me.Label5.AutoSize = True
        Me.Label5.Location = New System.Drawing.Point(499, 51)
        Me.Label5.Name = "Label5"
        Me.Label5.Size = New System.Drawing.Size(69, 13)
        Me.Label5.TabIndex = 4
        Me.Label5.Text = "Date of Meet"
        '
        'ComboBox2
        '
        Me.ComboBox2.FormattingEnabled = True
        Me.ComboBox2.Location = New System.Drawing.Point(417, 70)
        Me.ComboBox2.Name = "ComboBox2"
        Me.ComboBox2.Size = New System.Drawing.Size(50, 21)
        Me.ComboBox2.TabIndex = 11
        '
        'ComboBox3
        '
        Me.ComboBox3.FormattingEnabled = True
        Me.ComboBox3.Location = New System.Drawing.Point(473, 70)
        Me.ComboBox3.Name = "ComboBox3"
        Me.ComboBox3.Size = New System.Drawing.Size(117, 21)
        Me.ComboBox3.TabIndex = 12
        '
        'ComboBox4
        '
        Me.ComboBox4.FormattingEnabled = True
        Me.ComboBox4.Location = New System.Drawing.Point(596, 70)
        Me.ComboBox4.Name = "ComboBox4"
        Me.ComboBox4.Size = New System.Drawing.Size(59, 21)
        Me.ComboBox4.TabIndex = 13
        '
        'ListBox1
        '
        Me.ListBox1.FormattingEnabled = True
        Me.ListBox1.Location = New System.Drawing.Point(144, 315)
        Me.ListBox1.Name = "ListBox1"
        Me.ListBox1.Size = New System.Drawing.Size(299, 95)
        Me.ListBox1.TabIndex = 14
        '
        'FlowLayoutPanel1
        '
        Me.FlowLayoutPanel1.Location = New System.Drawing.Point(473, 310)
        Me.FlowLayoutPanel1.Name = "FlowLayoutPanel1"
        Me.FlowLayoutPanel1.Size = New System.Drawing.Size(200, 100)
        Me.FlowLayoutPanel1.TabIndex = 15
        '
        'ResultSearch
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(708, 469)
        Me.Controls.Add(Me.FlowLayoutPanel1)
        Me.Controls.Add(Me.ListBox1)
        Me.Controls.Add(Me.ComboBox4)
        Me.Controls.Add(Me.ComboBox3)
        Me.Controls.Add(Me.ComboBox2)
        Me.Controls.Add(Me.Label6)
        Me.Controls.Add(Me.Button2)
        Me.Controls.Add(Me.Button1)
        Me.Controls.Add(Me.TextBox1)
        Me.Controls.Add(Me.ComboBox1)
        Me.Controls.Add(Me.Label5)
        Me.Controls.Add(Me.Label4)
        Me.Controls.Add(Me.Label3)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.Label1)
        Me.Name = "ResultSearch"
        Me.Text = "ResultSearch"
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub

    Friend WithEvents Label1 As Label
    Friend WithEvents Label2 As Label
    Friend WithEvents Label3 As Label
    Friend WithEvents Label4 As Label
    Friend WithEvents ComboBox1 As ComboBox
    Friend WithEvents TextBox1 As TextBox
    Friend WithEvents Button1 As Button
    Friend WithEvents Button2 As Button
    Friend WithEvents ComboBox3 As ComboBox
    Friend WithEvents ComboBox4 As ComboBox
    Friend WithEvents ComboBox2 As ComboBox
    Friend WithEvents Label5 As Label
    Friend WithEvents Label6 As Label
    Friend WithEvents ListBox1 As ListBox
    Friend WithEvents FlowLayoutPanel1 As FlowLayoutPanel
End Class


text:
# svmjs
Andrej Karpathy
July 2012

svmjs is a lightweight implementation of the SMO algorithm to train a binary
Support Vector Machine. As this uses the dual formulation, it also supports
arbitrary kernels. Correctness test, together with MATLAB reference code
are in /test.

## Online GUI demo

Can be found here: http://cs.stanford.edu/~karpathy/svmjs/demo/

Corresponding code is inside /demo directory.

## Usage

The simplest use case:
```javascript
// include the library
<script src="./svmjs/lib/svm.js"></script>
<script>
svm = svmjs.SVM();
svm.train(data, labels);
testlabels = svm.predict(testdata);
</script>
```
Here, `data` and `testdata` are a 2D, NxD array of floats, `labels` and `testlabels`
is an array of size N that contains 1 or -1. You can also query for the raw margins:
```javascript
margins = svm.margins(testdata);
margin = svm.marginOne(testadata[0]);
```

The library supports arbitrary kernels, but currently comes with linear and rbf kernel:
```javascript
svm.train(data, labels, { kernel: function(v1,v2){ /* return K(v1, v2) */} }); // arbitrary function
svm.train(data, labels, { kernel: svmjs.linearKernel });
svm.train(data, labels, { kernel: svmjs.makeRbfKernel(0.5) }); // sigma = 0.5
```

For linear kernels, you can also query the weights and offset directly:
```javascript
wb= svm.getWeights();
//wb.w is array of weights and wb.b is the bias term
```

For training you can pass in several options. Here are the defaults:
```javascript
var options = {};
/* For C, Higher = you trust your data more. Lower = more regularization.
Should be in range of around 1e-2 ... 1e5 at most. */
options.C = 1.0;
options.tol = 1e-4; // do not touch this unless you're pro
options.maxiter = 10000; // if you have a larger problem, you may need to increase this
options.kernel = svmjs.linearKernel; // discussed above
options.numpasses = 10; // increase this for higher precision of the result. (but slower)
svm.train(data, labels, options);
```

## Implementation details
The SMO algorithm is very space efficient, so you need not worry about
running out of space no matter how large your problem is. However, you do need to
worry about runtime efficiency. In practice, there are many heuristics one can
use to select the pair of alphas (i,j) to optimize and this uses a rather naive
approach. If you have a large and complex problem, you will need to increase
maxiter a lot. (or don't use Javascript!)

If you intend to use only linear SVM and are worried about efficiency, I recommend
you train it, get the weights out with getWeights(), and use them directly in
your code from then on.

## License
MIT


text:
package ari

import "context"

// ChannelContextOptions describes the set of options to be used when creating a channel-bound context.
type ChannelContextOptions struct {
	ctx    context.Context
	cancel context.CancelFunc

	hangupOnEnd bool

	sub Subscription
}

// ChannelContextOptionFunc describes a function which modifies channel context options.
type ChannelContextOptionFunc func(o *ChannelContextOptions)

// ChannelContext returns a context which is closed when the provided channel leaves the ARI application or the parent context is closed.  The parent context is optional, and if it is `nil`, a new background context will be created.
func ChannelContext(h *ChannelHandle, opts ...ChannelContextOptionFunc) (context.Context, context.CancelFunc) {
	o := new(ChannelContextOptions)

	for _, opt := range opts {
		opt(o)
	}

	if o.ctx == nil {
		o.ctx, o.cancel = context.WithCancel(context.Background())
	}

	if o.sub == nil {
		o.sub = h.Subscribe(Events.StasisEnd)
	}

	go func() {
		defer o.cancel()

		select {
		case <-o.ctx.Done():
		case <-o.sub.Events():
		}

		if o.hangupOnEnd {
			h.Hangup() // nolint
		}
	}()

	return o.ctx, o.cancel
}

// WithParentContext requests that the generated channel context be created from the given parent context.
func WithParentContext(parent context.Context) ChannelContextOptionFunc {
	return func(o *ChannelContextOptions) {
		if parent != nil {
			o.ctx, o.cancel = context.WithCancel(parent)
		}
	}
}

// HangupOnEnd indicates that the channel should be terminated when the channel context is terminated.  Note that this also provides an easy way to create a time scope on a channel by putting a deadline on the parent context.
func HangupOnEnd() ChannelContextOptionFunc {
	return func(o *ChannelContextOptions) {
		o.hangupOnEnd = true
	}
}


text:
from __future__ import unicode_literals

from .common import InfoExtractor
from .jwplatform import JWPlatformIE

from ..utils import (
    unified_strdate,
)

class NormalbootsIE(InfoExtractor):
    _VALID_URL = r'https?://(?:www\.)?normalboots\.com/video/(?P<id>[0-9a-z-]*)/?$'
    _TEST = {
        'url': 'http://normalboots.com/video/home-alone-games-jontron/',
        'info_dict': {
            'id': 'home-alone-games-jontron',
            'ext': 'mp4',
            'title': 'Home Alone Games - JonTron - NormalBoots',
            'description': 'Jon is late for Christmas. Typical. Thanks to: Paul Ritchey for Co-Writing/Filming: http://www.youtube.com/user/ContinueShow Michael Azzi for Christmas Intro Animation: http://michafrar.tumblr.com/ Jerrod Waters for Christmas Intro Music: http://www.youtube.com/user/xXJerryTerryXx Casey Ormond for 'Tense Battle Theme':\xa0http://www.youtube.com/Kiamet/',
            'uploader': 'JonTron',
            'upload_date': '20140125',
        },
        'params': {
            # m3u8 download
            'skip_download': True,
        },
        'add_ie': ['JWPlatform'],
    }

    def _real_extract(self, url):
        video_id = self._match_id(url)
        webpage = self._download_webpage(url, video_id)

        video_uploader = self._html_search_regex(
            r'Posted\sby\s(?P<uploader>[A-Za-z]*)\s',
            webpage, 'uploader', fatal=False)
        video_upload_date = unified_strdate(self._html_search_regex(
            r'[A-Za-z]+, (?P<date>.*)',
            webpage, 'date', fatal=False))

        jwplatform_url = JWPlatformIE._extract_url(webpage)

        return {
            '_type': 'url_transparent',
            'id': video_id,
            'url': jwplatform_url,
            'ie_key': JWPlatformIE.ie_key(),
            'title': self._og_search_title(webpage),
            'description': self._og_search_description(webpage),
            'thumbnail': self._og_search_thumbnail(webpage),
            'uploader': video_uploader,
            'upload_date': video_upload_date,
        }


text:
package net.canadensys.dataportal.occurrence.search.parameter.parser;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.canadensys.dataportal.occurrence.search.config.SearchServiceConfig;
import net.canadensys.query.QueryOperatorEnum;
import net.canadensys.query.SearchQueryPart;
import net.canadensys.query.interpreter.InsidePolygonFieldInterpreter;
import net.canadensys.utils.NumberUtils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.log4j.Logger;

/**
 * This class is responsible to create a collection of SearchQueryPart based on
 * URL parameters. This class is designed for Occurrence Portal search.
 *
 * @author canadensys
 *
 */
public class SearchParamParser {
	// get log4j handler
	private static final Logger LOGGER = Logger
			.getLogger(SearchParamParser.class);

	// Pattern to roughly extract values from a QueryPart value
	private static final Pattern SEARCH_PARAM_PATTERN = Pattern
			.compile("^(\\d+)(_f|_o|_v(_\\d+)*)$");
	private static final Pattern DATE_VALUE_PATTERN = Pattern
			.compile("^([0-9]{0,4})-([0-9]{0,2})-([0-9]{0,2})$");
	private static final Pattern GEO_COORDINATES_PARAM_PATTERN = Pattern
			.compile("^([-+]?[0-9]*\\.?[0-9]+),([-+]?[0-9]*\\.?[0-9]+)$");

	private static final int GROUP_POS = 0;
	private static final int PARAM_TYPE_POS = 1;
	private static final int VAL_NUMBER_POS = 2;

	private static final String PARAM_TYPE_FIELD = "f";
	private static final String PARAM_TYPE_OPERATOR = "o";
	private static final String PARAM_TYPE_VALUE = "v";

	private SearchServiceConfig searchConfig;

	/**
	 * You should not use this function directly, look at SearchParamHandler.
	 * Main parsing function to convert Map<String,String> into
	 * Collection<SearchQueryPart>. The order of SearchQueryPart into the list
	 * will be kept according to the groupId. This function will skip additional
	 * parameters if they don't contain the underscore character. TODO : use a
	 * Regex
	 *
	 * @param parametersMap
	 * @return
	 */
	public Collection<SearchQueryPart> parse(Map<String, String[]> parametersMap) {
		// we use a TreeMap to keep the SearchQueryPart ordered by groupId
		Map<Integer, SearchQueryPart> groupNumberQueryPartMap = new TreeMap<Integer, SearchQueryPart>();

		String[] splittedParam;

		String groupId;
		Integer groupIdInt;
		String paramType;
		String valueNumber;
		SearchQueryPart queryPart;
		String parameterValue;

		for (String currParameterKey : parametersMap.keySet()) {
			splittedParam = currParameterKey.split("_");
			// we do not support multiple value per key
			parameterValue = parametersMap.get(currParameterKey)[0];

			if (splittedParam.length >= 2) {
				// we use groupId to regroup all related parameters
				groupId = splittedParam[GROUP_POS];
				paramType = splittedParam[PARAM_TYPE_POS];

				if (StringUtils.isNumeric(groupId)) {
					groupIdInt = Integer.parseInt(groupId);
					queryPart = groupNumberQueryPartMap.get(groupIdInt);
					if (queryPart == null) {
						// eventually, we could defined the type of
						// SearchQueryPart based on the fieldId
						queryPart = new SearchQueryPart();
						groupNumberQueryPartMap.put(groupIdInt, queryPart);
					}

					if (paramType.equalsIgnoreCase(PARAM_TYPE_FIELD)) {
						if (StringUtils.isNumeric(parameterValue)) {
							queryPart.setSearchableField(searchConfig
									.getSearchableFieldbyId(Integer
											.valueOf(parameterValue)));
						} else {// we put the parameterValue inside the field
								// but after?
							queryPart.setSearchableField(searchConfig
									.getSearchableFieldbyName(parameterValue));
						}
					} else if (paramType.equalsIgnoreCase(PARAM_TYPE_OPERATOR)) {
						// http://prideafrica.blogspot.com/2007/01/javalangclasscastexception.html
						queryPart.setOp(QueryOperatorEnum
								.fromString(parameterValue));
					} else if (paramType.equalsIgnoreCase(PARAM_TYPE_VALUE)) {
						if (splittedParam.length == 3) {
							valueNumber = splittedParam[VAL_NUMBER_POS];
							if (StringUtils.isNumeric(valueNumber)) {
								queryPart.addValue(parameterValue,
										Integer.valueOf(valueNumber));
							}
						} else {
							queryPart.addValue(parameterValue);
						}
					}
				}
			}
		}
		return parseValues(new ArrayList<SearchQueryPart>(
				groupNumberQueryPartMap.values()));
	}

	/**
	 * Inverse function of parse(Map<String,String[]> Takes SearchQueryPart
	 * collection and turn it back to Map<String,String> so it can be used as
	 * query string. The main usage is when some SearchQueryPart are added
	 * dynamically and we need to adjust the query string.
	 *
	 * @param searchQueryParts
	 * @return
	 */
	public Map<String, String> toQueryStringMap(
			Collection<SearchQueryPart> searchQueryParts) {
		Map<String, String> queryString = new TreeMap<String, String>();
		int currField = 1;
		int currFieldValue = 1;
		for (SearchQueryPart sqp : searchQueryParts) {
			queryString.put(currField + "_" + PARAM_TYPE_FIELD, Integer
					.toString(sqp.getSearchableField().getSearchableFieldId()));
			queryString.put(currField + "_" + PARAM_TYPE_OPERATOR, sqp.getOp()
					.toString().toLowerCase());
			currFieldValue = 1;
			for (String sqpValue : sqp.getValueList()) {
				queryString.put(currField + "_" + PARAM_TYPE_VALUE + "_"
						+ currFieldValue, sqpValue);
				currFieldValue++;
			}
			currField++;
		}
		return queryString;
	}

	/**
	 * Parses values according to special rules in the OccurrencePortal. This
	 * need to be done after the regular parsing because we accept query part in
	 * different order. Each SearchableFieldType is handle differently according
	 * to the proper Interpreter.
	 *
	 * @param searchQueryPartList
	 * @return
	 */
	private Collection<SearchQueryPart> parseValues(
			Collection<SearchQueryPart> searchQueryPartList) {
		for (SearchQueryPart currSearchQueryPart : searchQueryPartList) {
			// validation is not done yet, be careful
			if (currSearchQueryPart.getSearchableField() != null) {
				switch (currSearchQueryPart.getSearchableField()
						.getSearchableFieldTypeEnum()) {
				case SINGLE_VALUE:
					parseSingleValue(currSearchQueryPart);
					break;
				case MIN_MAX_NUMBER:
					parseMinMaxNumber(currSearchQueryPart);
					break;
				case START_END_DATE:
					parseStartEndDate(currSearchQueryPart);
					break;
				case INSIDE_ENVELOPE_GEO:
					parseInsidePolygon(currSearchQueryPart);
					break;
				case INSIDE_POLYGON_GEO:
					parseInsidePolygon(currSearchQueryPart);
					break;
				case WITHIN_RADIUS_GEO:
					parseWithinRadius(currSearchQueryPart);
					break;
				default:
					LOGGER.error("Unknown SearchableFieldTypeEnum value");
				}
			}
		}
		return searchQueryPartList;
	}

	public void setSearchConfig(SearchServiceConfig searchConfig) {
		this.searchConfig = searchConfig;
	}

	/**
	 * Tests if the parameter is a search parameter.
	 *
	 * @param value
	 * @return
	 */
	public static boolean isSearchParam(String param) {
		return SEARCH_PARAM_PATTERN.matcher(param).find();
	}

	/**
	 * Parse the value of the currSearchQueryPart into the proper type.
	 *
	 * @param currSearchQueryPart
	 */
	protected void parseSingleValue(SearchQueryPart currSearchQueryPart) {
		if (String.class.equals(currSearchQueryPart.getSearchableField()
				.getType())) {
			currSearchQueryPart.addParsedValue(
					currSearchQueryPart.getSingleValue(),
					currSearchQueryPart.getSingleField(),
					currSearchQueryPart.getSingleValue());
		} else if (Number.class.isAssignableFrom(currSearchQueryPart
				.getSearchableField().getType())) {
			currSearchQueryPart
					.addParsedValue(currSearchQueryPart.getSingleValue(),
							currSearchQueryPart.getSingleField(), NumberUtils
									.parseNumber(currSearchQueryPart
											.getSingleValue(),
											currSearchQueryPart
													.getSearchableField()
													.getType()));
		} else if (Boolean.class.equals(currSearchQueryPart
				.getSearchableField().getType())) {
			currSearchQueryPart.addParsedValue(
					currSearchQueryPart.getSingleValue(),
					currSearchQueryPart.getSingleField(),
					Boolean.parseBoolean(currSearchQueryPart.getSingleValue()));
		} else {
			LOGGER.error("Couldn't parse values["
					+ currSearchQueryPart.getValueList()
					+ "] into a valid single value query. QueryPart dropped.");
		}
	}

	protected void parseMinMaxNumber(SearchQueryPart currSearchQueryPart) {
		List<String> valueList = currSearchQueryPart.getValueList();
		List<String> fieldList = currSearchQueryPart.getFieldList();
		// if only 1 value is provided, set min and max as the same value
		if (valueList.size() == 1) {
			currSearchQueryPart.addParsedValue(valueList.get(0), fieldList
					.get(0), NumberUtils.parseNumber(valueList.get(0),
					currSearchQueryPart.getSearchableField().getType()));
			currSearchQueryPart.addParsedValue(valueList.get(0), fieldList
					.get(1), NumberUtils.parseNumber(valueList.get(0),
					currSearchQueryPart.getSearchableField().getType()));
		} else if (valueList.size() == 2) {
			currSearchQueryPart.addParsedValue(valueList.get(0), fieldList
					.get(0), NumberUtils.parseNumber(valueList.get(0),
					currSearchQueryPart.getSearchableField().getType()));
			currSearchQueryPart.addParsedValue(valueList.get(1), fieldList
					.get(1), NumberUtils.parseNumber(valueList.get(1),
					currSearchQueryPart.getSearchableField().getType()));
		} else {
			currSearchQueryPart.clearValues();
			LOGGER.error("Couldn't parse values["
					+ currSearchQueryPart.getValueList()
					+ "] into a valid min/max number query. QueryPart dropped.");
		}
	}

	protected void parseStartEndDate(SearchQueryPart currSearchQueryPart) {
		// Composed date are received as 2009-05-27 but the Interpreter wants
		// this as separated values
		List<String> valueList = currSearchQueryPart.getValueList();
		// try to parse all values, if one is not valid discard them all
		for (int i = 0; i < valueList.size(); i++) {
			String value = valueList.get(i);
			Matcher m = DATE_VALUE_PATTERN.matcher(value);
			if (m.find()) {
				currSearchQueryPart.addParsedValue(value,
						SearchServiceConfig.START_YEAR_PROPERTY,
						NumberUtils.parseNumber(m.group(1), Integer.class)); // year
				currSearchQueryPart.addParsedValue(value,
						SearchServiceConfig.START_MONTH_PROPERTY,
						NumberUtils.parseNumber(m.group(2), Integer.class)); // month
				currSearchQueryPart.addParsedValue(value,
						SearchServiceConfig.START_DAY_PROPERTY,
						NumberUtils.parseNumber(m.group(3), Integer.class)); // day
			} else {// simply clear the value to make this query part invalid
				currSearchQueryPart.clearValues();
				LOGGER.error("Couldn't parse value[" + value
						+ "] into a valid date query. QueryPart dropped.");
			}
		}
	}

	protected void parseInsidePolygon(SearchQueryPart currSearchQueryPart) {
		// Geo coordinates are received as -125.3,34.88 but the Interpreter
		// wants this in a Pair object
		List<String> valueList = currSearchQueryPart.getValueList();
		String relatedField = currSearchQueryPart.getSearchableField()
				.getRelatedFields()
				.get(InsidePolygonFieldInterpreter.GEOM_FIELD_IDX);
		for (int i = 0; i < valueList.size(); i++) {
			String value = valueList.get(i);
			Matcher m = GEO_COORDINATES_PARAM_PATTERN.matcher(value);
			if (m.find()) {
				currSearchQueryPart.addParsedValue(value, relatedField,
						Pair.of(m.group(1), m.group(2))); // lat,long
			} else {// simply clear the value to make this query part invalid
				currSearchQueryPart.clearValues();
				LOGGER.error("Couldn't parse value[" + value
						+ "] into a valid polygon query. QueryPart dropped.");
			}
		}
	}

	protected void parseWithinRadius(SearchQueryPart currSearchQueryPart) {
		List<String> valueList = currSearchQueryPart.getValueList();
		boolean parsed = true;

		// parse coordinates, Interpreter wants this in a Pair object
		String value = valueList.get(0);
		Matcher m = GEO_COORDINATES_PARAM_PATTERN.matcher(value);
		if (m.find()) {
			currSearchQueryPart.addParsedValue(value, currSearchQueryPart
					.getSearchableField().getRelatedField(), Pair.of(
					m.group(1), m.group(2))); // lat,long
		} else {
			parsed = false;
		}

		// parse radius
		value = valueList.get(1);
		try {
			currSearchQueryPart.addParsedValue(value, currSearchQueryPart
					.getSearchableField().getRelatedField(),
					Double.valueOf(value).intValue());
		} catch (NumberFormatException e) {
			parsed = false;
		}

		if (!parsed) {
			// simply clear the value to make this query part invalid
			currSearchQueryPart.clearValues();
			LOGGER.error("Couldn't parse value[" + value
					+ "] into a valid within radius query. QueryPart dropped.");
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You 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.
-->
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">

    <bean id="pojoA" class="org.apache.aries.blueprint.pojos.PojoA" depends-on=" pojoB  pojoC ">
        <argument value="val0"/>
        <argument ref="val1" />
        <argument>
            <description>null value</description>
            <null/>
        </argument>
        <argument type="java.lang.String">
            <value>val3</value>
        </argument>
        <argument>
            <array>
                <value>val0</value>
                <bean class="java.lang.String"/>
                <null/>
            </array>
        </argument>
        <argument>
            <ref component-id="pojoB"/>
        </argument>
        <property name="prop1" ref="pojoB"/>
        <property name="prop2" value="value" />
        <property name="prop3">
            <description>property</description>
            <value>val</value>
        </property>
    </bean>

    <bean id="pojoB" class="org.apache.aries.blueprint.pojos.PojoA" init-method="initPojo" >
        <argument index = "1" value="val0"/>
        <argument index = "0" ref="val1" />
    </bean>

</blueprint>


text:
package tutorial.checkbox_demo;

public class Test {

  final static String tag = Test.class.getPackage().getName();

  public static void main(String[] args) {
    System.out.println(tag);
    CheckBoxDemo.main();
  }

}


text:
<?php

namespace Laravel\Settings\DriverAssets\Database;

class SettingsRepository {

    protected $model;

    public function __construct(Setting $model) {
        $this->model = $model;
    }

    /**
     * Get all settings .
     *
     * @param null $group
     * @return mixed
     */
    public function all($group = null) {
        if(! is_null($group))
            return $this->model->where('group', $group)->lists('value', 'key');

        return $this->model->lists('value', 'key');
    }

    /**
     * Get by key .
     *
     * @param $key
     * @param null $group
     * @return mixed
     */
    public function getByKey($key, $group = null) {
        $query =  $this->model
            ->where('key', $key);

        if(! is_null($group))
            $query->where('group', $group);

        return $query->get();
    }

    /**
     * Get by group .
     *
     * @param $group
     * @return mixed
     */
    public function getByGroup($group) {
        return $this->model
            ->where('group', $group)
            ->get();
    }

    /**
     * Delete setting by key .
     *
     * @param $key
     * @param null $group
     * @return $this
     */
    public function deleteByKey($key, $group = null) {
        $query = $this->model
            ->where('key', $key);

        if(! is_null($group))
            $query->where('group', $group);

        $setting = $query
            ->first();

        if( isset($setting->id) )
            $setting->delete();

        return $this;
    }

    /**
     * Delete all settings .
     *
     * @return $this
     */
    public function deleteAll() {
        $this->model->truncate();

        return $this;
    }

    /**
     * Update or create .
     *
     * @param $key
     * @param array $data
     * @return $this
     */
    public function updateOrCreate($key, array $data) {
        $this->model->updateOrCreate([
            'key' => $key
        ], $data);

        return $this;
    }

}


text:
if DependencyHelper.http_present?
  require "appsignal/integrations/http"

  describe Appsignal::Integrations::HttpIntegration do
    let(:transaction) { http_request_transaction }

    around do |example|
      keep_transactions { example.run }
    end

    before :context do
      start_agent
    end

    before do
      set_current_transaction(transaction)
    end

    it "instruments a HTTP request" do
      stub_request(:get, "http://www.google.com")

      HTTP.get("http://www.google.com")

      transaction_hash = transaction.to_h
      expect(transaction_hash).to include("namespace" => Appsignal::Transaction::HTTP_REQUEST)
      expect(transaction_hash["events"].first).to include(
        "body" => "",
        "body_format" => Appsignal::EventFormatter::DEFAULT,
        "name" => "request.http_rb",
        "title" => "GET http://www.google.com"
      )
    end

    it "instruments a HTTPS request" do
      stub_request(:get, "https://www.google.com")

      HTTP.get("https://www.google.com")

      transaction_hash = transaction.to_h
      expect(transaction_hash).to include("namespace" => Appsignal::Transaction::HTTP_REQUEST)
      expect(transaction_hash["events"].first).to include(
        "body" => "",
        "body_format" => Appsignal::EventFormatter::DEFAULT,
        "name" => "request.http_rb",
        "title" => "GET https://www.google.com"
      )
    end

    context "with request parameters" do
      it "does not include the query parameters in the title" do
        stub_request(:get, "https://www.google.com?q=Appsignal")

        HTTP.get("https://www.google.com", :params => { :q => "Appsignal" })

        expect(transaction.to_h["events"].first).to include(
          "body" => "",
          "title" => "GET https://www.google.com"
        )
      end

      it "does not include the request body in the title" do
        stub_request(:post, "https://www.google.com")
          .with(:body => { :q => "Appsignal" }.to_json)

        HTTP.post("https://www.google.com", :json => { :q => "Appsignal" })

        expect(transaction.to_h["events"].first).to include(
          "body" => "",
          "title" => "POST https://www.google.com"
        )
      end
    end

    context "with an HTTP exception" do
      let(:error) { ExampleException.new("oh no!") }

      it "reports the exception and re-raises it" do
        stub_request(:get, "https://www.google.com").and_raise(error)

        expect do
          HTTP.get("https://www.google.com")
        end.to raise_error(ExampleException)

        transaction_hash = transaction.to_h
        expect(transaction_hash).to include("namespace" => Appsignal::Transaction::HTTP_REQUEST)
        expect(transaction_hash["events"].first).to include(
          "body" => "",
          "body_format" => Appsignal::EventFormatter::DEFAULT,
          "name" => "request.http_rb",
          "title" => "GET https://www.google.com"
        )

        expect(transaction_hash["error"]).to include(
          "backtrace" => kind_of(String),
          "name" => error.class.name,
          "message" => error.message
        )
      end
    end

    context "with various URI objects" do
      it "parses an object responding to #to_s" do
        request_uri = Struct.new(:uri) do
          def to_s
            uri.to_s
          end
        end

        stub_request(:get, "http://www.google.com")

        HTTP.get(request_uri.new("http://www.google.com"))

        expect(transaction.to_h["events"].first).to include(
          "name" => "request.http_rb",
          "title" => "GET http://www.google.com"
        )
      end

      it "parses an URI object" do
        stub_request(:get, "http://www.google.com")

        HTTP.get(URI("http://www.google.com"))

        expect(transaction.to_h["events"].first).to include(
          "name" => "request.http_rb",
          "title" => "GET http://www.google.com"
        )
      end

      it "parses a String object" do
        stub_request(:get, "http://www.google.com")

        HTTP.get("http://www.google.com")

        expect(transaction.to_h["events"].first).to include(
          "name" => "request.http_rb",
          "title" => "GET http://www.google.com"
        )
      end
    end
  end
end


text:
    {{'posts.index.title' | translate}}

  <md-content>
    <md-list>
      <md-list-item class="md-3-line" ng-repeat="post in postsController.posts">

          {{post.title}}

{{post.author}} - {{post.date | date: format: 'dd.MM.yyyy'}}

              {{'posts.index.edit' | translate}}
            |

              {{'posts.index.delete' | translate}}

          {{post.category}}

          {{'posts.rating' | translate}}: {{post.rating}}

          {{'posts.solved' | translate}}

      </md-list-item>
    </md-list>
  </md-content>


text:
Create the add-on package:

TODO: <https://github.com/ember-cli/ember-cli.github.io/issues/144>

`sudo ember addon ember-perfect-gallery`

Install dependencies:

`npm install perfect-layout --save`

Create a component:

`ember g component ember-perfect-gallery`

Add some text to the template and test if we can import the addon to an existing ember app.

`ember new foo && cd foo`

`ember install https://github.com/myartsev/ember-perfect-gallery.git`

TODO: what does this mean?

```
NPM: Installed https://github.com/myartsev/ember-perfect-gallery.git
WARNING: Could not figure out blueprint name from: "https://github.com/myartsev/ember-perfect-gallery.git". Please install the addon blueprint via "ember generate <addon-name>" if necessary.
Installed addon package.
```

# Serve the newly generated project

`ember s`

TODO: what does this mean?

```
Addon templates were detected, but there are no template compilers registered for `ember-perfect-gallery`. Please make sure your template precompiler (commonly `ember-cli-htmlbars`) is listed in `dependencies` (NOT `devDependencies`) in `ember-perfect-gallery`'s `package.json`.
```

# Try again

`ember install https://github.com/myartsev/ember-perfect-gallery.git`

`ember s`

It runs! Let's try to see if we can use the addon to see our placeholder text from earlier.

**application.hbs**

```
<div>Hello from Ember!</div>
{{ember-perfect-gallery}}
{{outlet}}
```

It works!

![](1.png)

# Let's try adding some interactivity.

**ember-perfect-gallery.hbs**

```
Hello from ember-perfect-gallery!
<button {{action 'doSomething'}}>Do something</button>
```

**ember-perfect-gallery.js**

```
import Ember from 'ember';
export { default } from 'ember-perfect-gallery/components/ember-perfect-gallery';

export default Ember.Component.extend({
  actions: {
    doSomething: () => {
      console.log('something');
    }
  }
});
```

Give it a try in the Ember app:

`ember install https://github.com/myartsev/ember-perfect-gallery.git` Stop and restart the Ember server:

`ember s`

Nope...

```
Build error

SyntaxError: foo/components/ember-perfect-gallery.js: Only one default export allowed per module. (4:0)
  2 | export { default } from 'ember-perfect-gallery/components/ember-perfect-gallery';
  3 |
> 4 | export default Ember.Component.extend({
    | ^
  5 |   actions: {
  6 |     doSomething: () => {
  7 |       console.log('something');
    at Parser.pp$5.raise (/home/anijap/code/foo/node_modules/babylon/lib/index.js:4452:13)
    at Parser.pp$1.raiseDuplicateExportError (/home/anijap/code/foo/node_modules/babylon/lib/index.js:2819:8)
    at Parser.pp$1.checkDuplicateExports (/home/anijap/code/foo/node_modules/babylon/lib/index.js:2813:10)
    at Parser.pp$1.checkExport (/home/anijap/code/foo/node_modules/babylon/lib/index.js:2712:12)
    at Parser.pp$1.parseExport (/home/anijap/code/foo/node_modules/babylon/lib/index.js:2649:10)
    at Parser.pp$1.parseStatement (/home/anijap/code/foo/node_modules/babylon/lib/index.js:1884:74)
    at Parser.pp$1.parseBlockBody (/home/anijap/code/foo/node_modules/babylon/lib/index.js:2268:21)
    at Parser.pp$1.parseTopLevel (/home/anijap/code/foo/node_modules/babylon/lib/index.js:1778:8)
    at Parser.parse (/home/anijap/code/foo/node_modules/babylon/lib/index.js:1673:17)
    at parse (/home/anijap/code/foo/node_modules/babylon/lib/index.js:7180:37)

The broccoli plugin was instantiated at:
    at Babel.Plugin (/home/anijap/code/foo/node_modules/broccoli-plugin/index.js:7:31)
    at Babel.Filter [as constructor] (/home/anijap/code/foo/node_modules/broccoli-persistent-filter/index.js:62:10)
    at new Babel (/home/anijap/code/foo/node_modules/broccoli-babel-transpiler/index.js:35:10)
    at Babel (/home/anijap/code/foo/node_modules/broccoli-babel-transpiler/index.js:30:12)
    at Class.transpileTree (/home/anijap/code/foo/node_modules/ember-cli-babel/index.js:38:48)
    at Object.toTree (/home/anijap/code/foo/node_modules/ember-cli-babel/index.js:45:30)
    at /home/anijap/code/foo/node_modules/ember-cli-preprocess-registry/preprocessors.js:180:26
    at Array.forEach (native)
    at processPlugins (/home/anijap/code/foo/node_modules/ember-cli-preprocess-registry/preprocessors.js:178:11)
    at module.exports.preprocessJs (/home/anijap/code/foo/node_modules/ember-cli-preprocess-registry/preprocessors.js:171:10)
```

Wait a minute, I can do this from the addon itself instead of having to push to GIT and test in a different Ember project. Just use the dummy app in the addon!

Turns out that there are two components in the addon hierarcy, not sure why yet. But now the JS action is working when the code is moved to _addon/components_

![](2.png)

**TODO:** what's up with the deprecation warning?

**TODO:** why are there two component JS files? Is it because of the ember g command we ran earlier? ![](4.png)

Cool, now it works in the dummy app. Let's try with our _foo_ Ember app to make sure.

`ember install https://github.com/myartsev/ember-perfect-gallery.git && ember s`

All good!

# Let's try adding some styles

There doesn't appear to be a generator for adding styles.

`mkdir addon/styles`

Create an app.css file here:

```
#counter {
  color: blue;
}
```

This must be added manually to be part of the addon.

**index.js**

```
module.exports = {
  name: 'ember-perfect-gallery',

  included: function(app) {
    app.import('addon/styles/app.css');
  }
};
```

It works on the dummy test app, let's try it with our Ember test app. It works too! ![](3.png)

**TODO:** CSS for addons is not documented too well in ember-cli, and not appears that there is no standarized way on how it should be done: <https://github.com/ember-cli/ember-cli/issues/2940>, <https://github.com/ember-cli/ember-cli/issues/1853>

# Adding a bower dependency

Generate a default blueprint

`ember g blueprint ember-perfect-gallery`

Add the bower dependency.

**blueprints/ember-perfect-gallery/index.js**

```
/* eslint-env node */
module.exports = {
  description: ''

  // locals: function(options) {
  //   // Return custom template variables here.
  //   return {
  //     foo: options.entity.options.foo
  //   };
  // }

  afterInstall: function(options) {
    return this.addBowerPackageToProject('perfect-layout');
  }
};
```

Now this dependency will be installed along with the addon when used in a separate Ember project.

Hah! Not so fast there. It still does not work. After much searching, [I stumbled upon this article](http://emberup.co/ember-addon-secrets/), and the missing piece turned out to be _normalizeEntityName_.

**TODO:** [why is this necessary?](https://stackoverflow.com/questions/44204540/why-does-an-ember-addon-using-a-bower-dependency-needs-to-override-normalizeenti)

```
/* eslint-env node */
module.exports = {
  description: '',
  normalizeEntityName: function() {},

  // locals: function(options) {
  //   // Return custom template variables here.
  //   return {
  //     foo: options.entity.options.foo
  //   };
  // }

  afterInstall: function(options) {
    return this.addBowerPackageToProject('perfect-layout');
  }
};
```

Note that since we are working with an "official" npm addon, we need to manually run `ember g ember-perfect-gallery` in our ember app so that the default blueprint executes.

# Linking to the addon while developing
Instead of pushing to GitHub (or other repo) and re-running `ember install https://github.com/myartsev/ember-perfect-gallery.git` every time you make a change and want to test it, you can use npm linking to do all this on your local machine:

* In the add-on directory, run `npm link`
This will make the addon accessible locally
* In the app directory that wishes to use this addon, run `npm link <addon-name`, in our case `npm link ember-perfect-gallery`.
Add the linked npm project manually to the app's package.json:
```
...
"dependencies": {
  "ember-perfect-gallery": "*"
},
...
```
Finally, `ember g ember-perfect-gallery` needs to be run in the app directory to execute the default blueprint. This would not be necessary if the addon is "officially" published to npm.

# Publish add-on
```
npm version 0.0.1
git push origin master
git push origin --tags
npm publish
```


text:
SakaiPy
=======

A library to access the information located on Sakai installations. This can be thought more of a 'pretty wrapper' around the REST interface that Sakai gives you.

I'm mainly a Java developer so anyone with more Python experience is more than welcome to make a pull request to clean it up!

I made this library so people can access the Sakai information at their schools (I'm @ Rutgers) more easily through Python.

You can install SakaiPy with pip by typing in the following command:

```
pip install SakaiPy
```

I'll usually make a blog post about each new version at my website. https://blog.willkara.com

### TO-DO
* Integrate services available under Sakai's WebServices directory.
* Add events to Google Calendar.
* Add more Sakai tools and more functionality for each tool.
* Better HTTP Code error handling- If something breaks return a code, or a reason depending on how Sakai handles the error.

### Example

````
from SakaiPy import SakaiPy

info = {'username': 'willkara',
        'password': '8675309eeine',
        'baseurl': 'https://sakai.rutgers.edu'}

sak = SakaiPy.SakaiPy(info)

print(sak.session.get_current_user_info())
```

### Sakai Documentation

**ALL** of the data,endpoints and documentation can be found @ <<Sakai Installation URL>>/direct/describe.

BTW: In no way,shape,form or Universe does Rutgers University endorse or have anything to do with this library. I made it myself. This library also does not speak for the Sakai Community Project either.


text:
<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=utf-8">

    <title>AvNav Routen Editor</title>
    <link href="../styles.css" rel="stylesheet" type="text/css">

Der Routeneditor

Übersicht

Der Routen-Editor ist über den Button von der Navigationsseite
      erreichbar. Ausserdem kann er über den Button Edit im Info Dialog zu einer Route auf der Files/Download Seite erreicht
      werden.

Buttons

          Icon
          Name
          Funktion

          ZoomIn
          Hereinzoomen

          ZoomOut
          Hinauszoomen

          NavAddAfter
          Einen neuen Punkt zur Route hinzufügen (insert after)

            Der Kartenmittelpunkt (Kreuz) wird als neuer Punkt hinter dem
            momentan rot markierten Punkt der Route hinzugefügt.

          NavAdd
          Einen neuen Punkt zur Route hinzufügen (insert before)

            Der Kartenmittelpunkt (Kreuz) wird als neuer Punkt vor dem momentan
            rot markierten Punkt der Route hinzugefügt.

          NavDelete
          Löschen des momentan rot markierten Punktes der Route

          NavToCenter
          Verschieben des momentan rot markierten Punktes der Route auf den
            Kartenmittelpunkt

          NavGoto
          Starte die Navigation zum momentan rot markierten Punkt der Route

          NavOverlays
          Ein- und Ausblenden von Overlays

          MOB
          Mann über Bord(siehe Hauptseite)

          Cancel
          Zurück zur Navigationsseite

Auf dieser Seite kann man eine Route bearbeiten bzw. erzeugen.

Zu jeder Zeit gibt es einen aktiven Wegpunkt (rot dargestellt, links in
      der Anzeige grau unterlegt. Die meisten Aktionen beziehen sich auf diesen
	   Wegpunkt. Er kann durch Anklicken links in der Liste oder durch Anklicken
      auf der Karte geändert werden.

Wenn man die momentan aktive Route bearbeitet, wird das durch einen roten
      Rahmen links um die Routen-Info angezeigt. Falls eine andere Route
      bearbeitet wird, ist dieser grün.

 Wenn man den Editor verlässt, geht die Anzeige zur aktiven Route zurück.

Alle Änderungen werden sofort wirksam, es gibt kein undo.

Auf der linken Seite werden die Wegpunkte der aktuellen Route angezeigt.
      Dazu jeweils die Kurse und Distanzen für die Abschnitte. Im oberen Teil
      die Gesamtlänge der Route sowie die Gesamtstrecke sowie die ETA. Durch
      Anklicken kann man einen Wegpunkt aktivieren.

Durch nochmaligen Klick auf einen links bereits markierten Punkt wird
      eine Eingabemaske aufgerufen, in der man den Wegpunkt bearbeiten kann.

Route Dialog

Ein Klick auf das Route Info Feld (links oben) führt zu einem Dialog.

Hier kann man den Namen der Route ändern, eine neue Route zum Editieren
      auswählen, die Route kopieren, sie löschen, invertieren oder alle Punkte
      löschen.

Ein Klick auf den Edit Button führt zur Route
        Liste. Hier kann man die Wegpunkte bearbeiten oder ebenfalls eine
      neue Route wählen.

Ein Klick auf die linken unteren Anzeigen zeigt einige zusätzliche
      Buttons.

Mit diesen kann zwischen den Punkten der Route gewechselt werden bzw. der
      aktuelle Punkt kann bearbeitet werden.

Ein Klick auf die rechten Anzeigen zentriert die Karte auf die
      Bootsposition.

Nutzung von Overlays

Falls (wie im Bild) Overlays
      angezeigt werden (oder in ocharts-Karten)
      kann man durch Klick auf ein Objekt einen Dialog aufrufen, der weitere
      Routen-Funktionen bietet.

Der angeklickte Punkt kann jetzt in die Route eingefügt werden. Auf diese
      Weise können leicht Punkte z.B. aus einer Wegpunkt-Datei zum Erstellen
      von Routen genutzt werden.

Falls das angezeigte Overlay eine Route ist, kann der Teil nach dem
      angeklickten Punkt der aktuellen Route hinzugefügt werden.

Im Dialog wird der angeklickte Startpunkt der Route angezeigt und man
      kann auswählen, ob man die Route vor oder hinter dem aktuell markierten
      Punkt der in Bearbeitung befindlichen Route einfügen möchte.


text:
<title>dlib C++ Library - rank_features_ex.cpp</title>

// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
/*

    This is an example illustrating the use of the rank_features() function
    from the dlib C++ Library.

    This example creates a simple set of data and then shows
    you how to use the rank_features() function to find a good
    set of features (where "good" means the feature set will probably
    work well with a classification algorithm).

    The data used in this example will be 4 dimensional data and will
    come from a distribution where points with a distance less than 10
    from the origin are labeled +1 and all other points are labeled
    as -1.  Note that this data is conceptually 2 dimensional but we
    will add two extra features for the purpose of showing what
    the rank_features() function does.
*/

#include <iostream>
#include <dlib/svm.h>
#include <dlib/rand.h>
#include <vector>

using namespace std;
using namespace dlib;

int main()
{

    // This first typedef declares a matrix with 4 rows and 1 column.  It will be the
    // object that contains each of our 4 dimensional samples.
    typedef matrix<double, 4, 1> sample_type;

    // Now lets make some vector objects that can hold our samples
    std::vector<sample_type> samples;
    std::vector<double> labels;

    dlib::rand rnd;

    for (int x = -30; x <= 30; ++x)
    {
        for (int y = -30; y <= 30; ++y)
        {
            sample_type samp;

            // the first two features are just the (x,y) position of our points and so
            // we expect them to be good features since our two classes here are points
            // close to the origin and points far away from the origin.
            samp(0) = x;
            samp(1) = y;

            // This is a worthless feature since it is just random noise.  It should
            // be indicated as worthless by the rank_features() function below.
            samp(2) = rnd.get_random_double();

            // This is a version of the y feature that is corrupted by random noise.  It
            // should be ranked as less useful than features 0, and 1, but more useful
            // than the above feature.
            samp(3) = y*0.2 + (rnd.get_random_double()-0.5)*10;

            // add this sample into our vector of samples.
            samples.push_back(samp);

            // if this point is less than 15 from the origin then label it as a +1 class point.
            // otherwise it is a -1 class point
            if (sqrt((double)x*x + y*y) <= 15)
                labels.push_back(+1);
            else
                labels.push_back(-1);
        }
    }

    // Here we normalize all the samples by subtracting their mean and dividing by their standard deviation.
    // This is generally a good idea since it often heads off numerical stability problems and also
    // prevents one large feature from smothering others.
    const sample_type m(mean(mat(samples)));  // compute a mean vector
    const sample_type sd(reciprocal(stddev(mat(samples)))); // compute a standard deviation vector
    // now normalize each sample
    for (unsigned long i = 0; i < samples.size(); ++i)
        samples[i] = pointwise_multiply(samples[i] - m, sd);

    // This is another thing that is often good to do from a numerical stability point of view.
    // However, in our case it doesn't really matter.   It's just here to show you how to do it.
    randomize_samples(samples,labels);

    // This is a typedef for the type of kernel we are going to use in this example.
    // In this case I have selected the radial basis kernel that can operate on our
    // 4D sample_type objects.  In general, I would suggest using the same kernel for
    // classification and feature ranking.
    typedef radial_basis_kernel<sample_type> kernel_type;

    // The radial_basis_kernel has a parameter called gamma that we need to set.  Generally,
    // you should try the same gamma that you are using for training.  But if you don't
    // have a particular gamma in mind then you can use the following function to
    // find a reasonable default gamma for your data.  Another reasonable way to pick a gamma
    // is often to use 1.0/compute_mean_squared_distance(randomly_subsample(samples, 2000)).
    // It computes the mean squared distance between 2000 randomly selected samples and often
    // works quite well.
    const double gamma = verbose_find_gamma_with_big_centroid_gap(samples, labels);

    // Next we declare an instance of the kcentroid object.  It is used by rank_features()
    // two represent the centroids of the two classes.  The kcentroid has 3 parameters
    // you need to set.  The first argument to the constructor is the kernel we wish to
    // use.  The second is a parameter that determines the numerical accuracy with which
    // the object will perform part of the ranking algorithm.  Generally, smaller values
    // give better results but cause the algorithm to attempt to use more dictionary vectors
    // (and thus run slower and use more memory).  The third argument, however, is the
    // maximum number of dictionary vectors a kcentroid is allowed to use.  So you can use
    // it to put an upper limit on the runtime complexity.
    kcentroid<kernel_type> kc(kernel_type(gamma), 0.001, 25);

    // And finally we get to the feature ranking. Here we call rank_features() with the kcentroid we just made,
    // the samples and labels we made above, and the number of features we want it to rank.
    cout << rank_features(kc, samples, labels) << endl;

    // The output is:
    /*
        0 0.749265
        1        1
        3 0.933378
        2 0.825179
    */

    // The first column is a list of the features in order of decreasing goodness.  So the rank_features() function
    // is telling us that the samples[i](0) and samples[i](1) (i.e. the x and y) features are the best two.  Then
    // after that the next best feature is the samples[i](3) (i.e. the y corrupted by noise) and finally the worst
    // feature is the one that is just random noise.  So in this case rank_features did exactly what we would
    // intuitively expect.

    // The second column of the matrix is a number that indicates how much the features up to that point
    // contribute to the separation of the two classes.  So bigger numbers are better since they
    // indicate a larger separation.  The max value is always 1.  In the case below we see that the bad
    // features actually make the class separation go down.

    // So to break it down a little more.
    //    0 0.749265   <-- class separation of feature 0 all by itself
    //    1        1   <-- class separation of feature 0 and 1
    //    3 0.933378   <-- class separation of feature 0, 1, and 3
    //    2 0.825179   <-- class separation of feature 0, 1, 3, and 2

}


text:
/**
 * Swaggy Jenkins
 * Jenkins API clients generated from Swagger / Open API specification
 *
 * The version of the OpenAPI document: 1.5.1-pre.0
 * Contact: blah@cliffano.com
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

/**
 * Class to storage authentication data
 */
export class AuthStorage {
  private storage: Map<string, string>;

  constructor() {
    this.storage = new Map();
  }

  /**
   * Sets the jenkins_auth auth method value.
   *
   * @param value The new value to set for jenkins_auth.
   */
  setjenkins_auth(value: string): this {
    this.storage.set('jenkins_auth', value);
    return this;
  }

  /**
   * Removes the jenkins_auth auth method value.
   */
  removejenkins_auth(): this {
    this.storage.delete('jenkins_auth');
    return this;
  }

  /**
   * Gets the jenkins_auth auth method value.
   */
  getjenkins_auth(): null | string {
    return this.storage.get('jenkins_auth') || null;
  }

  /**
   * Sets the jwt_auth auth method value.
   *
   * @param value The new value to set for jwt_auth.
   */
  setjwt_auth(value: string): this {
    this.storage.set('jwt_auth', value);
    return this;
  }

  /**
   * Removes the jwt_auth auth method value.
   */
  removejwt_auth(): this {
    this.storage.delete('jwt_auth');
    return this;
  }

  /**
   * Gets the jwt_auth auth method value.
   */
  getjwt_auth(): null | string {
    return this.storage.get('jwt_auth') || null;
  }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="bc.css">

IFC Update, Instance Geometry, Parameters

I completed the move to my new computer, and happily all systems go now.

Here are some other topics that came up in the past few days:

Revit-IFC Release 20.1.0

Community discussion on Revit

Solid or instance, depending

Exporting parameters to Access

Store globals on custom DataStorage, not ProjectInfo

Mahab Ghodss civil engineering project (video)

Iranian civil engineering project video

 Revit-IFC Release 20.1.0

Release 20.1.0 for Revit 2020 has been released.

It includes 20.0.0.0 plus the out-of-the-box Revit 2020 IFC functionalities, bug fixes and various regression fixes.

Says Angel @avelezsosa Velez:

Finally! #Revit #IFC #OpenSource #GitHub v20.1 is out! https://t.co/TmCc62uDjA. Up next: App Store version, v19.3.
— Angel Velez (@avelezsosa) August 8, 2019

 Community Discussion on Revit

In the Revit API discussion forum,
Daniel Alvarado invites all Revit API users to
a community discussion on Revit, saying:

I found an interesting article on the Revit Blog.
I am sharing this article by Amie Vaccaro to discuss

How ongoing innovations have made Revit more automated than ever

To participate in the discussion, write your comments, thoughts, and questions and feel free to agree or disagree with the ideas presented in the article. I would like to hear all kinds of feedback   :-)

Discussion questions:

What features of Revit do you wish were automated?

Now that you know what features are automated, which one is most useful for you?

We invite anyone to participate in these discussions and look forward to animated conversations!

 Solid or Instance, Depending

Also in the discussion forum, in the thread asking why
the solid element is missing,
Bobby C Jones points out two important basic knowledgebase articles clarifying how to retrieve geometry from family instances:

First, the article
on GeometryInstances explains:

Note that not all Family instances will include GeometryInstances.
  When Revit needs to make a unique copy of the family geometry for a given instance (because of the effect of local joins, intersections, and other factors related to the instance placement), no GeometryInstance will be encountered; instead, the Solid geometry will be found at the top level of the hierarchy.

It also points to the helpful Example: Retrieve Geometry Data from a Beam, which reiterates:

The GeometryElement may contain the desired geometry as a Solid or GeometryInstance, depending on whether a beam is joined or standalone, and this code covers both cases...

If this is unclear to you, please refer to the detailed knowledgebase explanations.

 Exporting Parameters to Access

Another short note from the discussion forum
on how to export selected parameters to MS access using my own ribbon:

Question: If I want to create my own ribbon within add-ins menu of Revit 2019. And when I click the ribbon, it will show the window that asks me which parameters I want to export to MS access file. (I want to be able to select the required parameters of each element.) Can you suggest any API sample code? Thank you.

Answer: Look at the ADN Xtra labs,
in the XtraCs project, module Lab4.cs, especially the external
commands Lab4_1_ElementParameters
and Lab4_2_ExportParametersToExcel.

 Store Globals on Custom DataStorage, not ProjectInfo

Talking about parameters, I implemented an add-in to round-trip Revit element parameters to Forge and back, enabling
the use of Forge or an external spreadsheet to create shared parameters.

A recent comment on that once again brought up the topic of storing global information in the model.

If you wish to do so, do not store it on the ProjectInfo singleton element; rather, you can and should create your own DataStorage element for this purpose, as explained in the note
on storing a dictionary – use DataStorage, not ProjectInfo.


text:
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0019_submission_description'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('rating', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='ThemeResults',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('modified', models.DateTimeField(auto_now=True)),
                ('accepted_threshold', models.SmallIntegerField()),
                ('theme', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='results', to='core.Theme')),
                ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='SubmissionReward',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('modified', models.DateTimeField(auto_now=True)),
                ('kind', models.SmallIntegerField(choices=[(1, 'Gold'), (2, 'Silver'), (3, 'Bronze'), (4, 'Honorable Mention')])),
                ('submission', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='reward', to='core.Submission')),
                ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
    ]


text:
@interface Tuple : NSObject<NSCopying>

@property (nonatomic, assign, readonly) int size;

- (instancetype)initWithObjectsFromArray:(NSArray*)array;
- (id)objectAtIndexedSubscript:(NSUInteger)index;

@end

#ifdef __cplusplus
extern "C" {
#endif

    Tuple* MkUnit();
    Tuple* MkPair(id a, id b);
    id Fst(Tuple* tuple);
    id Snd(Tuple* tuple);

#ifdef __cplusplus
}
#endif


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for /var/www/source/hca_draft/src/HealthCareAbroad/UserBundle</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

/var/www/source/hca_draft/src/HealthCareAbroad /

UserBundle

(Dashboard)

Code Coverage

Lines

Functions and Methods

Classes and Traits

      Total

25.19%

196 / 778

41.35%

55 / 133

18.52%

5 / 27

       Entity

14.91%

48 / 322

44.00%

33 / 75

0.00%

0 / 7

       Form

29.81%

31 / 104

35.71%

5 / 14

28.57%

2 / 7

       Repository

12.71%

15 / 118

23.08%

3 / 13

16.67%

1 / 6

       Services

43.23%

99 / 229

44.44%

12 / 27

20.00%

1 / 5

       Twig

60.00%

3 / 5

50.00%

2 / 4

0.00%

0 / 1

       UserBundle.php

100.00%

1 / 1

Legend

     Low: 0% to 35%
     Medium: 35% to 70%
     High: 70% to 100%

     Generated by PHP_CodeCoverage 1.2.2 using PHP 5.3.10-1ubuntu3.2 and PHPUnit 3.7.1 at Tue Oct 9 16:19:45 PHT 2012.


text:
package com.esri.gpt.catalog.arcims;

/**
 * Stores a reference to an ArcIMS server.
 */
public class ImsCatalog {

// class variables =============================================================

// instance variables ==========================================================
private ImsService _browseService;
private ImsService _publishService;

// constructors ================================================================

/** Default constructor. */
public ImsCatalog() {
  setBrowseService(new ImsService());
  setPublishService(new ImsService());
}

// properties ==================================================================

/**
 * Gets the metadata browse service.
 * @return the service
 */
public ImsService getBrowseService() {
  return _browseService;
}
/**
 * Sets the metadata browse service.
 * @param service the service
 */
private void setBrowseService(ImsService service) {
  _browseService = service;
}

/**
 * Gets the metadata publish service.
 * @return the service
 */
public ImsService getPublishService() {
  return _publishService;
}
/**
 * Sets the metadata publish service.
 * @param service the service
 */
private void setPublishService(ImsService service) {
  _publishService = service;
}

// methods =====================================================================

/**
 * Returns the string representation of the object.
 * @return the string
 */
@Override
public String toString() {
  StringBuffer sb = new StringBuffer(getClass().getName()).append(" (\n");
  sb.append(" publishService:").append(getPublishService()).append("\n");
  sb.append(" browseService:").append(getBrowseService()).append("\n");
  sb.append(") ===== end ").append(getClass().getName());
  return sb.toString();
}

}


text:
module Archimate
  module Svg
    module Entity
      class Contract < DataEntity
        def initialize(child, bounds_offset)
          super
        end

        def entity_shape(xml, bounds)
          calc_text_bounds(bounds)
          xml.g(class: background_class) do
            xml.rect(x: bounds.left, y: bounds.top, width: bounds.width, height: bounds.height, class: background_class, style: shape_style)
            xml.rect(x: bounds.left, y: bounds.top, width: bounds.width, height: @margin, class: "archimate-decoration")
            xml.rect(x: bounds.left, y: bounds.top + bounds.height - @margin, width: bounds.width, height: @margin, class: "archimate-decoration")
          end
        end
      end
    end
  end
end


text:
"""
* hooks_djb.py
* Author: stal, stqism; April 2014
* Copyright (c) 2014 Zodiac Labs.
* Further licensing information: see LICENSE.
"""
import os
import subprocess
import time
import logging
import threading

LOGGER = None
NEEDS_UPDATE = 0

def thread_run(root, database, ttl, home):
    global NEEDS_UPDATE
    while 1:
        if NEEDS_UPDATE:
            djbdns_write_file(root, database, ttl, home)
            NEEDS_UPDATE = 0
        time.sleep(10)

def init(config, database):
    global LOGGER, did_update_record, did_delete_record, NEEDS_UPDATE
    NEEDS_UPDATE = 1
    LOGGER = logging.getLogger("djb_hooks")
    t = threading.Thread(target=thread_run, args=(config["djbdns_root"],
                         database, config["dns_record_ttl"],
                         config["registration_domain"]))
    t.daemon = True
    t.start()

def did_update_record(nul, rec):
    global NEEDS_UPDATE
    NEEDS_UPDATE = 1

did_delete_record = did_update_record

def djbdns_write_file(root, database, ttl, home):
    data_name = os.path.join(root, "data")
    master = open(data_name, "w")
    header_name = os.path.join(root, "header.yuu")
    with open(header_name, "r") as header:
        h = header.read()
        master.write(h)
        master.write("\n")

    master.write("# This data automatically updated by yuu. Please edit"
                  " header.yuu instead.\n")
    for obj in database.iterate_all_users():
        master.write("'{0}:{1}:{2}\n".format(obj.fqdn(home), obj.record(), ttl))
    master.close()

    prev = os.getcwd()
    os.chdir(root)
    subprocess.check_output(["make"])
    os.chdir(prev)
    LOGGER.info("Update succeeded.")


text:
package nosj_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/totherme/nosj"
	. "github.com/totherme/nosj/gnosj"
)

var _ = Describe("Some things you can test with nosj", func() {
	Context("when I have some JSON", func() {
		var rawjson string = `
		{ "id": 1,
			"type": "hr-data",
			"employees": [
				{ "id": 1,
					"type": "employee",
					"name": "Alex",
					"salary-band": 12,
					"department": "finance",
					"profile": {
						"favourite-animal": "cat",
						"special-skill": "szechuan cookery",
						"number-of-reports": 4
					}
				},
				{ "id": 2,
					"type": "employee",
					"name": "Sue",
					"salary-band": 8,
					"department": "logistics",
					"profile": {
						"favourite-animal": "dog",
						"special-skill": "rock climbing",
						"number-of-reports": 12
					}
				},
				{ "id": 3,
					"type": "employee",
					"name": "Hilary",
					"salary-band": 14,
					"department": "engineering",
					"profile": {
						"favourite-animal": "hedgehog",
						"special-skill": "archery",
						"number-of-reports": 2
					}
				}
			]
		}`
		var json nosj.JSON

		BeforeEach(func() {
			var err error
			json, err = nosj.ParseJSON(rawjson)
			Expect(err).NotTo(HaveOccurred())
		})

		It("contains three employees", func() {
			employees, err := json.GetByPointer("/employees")
			Expect(err).NotTo(HaveOccurred())
			Expect(employees).To(BeAList())
			Expect(employees.ListValue()).To(HaveLen(3))
		})

		Describe("the first employee", func() {
			It("is great at cooking", func() {
				skill, err := json.GetByPointer("/employees/0/profile/special-skill")
				Expect(err).NotTo(HaveOccurred())
				Expect(skill).To(BeAString())
				Expect(skill.StringValue()).To(Equal("szechuan cookery"))
			})
		})
	})
})


text:
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using WoTget.Core.Authoring;
using System.IO;
using WoTget.Core;
using System;

namespace WoTget.LocalStore
{
    public class StoreItem
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Version { get; set; }
        [JsonIgnore]
        public string FileName
        {
            get
            {
                return $"{this.Id}.{new SemanticVersion(this.Version).ToNormalizedString()}{Constants.PackageExtension}";
            }
        }
    }

    public class Store
    {

        private List<StoreItem> items = new List<StoreItem>();
        private string file;
        private string directory;

        public Store(string file)
        {
            this.file = file;
            this.directory = Path.GetDirectoryName(this.file);

            if (!Directory.Exists(directory))
            {
                var d = Directory.CreateDirectory(directory);
                d.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
            }

            Load();
        }

        public void Add(IPackage package, Stream stream)
        {
            var item = Find(package);
            if (item != null)
            {
                if (item.Version == package.SemanticVersion.ToNormalizedString()) return;
                Remove(package);
            }

            this.items.Add(new StoreItem { Id = package.Id, Name = package.Name, Version = package.SemanticVersion.ToNormalizedString() });

            stream.Seek(0, SeekOrigin.Begin);
            using (FileStream file = new FileStream(Path.Combine(this.directory, package.FileName), FileMode.Create, FileAccess.Write))
                stream.CopyTo(file);

            Save();
        }

        public void Remove(IPackage package)
        {
            var item = Find(package);
            if (item == null) return;

            this.items.Remove(item);

            if (File.Exists(Path.Combine(this.directory, item.FileName)))
                File.Delete(Path.Combine(this.directory, item.FileName));

            Save();
        }

        public MemoryStream GetPackage(IPackage package)
        {

            var item = Find(package);
            if (item == null) throw new ArgumentException("Package not found in Store Settings!");
            if (!File.Exists(Path.Combine(this.directory, item.FileName))) throw new ArgumentException("Package not found in Store!");

            MemoryStream ms = new MemoryStream();
            using (FileStream file = new FileStream(Path.Combine(this.directory, item.FileName), FileMode.Open, FileAccess.Read))
                file.CopyTo(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return ms;
        }

        public bool PackageExists(IPackage package)
        {
            var item = Find(package);
            if (item == null) throw new ArgumentException("Package not found in Store Settings!");

            return File.Exists(Path.Combine(this.directory, item.FileName));
        }

        private StoreItem Find(IPackage package)
        {
            return this.items.FirstOrDefault(s => s.Id == package.Id);
        }

        private void Load()
        {
            if (!File.Exists(this.file))
            {
                Save();
                return;
            }
            items = JsonConvert.DeserializeObject<List<StoreItem>>(File.ReadAllText(this.file));
        }

        private void Save()
        {
            var json = JsonConvert.SerializeObject(this.items);
            File.WriteAllText(this.file, json);
        }

        public IEnumerable<IPackage> Packages
        {
            get
            {
                return this.items.Select(i => new Package { Name = i.Name, Version = i.Version });
            }
        }

    }
}


text:
package com.logbot;

import java.math.*;
import java.util.*;
import java.text.*;

public class ModuleChanManagerHelper implements ModuleInterface {
	/*
	 * We need one manager
	 */
	private IrcChannelManager chanManager;

	/*
	 */
	public ModuleChanManagerHelper(IrcChannelManager m) {
		this.chanManager = m;
	}

	/*
	 * This module's responsibility is simply to make sure the manager is up
	 * to date.
	 */
	public String[] run(IrcMessage m) {
		if (m.command.equals("JOIN") && m.nick.equals(IrcConfig.nick)) {
			this.chanManager.join(m.argument);
		}
		else if (m.command.equals("JOIN")) {
			this.chanManager.userJoin(m.argument, m.nick);
		}
		else if (m.command.equals("PART") && m.nick.equals(IrcConfig.nick)) {
			this.chanManager.part(m.target);
		}
		else if (m.command.equals("PART")) {
			this.chanManager.userPart(m.target, m.nick);
		}
		else if (m.command.equals("QUIT")) {
			this.chanManager.userQuit(m.nick);
		}
		else if (m.command.equals("KICK") && m.target.substring(m.target.indexOf(" ") + 1).equals(IrcConfig.nick)) {
			this.chanManager.part(m.target.substring(0, m.target.indexOf(" ")));
		}
		else if (m.command.equals("KICK")) {
			this.chanManager.userPart(m.target.substring(0, m.target.indexOf(" ")), m.target.substring(m.target.indexOf(" ") + 1));
		}
		else if (m.command.equals("NICK")) {
			this.chanManager.changeNick(m.nick, m.argument);
		}
		else if (m.command.equals("MODE")) {
			String[] parts = m.target.split("\\s");

			if (parts.length > 2) {
				return new String[] {"WHOIS " + parts[2]};
			}
		}
		else if (m.command.equals("319")) {
			String nick = m.target.substring(m.target.indexOf(" ") + 1);
			String[] parts = m.argument.split("\\s");
			char prefix;

			for (int i = 0; i < parts.length; i++) {
				prefix = IrcUser.getPrefix(parts[i]);
				this.chanManager.updatePrefix(IrcUser.stripPrefix(parts[i]), nick, prefix);
			}
		}
		else if (m.command.equals("353")) {
			String[] users = m.argument.split("\\s");
			String chan = m.target.substring(m.target.indexOf("#"));

			for (int i = 0; i < users.length; i++) {
				this.chanManager.userJoin(chan, users[i]);
			}
		}

		return null;
	}
}


text:
using Microsoft.Azure.Management.Compute;

namespace Microsoft.Azure.Commands.Compute
{
    public abstract class VirtualMachineSizeBaseCmdlet : ComputeClientBaseCmdlet
    {
        public IVirtualMachineSizesOperations VirtualMachineSizeClient
        {
            get
            {
                return ComputeClient.ComputeManagementClient.VirtualMachineSizes;
            }
        }

        public IVirtualMachinesOperations VirtualMachineClient
        {
            get
            {
                return ComputeClient.ComputeManagementClient.VirtualMachines;
            }
        }

        public IAvailabilitySetsOperations AvailabilitySetClient
        {
            get
            {
                return ComputeClient.ComputeManagementClient.AvailabilitySets;
            }
        }
    }
}


text:
<?php

use backend\modules\user\Module;
use common\models\User;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use common\components\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel backend\modules\user\models\search\RoleSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Module::t('role', 'Role');
$this->params['breadcrumbs'][] = $this->title;
?>

			<?= Html::a(Yii::t('common', 'Create {modelClass}', ['modelClass' => Module::t('role', 'Role')]), ['create'], ['class' => 'btn btn-success']) ?>

		<?= GridView::widget([
			'dataProvider' => $dataProvider,
			'filterModel'  => $searchModel,
			'columns'      => [
				'name',
				'description',

				['class' => '\common\components\grid\ActionColumn'],
			],
		]); ?>


text:
"""
This is part of WebScout software
Docs EN: http://hack4sec.pro/wiki/index.php/WebScout_en
Docs RU: http://hack4sec.pro/wiki/index.php/WebScout
License: MIT
Copyright (c) Anton Kuzmin <http://anton-kuzmin.ru> (ru) <http://anton-kuzmin.pro> (en)

Unit tests for Registry
"""
import sys
import os
import pytest

wrpath = os.path.realpath(os.path.dirname(os.path.realpath(__file__)) + '/../../')
testpath = os.path.realpath(os.path.dirname(os.path.realpath(__file__)))

sys.path.append(wrpath)
sys.path.append(wrpath + '/classes')
sys.path.append(wrpath + '/classes/models')
sys.path.append(wrpath + '/classes/kernel')
sys.path.append(testpath + '/classes')

from classes.Registry import Registry

class Test_Registry(object):
    """Unit tests for Unit tests for Registry"""
    model = None

    def test_set_and_get(self):
        with pytest.raises(KeyError):
            Registry().get('aaa')
        Registry().set('aaa', 'bbb')
        assert Registry().get('aaa') == 'bbb'