text:
using System;

namespace EasyCrypto
{
    internal class SlidingBuffer
    {
        private readonly object _sync = new object();
        private readonly Action<byte[]> _generateData;
        private byte[] _cache = new byte[0];

        public SlidingBuffer(Action<byte[]> generateData)
        {
            _generateData = generateData ?? throw new ArgumentNullException(nameof(generateData));
        }

        public void GetData(byte[] data)
        {
            lock (_sync)
            {
                if (_cache.Length < data.Length)
                {
                    byte[] temp = new byte[data.Length * 8];
                    _generateData(temp);

                    Buffer.BlockCopy(_cache, 0, data, 0, _cache.Length);
                    Buffer.BlockCopy(temp, 0, data, _cache.Length, data.Length - _cache.Length);
                    byte[] cache = new byte[temp.Length + _cache.Length - data.Length];
                    Buffer.BlockCopy(temp, data.Length - _cache.Length, cache, 0, cache.Length);
                    _cache = cache;
                }
                else
                {
                    Buffer.BlockCopy(_cache, 0, data, 0, data.Length);
                    byte[] cache = new byte[_cache.Length - data.Length];
                    Buffer.BlockCopy(_cache, data.Length, cache, 0, cache.Length);
                    _cache = cache;
                }
            }
        }
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.compute.model;

/**
 * The available logging options for a firewall rule.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class FirewallLogConfig extends com.google.api.client.json.GenericJson {

  /**
   * This field denotes whether to enable logging for a particular firewall rule.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean enable;

  /**
   * This field can only be specified for a particular firewall rule if logging is enabled for that
   * rule. This field denotes whether to include or exclude metadata for firewall logs.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String metadata;

  /**
   * This field denotes whether to enable logging for a particular firewall rule.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getEnable() {
    return enable;
  }

  /**
   * This field denotes whether to enable logging for a particular firewall rule.
   * @param enable enable or {@code null} for none
   */
  public FirewallLogConfig setEnable(java.lang.Boolean enable) {
    this.enable = enable;
    return this;
  }

  /**
   * This field can only be specified for a particular firewall rule if logging is enabled for that
   * rule. This field denotes whether to include or exclude metadata for firewall logs.
   * @return value or {@code null} for none
   */
  public java.lang.String getMetadata() {
    return metadata;
  }

  /**
   * This field can only be specified for a particular firewall rule if logging is enabled for that
   * rule. This field denotes whether to include or exclude metadata for firewall logs.
   * @param metadata metadata or {@code null} for none
   */
  public FirewallLogConfig setMetadata(java.lang.String metadata) {
    this.metadata = metadata;
    return this;
  }

  @Override
  public FirewallLogConfig set(String fieldName, Object value) {
    return (FirewallLogConfig) super.set(fieldName, value);
  }

  @Override
  public FirewallLogConfig clone() {
    return (FirewallLogConfig) super.clone();
  }

}

redpajama_set_name: RedPajamaGithub


text:
module Helpers

  def filter_fields(obj, fields = false)
    #
    # This method lets the user specify fields to return, for nice tight
    # partial responses.
    #
    # 'obj' is the JSON object we would normally send
    # 'fields' is a string of comma-separated fields from Grape's params
    # variable.
    #
    if fields && fields.is_a?(String)

      fields.split(',').find_all do |k|
        obj.has_key?(k.to_sym) || obj.has_key?(k)
      end.each_with_object({}) do |k, o|
        o[k] = obj.has_key?(k) ? obj[k] : obj[k.to_sym]
      end

    else
      obj
    end

  end

  def drill_data(data, selectors)
    #
    # Pick deep elelemnts out of a hash. Call it with the raw hash, and
    # the parts of the path the user may have supplied.
    #
    selectors.each do |part|

      if params[part]
        index = params[part]
        index = index.to_i if data.class == Array
        data = data[index]
      end

    end

    # We may have tried to access a non-existent field of an array,
    # which == nil. We don't want to pass that back to the client, so
    # let's make a new empty object
    #
    data = {} unless data

    filter_fields(data, params[:fields])
  end

  def send_or_err(info)
    #
    # Send filtered info back to the client, or 404 if it's nil
    #
    if (info)
      filter_fields(info, params[:fields])
    else
      error!("Not Found", 404)
    end

  end

  def os_type
    #
    # Return the operating system name
    #
    case RbConfig::CONFIG['host_os']

    when /solaris/
      "solaris"
    when /linux/
      "linux"
    end
  end

  def os_ver
    #
    # Return the version of the OS. So far I only need to care about
    # this on Solaris. OmniOS etc will return 11 for this. They
    # still know they're Solaris deep down.
    #
    if os_type == "solaris"
      RbConfig::CONFIG['host_os'].sub(/^.*\./, '').to_i
    end

  end

end


text:
<?php

namespace StreamDataBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class StreamDataBundle extends Bundle
{
}


text:
package org.apache.cassandra.auth;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.google.common.collect.ImmutableMap;

import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.KSMetaData;
import org.apache.cassandra.locator.SimpleStrategy;

public class AuthKeyspace
{
    public static final String NAME = "system_auth";

    public static final String ROLES = "roles";
    public static final String ROLE_MEMBERS = "role_members";
    public static final String ROLE_PERMISSIONS = "role_permissions";
    public static final String RESOURCE_ROLE_INDEX = "resource_role_permissons_index";

    public static final long SUPERUSER_SETUP_DELAY = Long.getLong("cassandra.superuser_setup_delay_ms", 10000);

    private static final CFMetaData Roles =
        compile(ROLES,
                "role definitions",
                "CREATE TABLE %s ("
                + "role text,"
                + "is_superuser boolean,"
                + "can_login boolean,"
                + "salted_hash text,"
                + "member_of set<text>,"
                + "PRIMARY KEY(role))");

    private static final CFMetaData RoleMembers =
        compile(ROLE_MEMBERS,
                "role memberships lookup table",
                "CREATE TABLE %s ("
                + "role text,"
                + "member text,"
                + "PRIMARY KEY(role, member))");

    private static final CFMetaData RolePermissions =
        compile(ROLE_PERMISSIONS,
                "permissions granted to db roles",
                "CREATE TABLE %s ("
                + "role text,"
                + "resource text,"
                + "permissions set<text>,"
                + "PRIMARY KEY(role, resource))");

    private static final CFMetaData ResourceRoleIndex =
        compile(RESOURCE_ROLE_INDEX,
                "index of db roles with permissions granted on a resource",
                "CREATE TABLE %s ("
                + "resource text,"
                + "role text,"
                + "PRIMARY KEY(resource, role))");

    private static CFMetaData compile(String name, String description, String schema)
    {
        return CFMetaData.compile(String.format(schema, name), NAME)
                         .comment(description)
                         .gcGraceSeconds((int) TimeUnit.DAYS.toSeconds(90));
    }

    public static KSMetaData definition()
    {
        List<CFMetaData> tables = Arrays.asList(Roles, RoleMembers, RolePermissions, ResourceRoleIndex);
        return new KSMetaData(NAME, SimpleStrategy.class, ImmutableMap.of("replication_factor", "1"), true, tables);
    }
}


text:
package com.jonathancolt.nicity.profile.latent;

/*
 * #%L
 * nicity-profile
 * %%
 * Copyright (C) 2013 Jonathan Colt
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

/**
 *
 */
public class Latent {

    private final ThreadLocal<LatentStack> latentStacks;
    private final String interfaceName;
    private final String className;
    private final String methodName;
    private long called;
    private long successlatency;
    private long failed;
    private long failedlatency;
    private final int hashCode;

    Latent(ThreadLocal<LatentStack> latentStacks, String interfaceName, String className, String methodName) {
        this.latentStacks = latentStacks;
        this.interfaceName = interfaceName;
        this.className = className;
        this.methodName = methodName;
        hashCode = interfaceName.hashCode() + className.hashCode() + methodName.hashCode();
    }

    public String getInterfaceName() {
        return interfaceName;
    }

    public String getClassName() {
        return className;
    }

    public String getMethodName() {
        return methodName;
    }

    public long getCalled() {
        return called;
    }

    public long getSuccesslatency() {
        return successlatency;
    }

    public long getFailed() {
        return failed;
    }

    public long getFailedlatency() {
        return failedlatency;
    }

    void enter(String tracerId) {
        latentStacks.get().enter(this, tracerId);
    }

    public void exit() {
        called++;
        successlatency = latentStacks.get().exit(this, successlatency);
    }

    public void failed() {
        failed++;
        failedlatency = latentStacks.get().failed(this,failedlatency);
    }

    @Override
    public String toString() {
        return className + "." + methodName + " latency=" + Math.max(successlatency, failedlatency);
    }

    @Override
    public int hashCode() {
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Latent other = (Latent) obj;
        if ((this.interfaceName == null) ? (other.interfaceName != null) : !this.interfaceName.equals(other.interfaceName)) {
            return false;
        }
        if ((this.className == null) ? (other.className != null) : !this.className.equals(other.className)) {
            return false;
        }
        if ((this.methodName == null) ? (other.methodName != null) : !this.methodName.equals(other.methodName)) {
            return false;
        }
        return true;
    }
}


text:
import pytest
from azure.keyvault.keys import ApiVersion, KeyClient

@pytest.mark.parametrize("version", ApiVersion)
def test_supported_version(version):
    """The client should be able to load generated code for every supported API version"""

    KeyClient("https://localhost", credential=object(), api_version=version)

def test_unsupported_version():
    """When given an unsupported API version, the client should raise an error listing supported versions"""

    with pytest.raises(NotImplementedError) as ex:
        client = KeyClient("https://localhost", credential=object(), api_version="nonsense")
    assert all(version.value in str(ex.value) for version in ApiVersion)


text:
from django import forms
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404
from account import models as amod
from . import templater
from django.contrib.auth.decorators import user_passes_test

@user_passes_test(lambda u: u.is_superuser)
def process_request(request):
  if request.user.is_authenticated():
    '''Shows all Users in the DB'''
    users = amod.User.objects.exclude(is_active= False).order_by('id')

    title = 'Active MyStuff Users'

    tvars = {
      'users': users,
      'title': title,
    }
    return templater.render_to_response(request, 'users.html', tvars)

  else:
    return HttpResponseRedirect("/account/please_sign_in/")

@user_passes_test(lambda u: u.is_superuser)
def process_request__staff(request):
  if request.user.is_authenticated():
    '''Shows all Users in the DB'''
    users = amod.User.objects.filter(is_staff = True).order_by('id')

    title = 'Active MyStuff Staff'

    tvars = {
      'users': users,
      'title': title,
    }
    return templater.render_to_response(request, 'users.html', tvars)

  else:
    return HttpResponseRedirect("/account/please_sign_in/")


text:
/**

    File:       bopen-02.c

    Project:    DCPU-16 Toolchain
    Component:  LibDCPU Test Suite

    Authors:    James Rhodes

    Description:    Tests the bopen() and bclose() methods
            to ensure that they correctly open and close
            files.

**/

#ifndef WIN32
#include <unistd.h>
#endif
#include <bfile.h>
#include "tests.h"

int bopen_02()
{
    BFILE* f;

    f = bfopen("nonexistant.blah", "wb");
    TEST_EXPECT(f != NULL);
    bfclose(f);
    unlink("nonexistant.blah");

    TEST_SUCCESS;
}


text:
<!DOCTYPE html>

<title>Matrix Admin</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css/bootstrap-responsive.min.css" />
<link rel="stylesheet" href="css/fullcalendar.css" />
<link rel="stylesheet" href="css/matrix-style.css" />
<link rel="stylesheet" href="css/matrix-media.css" />
<link href="font-awesome/css/font-awesome.css" rel="stylesheet" />
<link rel="stylesheet" href="css/jquery.gritter.css" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700,800' rel='stylesheet' type='text/css'>

  Welcome User

 My Profile

 My Tasks

 Log Out

Messages 5

new message

inbox

outbox

trash

Settings

Logout

  <input type="text" placeholder="Search here..."/>
  <button type="submit" class="tip-bottom" title="Search"></button>

 Dashboard

 Dashboard

  Charts & graphs

  Widgets

 Tables

 Full width

  Forms 3

Basic Form

Form with Validation

Form with Wizard

 Buttons & icons

 Eelements

  Addons 5

Dashboard2

Gallery

Calendar

Invoice

Chat option

  Error 4

Error 403

Error 404

Error 405

Error 500

 Monthly Bandwidth Transfer

      77%

21419.94 / 14000 MB

 Disk Space Usage

      87%

604.44 / 4000 MB

  Home

   20 My Dashboard

   Charts

  101 Widgets

   Tables

   Full width

   Forms

   Buttons

  Elements

   Calendar

   Error

Site Analytics

 2540 Total Users

 120 New Users

 656 Total Shop

 9540 Total Orders

 10 Pending Orders

 8540 Online Orders

Latest Posts

  By: john Deo / Date: 2 Aug 2012 / Time:09:27 AM

This is a much longer one that will go on for a few lines.It has multiple paragraphs and is full of waffle to pad out the comment.

  By: john Deo / Date: 2 Aug 2012 / Time:09:27 AM

This is a much longer one that will go on for a few lines.It has multiple paragraphs and is full of waffle to pad out the comment.

  By: john Deo / Date: 2 Aug 2012 / Time:09:27 AM

This is a much longer one that will go on for a few lines.Itaffle to pad out the comment.

                <button class="btn btn-warning btn-mini">View All</button>

To Do list

 Luanch This theme on Themeforest Alex

 Manage Pending Orders Today

 MAke your desk clean Admin

 Today we celebrate the theme 08.03.2013

 Manage all the orders 12.03.2013

Progress Box

  81% Clicks 567

  72% Uniquie Clicks 507

  53% Impressions 457

  3% Online Users 8

News updates

Lorem ipsum dolor sit amet, consectetur adipiscing elit. dolor sit amet, consectetur adipiscing eli

20jan

   Congratulation Maruti, Happy Birthday  many many happy returns of the day  11jan

   Maruti is a Responsive Admin theme But already everything was solved. It will ...  07Jan

   Envato approved Maruti Admin template i am very happy to approved by TF  05jan

   I am alwayse here if you have any question we glad that you choose our template  01jan

Chat Option

Online Users

 Alex

 Linda

 John3

 Mark

 Maxi

                <button class="btn btn-success">Send</button>

                <input type="text" name="msg-box" id="msg-box" />

Our Partner (Box with Fix height)

 John Deo

Web Desginer & creative Front end developer

 John Deo

Web Desginer & creative Front end developer

 John Deo

Web Desginer & creative Front end developer

Accordion Example 1

 It has multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.

Accordion Example 2

And is full of waffle to It has multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.

Accordion Example 3

 Waffle to It has multiple paragraphs and is full of waffle to pad out the comment. Usually, you just

Toggle, Open by default,

 This box is opened by default, paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.

Toggle, closed by default

 This box is now open

Toggle, closed by default

 This box is now open

Tab1

Tab2

Tab3

And is full of waffle to It has multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.multiple paragraphs and is full of waffle to pad out the comment.

And is full of waffle to It has multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.multiple paragraphs and is full of waffle to pad out the comment.

And is full of waffle to It has multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.multiple paragraphs and is full of waffle to pad out the comment.

 2013 © Matrix Admin. Brought to you by Themedesigner.in


text:
/* eslint no-path-concat: 0, func-names:0 */
var app = require('app');
var BrowserWindow = require('browser-window');
var Menu = require('menu');
var menu;
var template;

require('electron-debug')();
require('crash-reporter').start();

var mainWindow = null;

app.on('window-all-closed', function() {
  if (process.platform !== 'darwin') app.quit();
});

app.on('ready', function() {
  mainWindow = new BrowserWindow({ width: 1024, height: 728 });

  if (process.env.HOT) {
    mainWindow.loadUrl('file://' + __dirname + '/app/hot-dev-app.html');
  } else {
    mainWindow.loadUrl('file://' + __dirname + '/app/app.html');
  }

  mainWindow.on('closed', function() {
    mainWindow = null;
  });

  if (process.env.NODE_ENV === 'development') {
    mainWindow.openDevTools();
  }

  if (process.platform === 'darwin') {
    template = [{
      label: 'Electron',
      submenu: [{
        label: 'About ElectronReact',
        selector: 'orderFrontStandardAboutPanel:'
      }, {
        type: 'separator'
      }, {
        label: 'Services',
        submenu: []
      }, {
        type: 'separator'
      }, {
        label: 'Hide ElectronReact',
        accelerator: 'Command+H',
        selector: 'hide:'
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:'
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:'
      }, {
        type: 'separator'
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click: function() {
          app.quit();
        }
      }]
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:'
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:'
      }, {
        type: 'separator'
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:'
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:'
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:'
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:'
      }]
    }, {
      label: 'View',
      submenu: [{
        label: 'Reload',
        accelerator: 'Command+R',
        click: function() {
          mainWindow.restart();
        }
      }, {
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click: function() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle Developer Tools',
        accelerator: 'Alt+Command+I',
        click: function() {
          mainWindow.toggleDevTools();
        }
      }]
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      }, {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:'
      }, {
        type: 'separator'
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click: function() {
          require('shell').openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click: function() {
          require('shell').openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click: function() {
          require('shell').openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click: function() {
          require('shell').openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];

    menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O'
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click: function() {
          mainWindow.close();
        }
      }]
    }, {
      label: '&View',
      submenu: [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click: function() {
          mainWindow.restart();
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click: function() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click: function() {
          mainWindow.toggleDevTools();
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click: function() {
          require('shell').openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click: function() {
          require('shell').openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click: function() {
          require('shell').openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click: function() {
          require('shell').openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];
    menu = Menu.buildFromTemplate(template);
    mainWindow.setMenu(menu);
  }
});


text:
module.exports = function (RED) {
  const SERVICE_IDENTIFIER = 'speech-to-text';
  var temp = require('temp'),
    fs = require('fs'),
    fsp = require('fs').promises,
    fileType = require('file-type'),
    serviceutils = require('../../utilities/service-utils'),
    payloadutils = require('../../utilities/payload-utils'),
    responseutils = require('../../utilities/response-utils'),
    sttutils = require('./stt-utils'),
    service = serviceutils.getServiceCreds(SERVICE_IDENTIFIER),
    apikey = '', sApikey = '',
    endpoint = '',
    sEndpoint = 'https://stream.watsonplatform.net/speech-to-text/api';

  temp.track();

  // Require the Cloud Foundry Module to pull credentials from bound service
  // If they are found then the key and password will be stored in
  // the variable sApiket.
  //
  // This separation between is to allow
  // the end user to modify the credentials when the service is not bound.
  // Otherwise, once set credentials are never reset, resulting in a frustrated
  // user who, when he errenously enters bad credentials, can't figure out why
  // the edited ones are not being taken.

  if (service) {
    sApikey = service.apikey ? service.apikey : '';
    sEndpoint = service.url;
  }

  function executeCreateCustomisation(node, stt, params, msg) {
    return new Promise(function resolver(resolve, reject) {
      stt.createLanguageModel(params)
        .then((response) => {
          responseutils.parseResponseFor(msg, response, 'customization_id');
          resolve();
        })
        .catch((err) => {
          reject(err);
        })
    });
  }

  function executeListCustomisations(node, stt, params, msg) {
    return new Promise(function resolver(resolve, reject) {
      stt.listLanguageModels(params)
        .then((response) => {
          responseutils.parseResponseFor(msg, response, 'customizations');
          resolve();
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  function executeGetCustomisation(node, stt, params, msg) {
    return new Promise(function resolver(resolve, reject) {
      stt.getLanguageModel(params)
        .then((response) => {
          responseutils.parseResponseFor(msg, response, 'customization');
          resolve();
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  function executeDeleteCustomisation(node, stt, params, msg) {
    return new Promise(function resolver(resolve, reject) {
      stt.deleteLanguageModel(params)
        .then((response) => {
          msg['delcustomresponse'] = response;
          resolve();
        })
        .catch((err) => {
          reject(err);
        })
    });
  }

  function executeUpgradeCustomisation(node, stt, params, msg) {
    return new Promise(function resolver(resolve, reject) {
      stt.upgradeLanguageModel(params)
        .then((response) => {
          msg['updcustomresponse'] = response;
          resolve();
        })
        .catch((err) => {
          reject(err);
        })
    });
  }

  function executeResetCustomisation(node, stt, params, msg) {
    return new Promise(function resolver(resolve, reject) {
      stt.resetLanguageModel(params)
        .then((response) => {
          msg['rescustomresponse'] = response;
          resolve();
        })
        .catch((err) => {
          reject(err);
        })
    });
  }

  function executeAddCorpus(node, stt, params, msg) {
    return new Promise(function resolver(resolve, reject) {
      stt.addCorpus(params)
        .then((response) => {
          msg['addcorpusresponse'] = response;
          resolve();
        })
        .catch((err) => {
          reject(err);
        })
    });
  }

  function executeGetCorpora(node, stt, params, msg) {
    return new Promise(function resolver(resolve, reject) {
      stt.listCorpora(params)
      .then((response) => {
        responseutils.parseResponseFor(msg, response, 'corpora');
        resolve();
      })
      .catch((err) => {
        reject(err);
      })
    });
  }

  function executeGetCorpus(node, stt, params, msg) {
    return new Promise(function resolver(resolve, reject) {
      stt.getCorpus(params)
      .then((response) => {
        responseutils.parseResponseFor(msg, response, 'corpus');
        resolve();
      })
      .catch((err) => {
        reject(err);
      })
    });
  }

  function executeTrain(node, stt, params, msg) {
    return new Promise(function resolver(resolve, reject) {
      stt.trainLanguageModel(params)
      .then((response) => {
        msg['train'] = response;
        resolve();
      })
      .catch((err) => {
        reject(err);
      })
    });
  }

  function executeGetCustomWords(node, stt, params, msg) {
    return new Promise(function resolver(resolve, reject) {
      stt.listWords(params)
      .then((response) => {
        responseutils.parseResponseFor(msg, response, 'words');
        resolve();
      })
      .catch((err) => {
        reject(err);
      })
    });
  }

  function executeAddWords(node, stt, params, msg) {
    return new Promise(function resolver(resolve, reject) {
      stt.addWords(params)
      .then((response) => {
        msg['addwordsresponse'] = response;
        resolve();
      })
      .catch((err) => {
        reject(err);
      })
    });
  }

  function executeDeleteCorpus(node, stt, params, msg) {
    return new Promise(function resolver(resolve, reject) {
      stt.deleteCorpus(params)
      .then((response) => {
        msg['delcorpusresponse'] = response;
        resolve();
      })
      .catch((err) => {
        reject(err);
      })
    });
  }

  function executeDeleteWord(node, stt, params, msg) {
    return new Promise(function resolver(resolve, reject) {
      stt.deleteWord(params)
      .then((response) => {
        msg['delwordresponse'] = response;
        resolve();
      })
      .catch((err) => {
        reject(err);
      })
    });
  }

  function executeUnknownMethod(node, stt, params, msg) {
    return new Promise(function resolver(resolve, reject) {
      msg.error = 'Unable to process as unknown mode has been specified';
      reject(msg.error);
    });
  }

  function determineService() {
    return sttutils.determineService(apikey, endpoint);
  }

  function executeMethod(node, method, params, msg) {
    let stt = determineService();
    let p = null;

    node.status({fill:'blue', shape:'dot', text:'executing'});

    switch (method) {
    case 'createCustomisation':
      p = executeCreateCustomisation(node, stt, params, msg);
      break;
    case 'listCustomisations':
      p = executeListCustomisations(node, stt, params, msg);
      break;
    case 'getCustomisation':
      p = executeGetCustomisation(node, stt, params, msg);
      break;
    case 'deleteCustomisation':
      p = executeDeleteCustomisation(node, stt, params, msg);
      break;
    case 'resetCustomisation':
      p = executeResetCustomisation(node, stt, params, msg);
      break;
    case 'upgradeCustomisation':
      p = executeUpgradeCustomisation(node, stt, params, msg);
      break;
    case 'addCorpus':
      p = executeAddCorpus(node, stt, params, msg);
      break;
    case 'getCorpora':
      p = executeGetCorpora(node, stt, params, msg);
      break;
    case 'getCorpus':
      p = executeGetCorpus(node, stt, params, msg);
      break;
    case 'train':
      p = executeTrain(node, stt, params, msg);
      break;
    case 'listCustomWords':
      p = executeGetCustomWords(node, stt, params, msg);
      break;
    case 'addWords':
      p = executeAddWords(node, stt, params, msg);
      break;
    case 'deleteCorpus':
      p = executeDeleteCorpus(node, stt, params, msg);
      break;
    case 'deleteCustomWord':
      p = executeDeleteWord(node, stt, params, msg);
      break;
    default:
      p = executeUnknownMethod(node, stt, params, msg);
      break;
    }

    return p;
  }

  function paramsForNewCustom(config) {
    var params = {};

    if (config['stt-base-model']) {
      params['baseModelName'] = config['stt-base-model'];
    }
    if (config['stt-custom-model-name']) {
      params['name'] = config['stt-custom-model-name'];
    }
    if (config['stt-custom-model-description']) {
      params['description'] = config['stt-custom-model-description'];
    }

    return params;
  }

  function paramsForCorpus(config, method) {
    var params = {};

    if (config['stt-corpus-name']) {
      params['corpusName'] = config['stt-corpus-name'];
    }
    if (config['stt-custom-id']) {
      params['customizationId'] = config['stt-custom-id'];
    }
    if ('addCorpus' === method) {
      params['allowOverwrite'] = config['stt-allow-overwrite'];
    }

    return params;
  }

  function buildParams(msg, method, config) {
    var params = {};

    switch (method) {
    case 'createCustomisation':
      params = paramsForNewCustom(config);
      break;
    case 'listCustomisations':
      break;
    case 'deleteCustomWord':
      if (config['stt-word-name']) {
        params['wordName'] = config['stt-word-name'];
      }
      // Deliberate no break;
    case 'getCustomisation':
    case 'getCorpora':
    case 'train':
    case 'listCustomWords':
    case 'addWords':
    case 'deleteCustomisation':
    case 'upgradeCustomisation':
    case 'resetCustomisation':
      if (config['stt-custom-id']) {
        params['customizationId'] = config['stt-custom-id'];
      }
      break;
    case 'addCorpus':
    case 'getCorpus':
    case 'deleteCorpus':
      params = paramsForCorpus(config, method);
      break;
    }

    return params;
  }

  function setFileParams(method, params, msg) {
    switch (method) {
    case 'addCorpus':
      params.corpusFile = msg.payload;
      break;
    case 'addWords':
      params.words = msg.payload;
      break;
    }
    return params;
  }

  function loadFile(node, method, params, msg) {
    return new Promise(function resolver(resolve, reject) {
      temp.open({
        suffix: '.txt'
      }, function(err, info) {
        if (err) {
          node.status({
            fill: 'red',
            shape: 'dot',
            text: 'Error receiving the data buffer for training'
          });
          reject(err);
        }

        // Syncing up the asynchronous nature of the stream
        // so that the full file can be sent to the API.
        fsp.writeFile(info.path, msg.payload)
          .then(() => {
            switch (method) {
            case 'addCorpus':
              params.corpusFile = fs.createReadStream(info.path);
              break;
            case 'addWords':
              try {
                params.words = JSON.parse(fs.readFileSync(info.path, 'utf8'));
              } catch (err) {
                params.words = fs.createReadStream(info.path);
              }
            }
            resolve();
          })
          .catch((err) => {
            reject(err);
          })
      });

    });
  }

  function checkForFile(method) {
    switch (method) {
    case 'addCorpus':
    case 'addWords':
      return Promise.resolve(true);
    }
    return Promise.resolve(false);
  }

  // These are APIs that the node has created to allow it to dynamically fetch IBM Cloud
  // credentials, and also translation models. This allows the node to keep up to
  // date with new tranlations, without the need for a code update of this node.

  // Node RED Admin - fetch and set vcap services
  RED.httpAdmin.get('/watson-speech-to-text-v1-query-builder/vcap', function (req, res) {
    res.json(service ? {bound_service: true} : null);
  });

   // API used by widget to fetch available models
  RED.httpAdmin.get('/watson-speech-to-text-v1-query-builder/models', function (req, res) {
    endpoint = req.query.e ? req.query.e : sEndpoint;

    var stt = sttutils.initSTTService(req, sApikey, sEndpoint);

    stt.listModels({})
      .then((response) => {
        let models = response;
        if (response.result) {
          models = response.result;
        }
        res.json(models);
      })
      .catch((err) => {
        res.json(err);
      })
  });

  // This is the Speech to Text V1 Query Builder Node
  function Node (config) {
    RED.nodes.createNode(this, config);
    var node = this;

    this.on('input', function(msg, send, done) {
      var method = config['stt-custom-mode'],
        message = '',
        params = {};

      apikey = sApikey || this.credentials.apikey || config.apikey;

      endpoint = sEndpoint;
      if (config['service-endpoint']) {
        endpoint = config['service-endpoint'];
      }

      if (!apikey) {
        message = 'Missing Watson Speech to Text service credentials';
      } else if (!method || '' === method) {
        message = 'Required mode has not been specified';
      } else {
        params = buildParams(msg, method, config);
      }

      if (message) {
        payloadutils.reportError(node, msg, message);
        return;
      }

      checkForFile(method)
        .then((lookForBuffer) => {
          if (! lookForBuffer) {
            return Promise.resolve();
          } else if (msg.payload instanceof Buffer) {
            return loadFile(node, method, params, msg);
          } else {
            params = setFileParams(method, params, msg);
            return Promise.resolve();
          }
        })
        .then(() => {
          return executeMethod(node, method, params, msg)
        })
        .then(() => {
          node.status({});
          send(msg);
          temp.cleanup();
          done();
        })
        .catch((err) => {
          node.status({});
          let errMsg = payloadutils.reportError(node, msg, err);
          temp.cleanup();
          done(errMsg);
        });

    });
  }

  RED.nodes.registerType('watson-speech-to-text-v1-query-builder', Node, {
    credentials: {
      apikey: {type:'password'}
    }
  });

};


text:
namespace uvkc {
namespace benchmark {

// Sets data for a |device_image| via a CPU staging buffer by invoking
// |staging_buffer_setter| on the pointer pointing to the start of the CPU
// staging buffer.
//
// |device_image| is expected to have VK_IMAGE_USAGE_TRANSFER_DST_BIT bit.
//
// This function will discard the existing content in the image and transition
// it into |to_layout|.
absl::Status SetDeviceImageViaStagingBuffer(
    vulkan::Device *device, vulkan::Image *device_image,
    VkExtent3D image_dimensions, VkImageLayout to_layout,
    size_t buffer_size_in_bytes,
    const std::function<void(void *, size_t)> &staging_buffer_setter);

// Get data from a |device_image| via a CPU staging buffer by invoking
// |staging_buffer_getter| on the pointer pointing to the start of the CPU
// staging buffer.
//
// |device_image| is expected to have VK_IMAGE_USAGE_TRANSFER_SRC_BIT bit.
//
// This function will transition the image from |from_layout| to
// VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL.
absl::Status GetDeviceImageViaStagingBuffer(
    vulkan::Device *device, vulkan::Image *device_image,
    VkExtent3D image_dimensions, VkImageLayout from_layout,
    size_t buffer_size_in_bytes,
    const std::function<void(void *, size_t)> &staging_buffer_getter);

}  // namespace benchmark
}  // namespace uvkc

#endif  // UVKC_BENCHMARK_VULKAN_IMAGE_UTIL_H_


text:
@interface TestPlistViewController : HBBaseTableViewController

@end


text:
require 'rubygems/test_case'
require 'rubygems/server'
require 'stringio'

class Gem::Server

  attr_reader :server

end

class TestGemServer < Gem::TestCase

  def process_based_port
    0
  end

  def setup
    super

    @a1   = quick_gem 'a', '1'
    @a2   = quick_gem 'a', '2'
    @a3_p = quick_gem 'a', '3.a'

    @server = Gem::Server.new Gem.dir, process_based_port, false
    @req = WEBrick::HTTPRequest.new :Logger => nil
    @res = WEBrick::HTTPResponse.new :HTTPVersion => '1.0'
  end

  def test_doc_root_3
    orig_rdoc_version = Gem::RDoc.rdoc_version
    Gem::RDoc.instance_variable_set :@rdoc_version, Gem::Version.new('3.12')

    assert_equal '/doc_root/X-1/rdoc/index.html', @server.doc_root('X-1')

  ensure
    Gem::RDoc.instance_variable_set :@rdoc_version, orig_rdoc_version
  end

  def test_doc_root_4
    orig_rdoc_version = Gem::RDoc.rdoc_version
    Gem::RDoc.instance_variable_set :@rdoc_version, Gem::Version.new('4.0')

    assert_equal '/doc_root/X-1/', @server.doc_root('X-1')

  ensure
    Gem::RDoc.instance_variable_set :@rdoc_version, orig_rdoc_version
  end

  def test_have_rdoc_4_plus_eh
    orig_rdoc_version = Gem::RDoc.rdoc_version
    Gem::RDoc.instance_variable_set(:@rdoc_version, Gem::Version.new('4.0'))

    server = Gem::Server.new Gem.dir, 0, false
    assert server.have_rdoc_4_plus?

    Gem::RDoc.instance_variable_set :@rdoc_version, Gem::Version.new('3.12')

    server = Gem::Server.new Gem.dir, 0, false
    refute server.have_rdoc_4_plus?

    Gem::RDoc.instance_variable_set(:@rdoc_version,
                                    Gem::Version.new('4.0.0.preview2'))

    server = Gem::Server.new Gem.dir, 0, false
    assert server.have_rdoc_4_plus?
  ensure
    Gem::RDoc.instance_variable_set :@rdoc_version, orig_rdoc_version
  end

  def test_spec_dirs
    s = Gem::Server.new Gem.dir, process_based_port, false

    assert_equal [File.join(Gem.dir, 'specifications')], s.spec_dirs

    s = Gem::Server.new [Gem.dir, Gem.dir], process_based_port, false

    assert_equal [File.join(Gem.dir, 'specifications'),
                  File.join(Gem.dir, 'specifications')], s.spec_dirs
  end

  def test_latest_specs
    data = StringIO.new "GET /latest_specs.#{Gem.marshal_version} HTTP/1.0\r\n\r\n"
    @req.parse data

    Gem::Deprecate.skip_during do
      @server.latest_specs @req, @res
    end

    assert_equal 200, @res.status, @res.body
    assert_match %r| \d\d:\d\d:\d\d |, @res['date']
    assert_equal 'application/octet-stream', @res['content-type']
    assert_equal [['a', Gem::Version.new(2), Gem::Platform::RUBY]],
    Marshal.load(@res.body)
  end

  def test_latest_specs_gemdirs
    data = StringIO.new "GET /latest_specs.#{Gem.marshal_version} HTTP/1.0\r\n\r\n"
    dir = "#{@gemhome}2"

    spec = util_spec 'z', 9

    specs_dir = File.join dir, 'specifications'
    FileUtils.mkdir_p specs_dir

    File.open File.join(specs_dir, spec.spec_name), 'w' do |io|
      io.write spec.to_ruby
    end

    server = Gem::Server.new dir, process_based_port, false

    @req.parse data

    server.latest_specs @req, @res

    assert_equal 200, @res.status

    assert_equal [['z', v(9), Gem::Platform::RUBY]], Marshal.load(@res.body)
  end

  def test_latest_specs_gz
    data = StringIO.new "GET /latest_specs.#{Gem.marshal_version}.gz HTTP/1.0\r\n\r\n"
    @req.parse data

    Gem::Deprecate.skip_during do
      @server.latest_specs @req, @res
    end

    assert_equal 200, @res.status, @res.body
    assert_match %r| \d\d:\d\d:\d\d |, @res['date']
    assert_equal 'application/x-gzip', @res['content-type']
    assert_equal [['a', Gem::Version.new(2), Gem::Platform::RUBY]],
                 Marshal.load(Gem::Util.gunzip(@res.body))
  end

  def test_listen
    util_listen

    capture_io do
      @server.listen
    end

    assert_equal 1, @server.server.listeners.length
  end

  def test_listen_addresses
    util_listen

    capture_io do
      @server.listen %w[a b]
    end

    assert_equal 2, @server.server.listeners.length
  end

  def test_prerelease_specs
    data = StringIO.new "GET /prerelease_specs.#{Gem.marshal_version} HTTP/1.0\r\n\r\n"
    @req.parse data

    Gem::Deprecate.skip_during do
      @server.prerelease_specs @req, @res
    end

    assert_equal 200, @res.status, @res.body
    assert_match %r| \d\d:\d\d:\d\d |, @res['date']
    assert_equal 'application/octet-stream', @res['content-type']
    assert_equal [['a', v('3.a'), Gem::Platform::RUBY]],
                 Marshal.load(@res.body)
  end

  def test_prerelease_specs_gz
    data = StringIO.new "GET /prerelease_specs.#{Gem.marshal_version}.gz HTTP/1.0\r\n\r\n"
    @req.parse data

    Gem::Deprecate.skip_during do
      @server.prerelease_specs @req, @res
    end

    assert_equal 200, @res.status, @res.body
    assert_match %r| \d\d:\d\d:\d\d |, @res['date']
    assert_equal 'application/x-gzip', @res['content-type']
    assert_equal [['a', v('3.a'), Gem::Platform::RUBY]],
                 Marshal.load(Gem::Util.gunzip(@res.body))
  end

  def test_quick_gemdirs
    data = StringIO.new "GET /quick/Marshal.4.8/z-9.gemspec.rz HTTP/1.0\r\n\r\n"
    dir = "#{@gemhome}2"

    server = Gem::Server.new dir, process_based_port, false

    @req.parse data

    server.quick @req, @res

    assert_equal 404, @res.status

    spec = util_spec 'z', 9

    specs_dir = File.join dir, 'specifications'

    FileUtils.mkdir_p specs_dir

    File.open File.join(specs_dir, spec.spec_name), 'w' do |io|
      io.write spec.to_ruby
    end

    data.rewind

    req = WEBrick::HTTPRequest.new :Logger => nil
    res = WEBrick::HTTPResponse.new :HTTPVersion => '1.0'
    req.parse data

    server.quick req, res

    assert_equal 200, res.status
  end

  def test_quick_missing
    data = StringIO.new "GET /quick/Marshal.4.8/z-9.gemspec.rz HTTP/1.0\r\n\r\n"
    @req.parse data

    @server.quick @req, @res

    assert_equal 404, @res.status, @res.body
    assert_match %r| \d\d:\d\d:\d\d |, @res['date']
    assert_equal 'text/plain', @res['content-type']
    assert_equal 'No gems found matching "z-9"', @res.body
    assert_equal 404, @res.status
  end

  def test_quick_marshal_a_1_gemspec_rz
    data = StringIO.new "GET /quick/Marshal.#{Gem.marshal_version}/a-1.gemspec.rz HTTP/1.0\r\n\r\n"
    @req.parse data

    @server.quick @req, @res

    assert_equal 200, @res.status, @res.body
    assert @res['date']
    assert_equal 'application/x-deflate', @res['content-type']

    spec = Marshal.load Gem::Util.inflate(@res.body)
    assert_equal 'a', spec.name
    assert_equal Gem::Version.new(1), spec.version
  end

  def test_quick_marshal_a_1_mswin32_gemspec_rz
    quick_gem 'a', '1' do |s|
      s.platform = Gem::Platform.local
    end

    data = StringIO.new "GET /quick/Marshal.#{Gem.marshal_version}/a-1-#{Gem::Platform.local}.gemspec.rz HTTP/1.0\r\n\r\n"
    @req.parse data

    @server.quick @req, @res

    assert_equal 200, @res.status, @res.body
    assert @res['date']
    assert_equal 'application/x-deflate', @res['content-type']

    spec = Marshal.load Gem::Util.inflate(@res.body)
    assert_equal 'a', spec.name
    assert_equal Gem::Version.new(1), spec.version
    assert_equal Gem::Platform.local, spec.platform
  end

  def test_quick_marshal_a_3_a_gemspec_rz
    data = StringIO.new "GET /quick/Marshal.#{Gem.marshal_version}/a-3.a.gemspec.rz HTTP/1.0\r\n\r\n"
    @req.parse data

    @server.quick @req, @res

    assert_equal 200, @res.status, @res.body
    assert @res['date']
    assert_equal 'application/x-deflate', @res['content-type']

    spec = Marshal.load Gem::Util.inflate(@res.body)
    assert_equal 'a', spec.name
    assert_equal v('3.a'), spec.version
  end

  def test_quick_marshal_a_b_3_a_gemspec_rz
    quick_gem 'a-b', '3.a'

    data = StringIO.new "GET /quick/Marshal.#{Gem.marshal_version}/a-b-3.a.gemspec.rz HTTP/1.0\r\n\r\n"
    @req.parse data

    @server.quick @req, @res

    assert_equal 200, @res.status, @res.body
    assert @res['date']
    assert_equal 'application/x-deflate', @res['content-type']

    spec = Marshal.load Gem::Util.inflate(@res.body)
    assert_equal 'a-b', spec.name
    assert_equal v('3.a'), spec.version
  end

  def test_quick_marshal_a_b_1_3_a_gemspec_rz
    quick_gem 'a-b-1', '3.a'

    data = StringIO.new "GET /quick/Marshal.#{Gem.marshal_version}/a-b-1-3.a.gemspec.rz HTTP/1.0\r\n\r\n"
    @req.parse data

    @server.quick @req, @res

    assert_equal 200, @res.status, @res.body
    assert @res['date']
    assert_equal 'application/x-deflate', @res['content-type']

    spec = Marshal.load Gem::Util.inflate(@res.body)
    assert_equal 'a-b-1', spec.name
    assert_equal v('3.a'), spec.version
  end

  def test_rdoc
    data = StringIO.new "GET /rdoc?q=a HTTP/1.0\r\n\r\n"
    @req.parse data

    @server.rdoc @req, @res

    assert_equal 200, @res.status, @res.body
    assert_match %r|No documentation found|, @res.body
    assert_equal 'text/html', @res['content-type']
  end

  def test_root
    data = StringIO.new "GET / HTTP/1.0\r\n\r\n"
    @req.parse data

    @server.root @req, @res

    assert_equal 200, @res.status, @res.body
    assert_match %r| \d\d:\d\d:\d\d |, @res['date']
    assert_equal 'text/html', @res['content-type']
  end

  def test_root_gemdirs
    data = StringIO.new "GET / HTTP/1.0\r\n\r\n"
    dir = "#{@gemhome}2"

    spec = util_spec 'z', 9

    specs_dir = File.join dir, 'specifications'
    FileUtils.mkdir_p specs_dir

    File.open File.join(specs_dir, spec.spec_name), 'w' do |io|
      io.write spec.to_ruby
    end

    server = Gem::Server.new dir, process_based_port, false

    @req.parse data

    server.root @req, @res

    assert_equal 200, @res.status
    assert_match 'z 9', @res.body
  end

  def test_xss_homepage_fix_289313
    data = StringIO.new "GET / HTTP/1.0\r\n\r\n"
    dir = "#{@gemhome}2"

    spec = util_spec 'xsshomepagegem', 1
    spec.homepage = "javascript:confirm(document.domain)"

    specs_dir = File.join dir, 'specifications'
    FileUtils.mkdir_p specs_dir

    open File.join(specs_dir, spec.spec_name), 'w' do |io|
      io.write spec.to_ruby
    end

    server = Gem::Server.new dir, process_based_port, false

    @req.parse data

    server.root @req, @res

    assert_equal 200, @res.status
    assert_match 'xsshomepagegem 1', @res.body

    # This verifies that the homepage for this spec is not displayed and is set to ".", because it's not a
    # valid HTTP/HTTPS URL and could be unsafe in an HTML context.  We would prefer to throw an exception here,
    # but spec.homepage is currently free form and not currently required to be a URL, this behavior may be
    # validated in future versions of Gem::Specification.
    #
    # There are two variant we're checking here, one where rdoc is not present, and one where rdoc is present in the same regex:
    #
    # Variant #1 - rdoc not installed
    #
    #   xsshomepagegem 1
    #
    #
    #  [rdoc]
    #
    #
    #
    #  [www]
    #
    # Variant #2 - rdoc installed
    #
    #   xsshomepagegem 1
    #
    #
    #  \[rdoc\]<\/a>
    #
    #
    #
    #  [www]
    regex_match = /xsshomepagegem 1<\/b>\s+(\[rdoc\]<\/span>|\[rdoc\]<\/a>)\s+\[www\]<\/a>/
    assert_match regex_match, @res.body
  end

  def test_invalid_homepage
    data = StringIO.new "GET / HTTP/1.0\r\n\r\n"
    dir = "#{@gemhome}2"

    spec = util_spec 'invalidhomepagegem', 1
    spec.homepage = "notavalidhomepageurl"

    specs_dir = File.join dir, 'specifications'
    FileUtils.mkdir_p specs_dir

    open File.join(specs_dir, spec.spec_name), 'w' do |io|
      io.write spec.to_ruby
    end

    server = Gem::Server.new dir, process_based_port, false

    @req.parse data

    server.root @req, @res

    assert_equal 200, @res.status
    assert_match 'invalidhomepagegem 1', @res.body

    # This verifies that the homepage for this spec is not displayed and is set to ".", because it's not a
    # valid HTTP/HTTPS URL and could be unsafe in an HTML context.  We would prefer to throw an exception here,
    # but spec.homepage is currently free form and not currently required to be a URL, this behavior may be
    # validated in future versions of Gem::Specification.
    #
    # There are two variant we're checking here, one where rdoc is not present, and one where rdoc is present in the same regex:
    #
    # Variant #1 - rdoc not installed
    #
    #   invalidhomepagegem 1
    #
    #
    #  [rdoc]
    #
    #
    #
    #  [www]
    #
    # Variant #2 - rdoc installed
    #
    #   invalidhomepagegem 1
    #
    #
    #  \[rdoc\]<\/a>
    #
    #
    #
    #  [www]
    regex_match = /invalidhomepagegem 1<\/b>\s+(\[rdoc\]<\/span>|\[rdoc\]<\/a>)\s+\[www\]<\/a>/
    assert_match regex_match, @res.body
  end

  def test_valid_homepage_http
    data = StringIO.new "GET / HTTP/1.0\r\n\r\n"
    dir = "#{@gemhome}2"

    spec = util_spec 'validhomepagegemhttp', 1
    spec.homepage = "http://rubygems.org"

    specs_dir = File.join dir, 'specifications'
    FileUtils.mkdir_p specs_dir

    open File.join(specs_dir, spec.spec_name), 'w' do |io|
      io.write spec.to_ruby
    end

    server = Gem::Server.new dir, process_based_port, false

    @req.parse data

    server.root @req, @res

    assert_equal 200, @res.status
    assert_match 'validhomepagegemhttp 1', @res.body

    regex_match = /validhomepagegemhttp 1<\/b>\s+(\[rdoc\]<\/span>|\[rdoc\]<\/a>)\s+\[www\]<\/a>/
    assert_match regex_match, @res.body
  end

  def test_valid_homepage_https
    data = StringIO.new "GET / HTTP/1.0\r\n\r\n"
    dir = "#{@gemhome}2"

    spec = util_spec 'validhomepagegemhttps', 1
    spec.homepage = "https://rubygems.org"

    specs_dir = File.join dir, 'specifications'
    FileUtils.mkdir_p specs_dir

    open File.join(specs_dir, spec.spec_name), 'w' do |io|
      io.write spec.to_ruby
    end

    server = Gem::Server.new dir, process_based_port, false

    @req.parse data

    server.root @req, @res

    assert_equal 200, @res.status
    assert_match 'validhomepagegemhttps 1', @res.body

    regex_match = /validhomepagegemhttps 1<\/b>\s+(\[rdoc\]<\/span>|\[rdoc\]<\/a>)\s+\[www\]<\/a>/
    assert_match regex_match, @res.body
  end

  def test_specs
    data = StringIO.new "GET /specs.#{Gem.marshal_version} HTTP/1.0\r\n\r\n"
    @req.parse data

    @server.specs @req, @res

    assert_equal 200, @res.status, @res.body
    assert_match %r| \d\d:\d\d:\d\d |, @res['date']
    assert_equal 'application/octet-stream', @res['content-type']

    assert_equal [['a', Gem::Version.new(1), Gem::Platform::RUBY],
                  ['a', Gem::Version.new(2), Gem::Platform::RUBY],
                  ['a', v('3.a'), Gem::Platform::RUBY]],
                 Marshal.load(@res.body)
  end

  def test_specs_gemdirs
    data = StringIO.new "GET /specs.#{Gem.marshal_version} HTTP/1.0\r\n\r\n"
    dir = "#{@gemhome}2"

    spec = util_spec 'z', 9

    specs_dir = File.join dir, 'specifications'
    FileUtils.mkdir_p specs_dir

    File.open File.join(specs_dir, spec.spec_name), 'w' do |io|
      io.write spec.to_ruby
    end

    server = Gem::Server.new dir, process_based_port, false

    @req.parse data

    server.specs @req, @res

    assert_equal 200, @res.status

    assert_equal [['z', v(9), Gem::Platform::RUBY]], Marshal.load(@res.body)
  end

  def test_specs_gz
    data = StringIO.new "GET /specs.#{Gem.marshal_version}.gz HTTP/1.0\r\n\r\n"
    @req.parse data

    @server.specs @req, @res

    assert_equal 200, @res.status, @res.body
    assert_match %r| \d\d:\d\d:\d\d |, @res['date']
    assert_equal 'application/x-gzip', @res['content-type']

    assert_equal [['a', Gem::Version.new(1), Gem::Platform::RUBY],
                  ['a', Gem::Version.new(2), Gem::Platform::RUBY],
                  ['a', v('3.a'), Gem::Platform::RUBY]],
                 Marshal.load(Gem::Util.gunzip(@res.body))
  end

  def test_uri_encode
    url_safe = @server.uri_encode 'http://rubyonrails.org/">malicious_content'
    assert_equal url_safe, 'http://rubyonrails.org/%22%3Emalicious_content%3C/a%3E'
  end

  # Regression test for issue #1793: incorrect URL encoding.
  # Checking that no URLs have had '://' incorrectly encoded
  def test_regression_1793
    data = StringIO.new "GET / HTTP/1.0\r\n\r\n"
    @req.parse data

    @server.root @req, @res

    refute_match %r|%3A%2F%2F|, @res.body
  end

  def util_listen
    webrick = Object.new
    webrick.instance_variable_set :@listeners, []
    def webrick.listeners() @listeners end
    def webrick.listen(host, port)
      socket = Object.new
      socket.instance_variable_set :@host, host
      socket.instance_variable_set :@port, port
      def socket.addr() [nil, @port, @host] end
      @listeners << socket
    end

    @server.instance_variable_set :@server, webrick
  end

end


text:
#!/bin/bash

#Break execution on any error received
set -e

#Locally suppress stderr to avoid raising not relevant messages
exec 3>&2
exec 2> /dev/null
con_dev=$(ls /dev/video* | wc -l)
exec 2>&3

#Parse user inputs
reset_driver=0
xhci_patch=0
build_usbcore_modules=0
rebuild_ko=0
debug_uvc=0
retpoline_retrofit=0

#Parse input
while test $# -gt 0; do
  case "$1" in
  --help)
		;&
	-h)
		echo "Parse user-provided flags"
		echo "[Flag]                  [Operation]"
		echo " "
		echo "options:"
		echo "-h, --help              Show script activation flags"
		echo "reset                   Remove custom kernel patches and rebuild ko with Ubuntu stock driver"
		echo "xhci-patch              Rebuild XHCI host controller modules to retrofit kernel fixes. Applicable for Kernel 4.4 only"
		echo "build_usbcore_modules   Rebuilds usbcore/usbhost kernel modules"
		echo "ko                      Rebuild modified kernel modules w/o modifying the source tree"
		echo "uvc_dbg                 Add profyling messages to uvcvideo and videobuf2 modules"
		exit 0
		;;
	reset)
		reset_driver=1; shift;;
	build_usbcore_modules)
		build_usbcore_modules=1 ;& # fallthrough: usbcore implies xhci
	xhci-patch)
		xhci_patch=1; shift ;;
	ko)
		rebuild_ko=1; shift ;;
	uvc_dbg)
		debug_uvc=1;  shift ;;
	*)
		echo -e "\e[36mUnrecognized flag:  $1\e[0m"; shift;;
  esac
done

if [ $con_dev -ne 0 ];
then
	echo -e "\e[32m"
	read -p "Remove all RealSense cameras attached. Hit any key when ready"
	echo -e "\e[0m"
fi

#Include usability functions
source ./scripts/patch-utils.sh

# Get the required tools and headers to build the kernel
sudo apt-get install linux-headers-generic build-essential git bc -y
#Packages to build the patched modules
require_package libusb-1.0-0-dev
require_package libssl-dev

LINUX_BRANCH=$(uname -r)
#Get kernel major.minor
IFS='.' read -a kernel_version <<< ${LINUX_BRANCH}
k_maj_min=$((${kernel_version[0]}*100 + ${kernel_version[1]}))
if [[ ( ${xhci_patch} -eq 1 ) && ( ${k_maj_min} -ne 404 ) ]]; then
	echo -e "\e[43mThe xhci_patch flag is compatible with LTS branch 4.4 only, currently selected kernel is $(uname -r)\e[0m"
	exit 1
fi

# Construct branch name from distribution codename {xenial,bionic,..} and kernel version
ubuntu_codename=`. /etc/os-release; echo ${UBUNTU_CODENAME/*, /}`
if [ -z "${ubuntu_codename}" ];
then
	# Trusty Tahr shall use xenial code base
	ubuntu_codename="xenial"
	retpoline_retrofit=1
fi

kernel_branch=$(choose_kernel_branch ${LINUX_BRANCH} ${ubuntu_codename})
kernel_name="ubuntu-${ubuntu_codename}-$kernel_branch"
echo -e "\e[32mCreate patches workspace in \e[93m${kernel_name} \e[32mfolder\n\e[0m"

#Distribution-specific packages
if { [ ${ubuntu_codename} == "bionic" ] || [ ${ubuntu_codename} == "focal" ];  } ;
then
	require_package libelf-dev
	require_package elfutils
	#Ubuntu 18.04 kernel 4.18 + 20.04/ 5.4
	require_package bison
	require_package flex
fi

# Get the linux kernel and change into source tree
if [ ! -d ${kernel_name} ]; then
	mkdir ${kernel_name}
	cd ${kernel_name}
	git init
	git remote add origin git://kernel.ubuntu.com/ubuntu/ubuntu-${ubuntu_codename}.git
	cd ..
fi

cd ${kernel_name}

if [ $rebuild_ko -eq 0 ];
then
	#Search the repository for the tag that matches the mmaj.min.patch-build of Ubuntu kernel
	kernel_full_num=$(echo $LINUX_BRANCH | cut -d '-' -f 1,2)
	kernel_git_tag=$(git ls-remote --tags origin | grep "${kernel_full_num}\." | grep '[^^{}]$' | tail -n 1 | awk -F/ '{print $NF}')
	echo -e "\e[32mFetching Ubuntu LTS tag \e[47m${kernel_git_tag}\e[0m \e[32m to the local kernel sources folder\e[0m"
	git fetch origin tag ${kernel_git_tag} --no-tags

	# Verify that there are no trailing changes., warn the user to make corrective action if needed
	if [ $(git status | grep 'modified:' | wc -l) -ne 0 ];
	then
		echo -e "\e[36mThe kernel has modified files:\e[0m"
		git status | grep 'modified:'
		echo -e "\e[36mProceeding will reset all local kernel changes. Press 'n' within 3 seconds to abort the operation"
		set +e
		read -n 1 -t 3 -r -p "Do you want to proceed? [Y/n]" response
		set -e
		response=${response,,}    # tolower
		if [[ $response =~ ^(n|N)$ ]];
		then
			echo -e "\e[41mScript has been aborted on user requiest. Please resolve the modified files are rerun\e[0m"
			exit 1
		else
			echo -e "\e[0m"
			printf "Resetting local changes in %s folder\n " ${kernel_name}
			git reset --hard
		fi
	fi

	echo -e "\e[32mSwitching to LTS tag ${kernel_git_tag}\e[0m"
	git checkout ${kernel_git_tag}

	if [ $reset_driver -eq 1 ];
	then
		echo -e "\e[43mUser requested to rebuild and reinstall ubuntu-${ubuntu_codename} stock drivers\e[0m"
	else
		# Patching kernel for RealSense devices
		echo -e "\e[32mApplying patches for \e[36m${ubuntu_codename}-${kernel_branch}\e[32m line\e[0m"
		echo -e "\e[32mApplying realsense-uvc patch\e[0m"
		patch -p1 < ../scripts/realsense-camera-formats-${ubuntu_codename}-${kernel_branch}.patch || patch -p1 < ../scripts/realsense-camera-formats-${ubuntu_codename}-master.patch
		echo -e "\e[32mApplying realsense-metadata patch\e[0m"
		patch -p1 < ../scripts/realsense-metadata-${ubuntu_codename}-${kernel_branch}.patch || patch -p1 < ../scripts/realsense-metadata-${ubuntu_codename}-master.patch
		echo -e "\e[32mApplying realsense-hid patch\e[0m"
		patch -p1 < ../scripts/realsense-hid-${ubuntu_codename}-${kernel_branch}.patch || patch -p1 < ../scripts/realsense-hid-${ubuntu_codename}-master.patch
		echo -e "\e[32mApplying realsense-powerlinefrequency-fix patch\e[0m"
		patch -p1 < ../scripts/realsense-powerlinefrequency-control-fix.patch
		# Applying 3rd-party patch that affects USB2 behavior
		# See reference https://patchwork.kernel.org/patch/9907707/
		if [ ${k_maj_min} -lt 418 ];
		then
			echo -e "\e[32mRetrofit UVC bug fix rectified in 4.18+\e[0m"
			if patch -N --dry-run -p1 < ../scripts/v1-media-uvcvideo-mark-buffer-error-where-overflow.patch; then
				patch -N -p1 < ../scripts/v1-media-uvcvideo-mark-buffer-error-where-overflow.patch
			else
				echo -e "\e[36m  Skip the patch - it is already found in the source tree\e[0m"
			fi
		fi
		if [ $xhci_patch -eq 1 ]; then
			echo -e "\e[32mApplying streamoff hotfix patch in videobuf2-core\e[0m"
			patch -p1 < ../scripts/01-Backport-streamoff-vb2-core-hotfix.patch
			echo -e "\e[32mApplying 01-xhci-Add-helper-to-get-hardware-dequeue-pointer-for patch\e[0m"
			patch -p1 < ../scripts/01-xhci-Add-helper-to-get-hardware-dequeue-pointer-for.patch
			echo -e "\e[32mApplying 02-xhci-Add-stream-id-to-to-xhci_dequeue_state-structur patch\e[0m"
			patch -p1 < ../scripts/02-xhci-Add-stream-id-to-to-xhci_dequeue_state-structur.patch
			echo -e "\e[32mApplying 03-xhci-Find-out-where-an-endpoint-or-stream-stopped-fr patch\e[0m"
			patch -p1 < ../scripts/03-xhci-Find-out-where-an-endpoint-or-stream-stopped-fr.patch
			echo -e "\e[32mApplying 04-xhci-remove-unused-stopped_td-pointer patch\e[0m"
			patch -p1 < ../scripts/04-xhci-remove-unused-stopped_td-pointer.patch
		fi
		echo -e "\e[32mIncrease UVC_URBs in uvcvideo\e[0m"
		patch -p1 < ../scripts/uvcvideo_increase_UVC_URBS.patch
		if [ $debug_uvc -eq 1 ]; then
			echo -e "\e[32mApplying uvcvideo and videobuf2 debug patch\e[0m"
			patch -p1 < ../scripts/uvc_debug.patch
		fi
	fi

	#Copy configuration
	sudo cp /usr/src/linux-headers-$(uname -r)/.config .
	sudo cp /usr/src/linux-headers-$(uname -r)/Module.symvers .

	# Basic build for kernel modules
	echo -e "\e[32mPrepare kernel modules configuration\e[0m"
	#Retpoline script manual retrieval. based on https://github.com/IntelRealSense/librealsense/issues/1493
	#Required since the retpoline patches were introduced into Ubuntu kernels
	if [ ! -f scripts/ubuntu-retpoline-extract-one ]; then
		pwd
		for f in $(find . -name 'retpoline-extract-one'); do cp ${f} scripts/ubuntu-retpoline-extract-one; done;
		echo $$$
	fi

	#Reuse current kernel configuration. Assign default values to newly-introduced options.
	sudo make olddefconfig modules_prepare
	#Replacement of  USBcore modules implies usbcore is modular
	[ ${build_usbcore_modules} -eq 1 ] && sudo make menuconfig modules_prepare

	#Vermagic identity is required
	sudo sed -i "s/\".*\"/\"$LINUX_BRANCH\"/g" ./include/generated/utsrelease.h
	sudo sed -i "s/.*/$LINUX_BRANCH/g" ./include/config/kernel.release
	#Patch for Trusty Tahr (Ubuntu 14.05) with GCC not retrofitted with the retpoline patch.
	[ $retpoline_retrofit -eq 1 ] && sudo sed -i "s/#ifdef RETPOLINE/#if (1)/g" ./include/linux/vermagic.h

	if [[ ( $xhci_patch -eq 1 ) && ( $build_usbcore_modules -eq 0 ) ]]; then
		sudo make -j$(($(nproc)-1))
		sudo make modules -j$(($(nproc)-1))
		sudo make modules_install -j$(($(nproc)-1))
		sudo make install
		echo -e "\e[92m\n\e[1m`sudo make kernelrelease` Kernel has been successfully installed."
		echo -e "\e[92m\n\e[1mScript has completed. Please reboot and load the newly installed Kernel from GRUB list.\n\e[0m"
	exit 0
	fi
fi # rebuild_ko==0

# Build the uvc, accel and gyro modules
KBASE=`pwd`
cd drivers/media/usb/uvc
sudo cp $KBASE/Module.symvers .

echo -e "\e[32mCompiling uvc module\e[0m"
sudo make -j -C $KBASE M=$KBASE/drivers/media/usb/uvc/ modules
echo -e "\e[32mCompiling accelerometer and gyro modules\e[0m"
sudo make -j -C $KBASE M=$KBASE/drivers/iio/accel modules
sudo make -j -C $KBASE M=$KBASE/drivers/iio/gyro modules
echo -e "\e[32mCompiling v4l2-core modules\e[0m"
sudo make -j -C $KBASE M=$KBASE/drivers/media/v4l2-core modules
if [[ ( $xhci_patch -eq 1 ) || ( $debug_uvc -eq 1 ) ]]; then
	echo -e "\e[32mCompiling media/common modules\e[0m"
	sudo make -j -C $KBASE M=$KBASE/drivers/media/common/videobuf2 modules
fi

# Copy the patched modules to a  location
sudo cp $KBASE/drivers/media/usb/uvc/uvcvideo.ko ~/$LINUX_BRANCH-uvcvideo.ko
sudo cp $KBASE/drivers/iio/accel/hid-sensor-accel-3d.ko ~/$LINUX_BRANCH-hid-sensor-accel-3d.ko
sudo cp $KBASE/drivers/iio/gyro/hid-sensor-gyro-3d.ko ~/$LINUX_BRANCH-hid-sensor-gyro-3d.ko
sudo cp $KBASE/drivers/media/v4l2-core/videodev.ko ~/$LINUX_BRANCH-videodev.ko
if [[ ( $xhci_patch -eq 1 ) || ( $debug_uvc -eq 1 ) ]]; then
	sudo cp $KBASE/drivers/media/common/videobuf2/videobuf2-common.ko ~/$LINUX_BRANCH-videobuf2-common.ko
	sudo cp $KBASE/drivers/media/common/videobuf2/videobuf2-v4l2.ko ~/$LINUX_BRANCH-videobuf2-v4l2.ko
fi

if [ $build_usbcore_modules -eq 1 ]; then
	sudo make -j -C $KBASE M=$KBASE/drivers/usb/core modules
	sudo make -j -C $KBASE M=$KBASE/drivers/usb/host modules
	sudo make -j -C $KBASE M=$KBASE/drivers/hid/usbhid modules
	sudo cp $KBASE/drivers/media/v4l2-core/videobuf2-v4l2.ko ~/$LINUX_BRANCH-videobuf2-v4l2.ko
	sudo cp $KBASE/drivers/media/v4l2-core/videobuf2-core.ko ~/$LINUX_BRANCH-videobuf2-core.ko
	sudo cp $KBASE/drivers/media/v4l2-core/v4l2-common.ko ~/$LINUX_BRANCH-v4l2-common.ko
	sudo cp $KBASE/drivers/usb/core/usbcore.ko ~/$LINUX_BRANCH-usbcore.ko
	sudo cp $KBASE/drivers/usb/host/ehci-hcd.ko ~/$LINUX_BRANCH-ehci-hcd.ko
	sudo cp $KBASE/drivers/usb/host/ehci-pci.ko ~/$LINUX_BRANCH-ehci-pci.ko
	sudo cp $KBASE/drivers/usb/host/xhci-hcd.ko ~/$LINUX_BRANCH-xhci-hcd.ko
	sudo cp $KBASE/drivers/usb/host/xhci-pci.ko ~/$LINUX_BRANCH-xhci-pci.ko
	sudo cp $KBASE/drivers/hid/usbhid/usbhid.ko ~/$LINUX_BRANCH-usbhid.ko
fi

echo -e "\e[32mPatched kernels modules were created successfully\n\e[0m"

# Load the newly-built modules
# As a precausion start with unloading the core uvcvideo:
try_unload_module uvcvideo
try_unload_module videobuf2_v4l2
[ ${k_maj_min} -ge 500 ] && try_unload_module videobuf2_common
try_unload_module videodev

if [ $build_usbcore_modules -eq 1 ]; then
	echo -e "\e[32mReplacing USB Core modules\e[0m"

	try_unload_module videobuf2_core
	try_unload_module v4l2_common

	#Replace usb subsystem modules
	try_unload_module usbhid
	try_unload_module xhci-pci
	try_unload_module xhci-hcd
	try_unload_module ehci-pci
	try_unload_module ehci-hcd

	try_module_insert usbcore				~/$LINUX_BRANCH-usbcore.ko 				/lib/modules/`uname -r`/kernel/drivers/usb/core/usbcore.ko
	try_module_insert ehci-hcd				~/$LINUX_BRANCH-ehci-hcd.ko 			/lib/modules/`uname -r`/kernel/drivers/usb/host/ehci-hcd.ko
	try_module_insert ehci-pci				~/$LINUX_BRANCH-ehci-pci.ko 			/lib/modules/`uname -r`/kernel/drivers/usb/host/ehci-pci.ko
	try_module_insert xhci-hcd				~/$LINUX_BRANCH-xhci-hcd.ko 			/lib/modules/`uname -r`/kernel/drivers/usb/host/xhci-hcd.ko
	try_module_insert xhci-pci				~/$LINUX_BRANCH-xhci-pci.ko 			/lib/modules/`uname -r`/kernel/drivers/usb/host/xhci-pci.ko

	try_module_insert videodev				~/$LINUX_BRANCH-videodev.ko 			/lib/modules/`uname -r`/kernel/drivers/media/v4l2-core/videodev.ko
	try_module_insert v4l2-common			~/$LINUX_BRANCH-v4l2-common.ko			/lib/modules/`uname -r`/kernel/drivers/media/v4l2-core/v4l2-common.ko

	try_module_insert videobuf2_core		~/$LINUX_BRANCH-videobuf2-core.ko		/lib/modules/`uname -r`/kernel/drivers/media/v4l2-core/videobuf2-core.ko
	try_module_insert videobuf2_v4l2		~/$LINUX_BRANCH-videobuf2-v4l2.ko		/lib/modules/`uname -r`/kernel/drivers/media/v4l2-core/videobuf2-v4l2.ko
fi

try_module_insert videodev				~/$LINUX_BRANCH-videodev.ko 			/lib/modules/`uname -r`/kernel/drivers/media/v4l2-core/videodev.ko
if [[ ( ${k_maj_min} -ge 500 ) && ( $debug_uvc -eq 1 ) ]]; then
	try_module_insert videobuf2-common		~/$LINUX_BRANCH-videobuf2-common.ko 	/lib/modules/`uname -r`/kernel/drivers/media/common/videobuf2/videobuf2-common.ko
fi
try_module_insert uvcvideo				~/$LINUX_BRANCH-uvcvideo.ko 			/lib/modules/`uname -r`/kernel/drivers/media/usb/uvc/uvcvideo.ko
try_module_insert hid_sensor_accel_3d 	~/$LINUX_BRANCH-hid-sensor-accel-3d.ko 	/lib/modules/`uname -r`/kernel/drivers/iio/accel/hid-sensor-accel-3d.ko
try_module_insert hid_sensor_gyro_3d	~/$LINUX_BRANCH-hid-sensor-gyro-3d.ko 	/lib/modules/`uname -r`/kernel/drivers/iio/gyro/hid-sensor-gyro-3d.ko

echo -e "\e[92m\n\e[1mScript has completed. Please consult the installation guide for further instruction.\n\e[0m"


text:
import os.path
import sys

from config import UserConfig

config = UserConfig()

BASEDIR = config.BASEDIR
WHITE_SPACE = config.WHITE_SPACE
SQLALCHEMY_MIGRATE_REPO = config.SQLALCHEMY_MIGRATE_REPO

from controller_generator import generate_controller

def add_model(model_name, model_components):
    # This is used to add model to the model file.

    # Get the current model file and open it for writing.
    model_path = os.path.join(BASEDIR, "app/models/" + model_name.lower() + ".py")
    init_path = os.path.join(BASEDIR, "app/models/__init__.py")
    model_file = open(model_path, 'w')

    # Write the class definition.
    model_file.write('from app import db\n')
    model_file.write('from helpers import json_date_format\n\n')
    model_file.write('class ' + model_name.title() + '(db.Model):\n')
    model_file.write(WHITE_SPACE+'id = db.Column(db.Integer, primary_key=True)\n')

    ## Add the model fields.
    ### First check for the data types and standardize it.
    for component in model_components:
        in_type = component['field_property'][0].lower()
        ### The database field type based on http://docs.sqlalchemy.org/en/rel_0_7/core/types.html#types-generic.
        if in_type == 'biginteger' or in_type == 'bigint':
            data_type = 'BigInteger'
        elif in_type == 'binary':
            data_type = 'Binary'
        elif in_type == 'blob':
            data_type = 'BLOB'
        elif in_type == 'boolean':
            data_type = 'Boolean'
        elif in_type == 'date':
            data_type = 'Date'
        elif in_type == 'datetime':
            data_type = 'DateTime'
        elif in_type == 'enum':
            data_type = 'Enum'
        elif in_type == 'float':
            data_type = 'Float'
        elif in_type=='int' or in_type=='integer':
            data_type = 'Integer'
        elif in_type == 'interval':
            data_type = 'Interval'
        elif in_type == 'largebinary':
            data_type = 'LargeBinary'
        elif in_type == 'numeric':
            data_type = 'Numeric'
        elif in_type == 'pickletype':
            data_type = 'PickleType'
        elif in_type == 'schematype':
            data_type = 'SchemaType'
        elif in_type == 'smallinteger' or in_type == 'smallint':
            data_type = 'SmallInteger'
        elif in_type == 'string':
            data_type = 'String'
        elif in_type == 'text':
            data_type = 'Text'
        elif in_type == 'time':
            data_type = 'Time'
        elif in_type == 'unicode':
            data_type = 'Unicode'
        elif in_type == 'unicodetext':
            data_type = 'UnicodeText'
        else:

    ### If the data type did not match any of the existing data types, display error message and quit the program.
            print 'Data type ' + component['field_property'][0] + ' not found. Please refer to SQLAlchemy documentation for valid data types.'
            sys.exit()

    ### If it matches write the model fields into the model files.
        if len(component['field_property']) == 2:
            model_file.write(WHITE_SPACE + component['field_name'].lower() + ' = db.Column(db.' + data_type + '(' + component['field_property'][1] + '))\n')
        else:
            model_file.write(WHITE_SPACE + component['field_name'].lower() + ' = db.Column(db.' + data_type + ')\n')
    model_file.write(WHITE_SPACE + 'created_on = db.Column(db.DateTime)\n')
    model_file.write(WHITE_SPACE + 'last_updated_on = db.Column(db.DateTime)\n')

    ## Create the class method for data transfer object (dto) for JSON representation.
    model_file.write('\n')
    model_file.write(WHITE_SPACE + '# data transfer object to form JSON\n')
    model_file.write(WHITE_SPACE + 'def dto(self):\n')
    model_file.write(WHITE_SPACE + WHITE_SPACE + 'return dict(\n')

    ### Add the json component for all fields.
    model_file.write(WHITE_SPACE+WHITE_SPACE+WHITE_SPACE+'id = self.id,\n')

    for component in model_components:
        model_file.write(WHITE_SPACE + WHITE_SPACE + WHITE_SPACE + component['field_name'].lower() + ' = self.' + component['field_name'].lower() + ',\n')
    model_file.write(WHITE_SPACE+WHITE_SPACE+WHITE_SPACE+'created_on = json_date_format(self.created_on),\n')
    model_file.write(WHITE_SPACE+WHITE_SPACE+WHITE_SPACE+'last_updated_on = json_date_format(self.last_updated_on))\n')
    model_file.close()

    init_file = open(init_path, 'a')
    init_file.write("from "+ model_name.lower() + " import " + model_name.title()+"\n")
    init_file.close()

    print '\n'+model_name+' tree seed planted in the greenhouse\n'

    if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
        print "If you're done, please run yard shove to complete the database creation"
    else:
        print "If you're done, please run yard water to complete the database creation"

# end of file


text:
module.exports = function(config) {
    'use strict';

    var cfg = {
        bowerComponents: 'demo/bower_components'
    };

    config.set({
        basePath: '',
        frameworks: ['jasmine'],

        // files to load in the browser
        files: [
            // components
            cfg.bowerComponents + '/jquery/dist/jquery.js',
            cfg.bowerComponents + '/jasmine-jquery/lib/jasmine-jquery.js',
            cfg.bowerComponents + '/angular/angular.js',
            cfg.bowerComponents + '/angular-mocks/angular-mocks.js',

            // source files
            'src/pinetree.js',
            'src/**/*.js',

            // templates
            //'**/*.html',

            // tests
            'test/**/*.spec.js'

        ],

        // generate js files from html templates to expose them during testing
        preprocessors: {
            '**/*.html': 'ng-html2js'
        },

        // https://github.com/karma-runner/karma-ng-html2js-preprocessor#configuration
        ngHtml2JsPreprocessor: {
            // setting this option will create only a single module that contains templates
            // from all the files, so you can load them all with module('foo')
            moduleName: 'pinetree'
        },

        // files to exclude
        exclude: [],

        // level of logging
        // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
        logLevel: config.LOG_INFO,

        port: 9876,
        reporters: 'dots'
    });
};


text:
from nova.api.openstack import common

class ViewBuilder(common.ViewBuilder):

    _collection_name = "flavors"

    def basic(self, request, flavor):
        return {
            "flavor": {
                "id": flavor["flavorid"],
                "name": flavor["name"],
                "links": self._get_links(request,
                                         flavor["flavorid"],
                                         self._collection_name),
            },
        }

    def show(self, request, flavor):
        flavor_dict = {
            "flavor": {
                "id": flavor["flavorid"],
                "name": flavor["name"],
                "ram": flavor["memory_mb"],
                "disk": flavor["root_gb"],
                "swap": flavor["swap"] or "",
                "OS-FLV-EXT-DATA:ephemeral": flavor["ephemeral_gb"],
                "OS-FLV-DISABLED:disabled": flavor["disabled"],
                "vcpus": flavor["vcpus"],
                "links": self._get_links(request,
                                         flavor["flavorid"],
                                         self._collection_name),
            },
        }

        return flavor_dict

    def index(self, request, flavors):
        """Return the 'index' view of flavors."""
        coll_name = self._collection_name
        return self._list_view(self.basic, request, flavors, coll_name)

    def detail(self, request, flavors):
        """Return the 'detail' view of flavors."""
        coll_name = self._collection_name + '/detail'
        return self._list_view(self.show, request, flavors, coll_name)

    def _list_view(self, func, request, flavors, coll_name):
        """Provide a view for a list of flavors.

        :param func: Function used to format the flavor data
        :param request: API request
        :param flavors: List of flavors in dictionary format
        :param coll_name: Name of collection, used to generate the next link
                          for a pagination query

        :returns: Flavor reply data in dictionary format
        """
        flavor_list = [func(request, flavor)["flavor"] for flavor in flavors]
        flavors_links = self._get_collection_links(request,
                                                   flavors,
                                                   coll_name,
                                                   "flavorid")
        flavors_dict = dict(flavors=flavor_list)

        if flavors_links:
            flavors_dict["flavors_links"] = flavors_links

        return flavors_dict


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/Aspose.Barcode Java for IntelliJ (Maven).iml" filepath="$PROJECT_DIR$/Aspose.Barcode Java for IntelliJ (Maven).iml" />
    </modules>
  </component>
</project>


text:
import { Observable } from '../Observable';
import { ColdObservable } from './ColdObservable';
import { HotObservable } from './HotObservable';
import { TestMessage } from './TestMessage';
import { SubscriptionLog } from './SubscriptionLog';
import { VirtualTimeScheduler } from '../scheduler/VirtualTimeScheduler';
export interface RunHelpers {
    cold: typeof TestScheduler.prototype.createColdObservable;
    hot: typeof TestScheduler.prototype.createHotObservable;
    flush: typeof TestScheduler.prototype.flush;
    expectObservable: typeof TestScheduler.prototype.expectObservable;
    expectSubscriptions: typeof TestScheduler.prototype.expectSubscriptions;
}
export declare type observableToBeFn = (marbles: string, values?: any, errorValue?: any) => void;
export declare type subscriptionLogsToBeFn = (marbles: string | string[]) => void;
export declare class TestScheduler extends VirtualTimeScheduler {
    assertDeepEqual: (actual: any, expected: any) => boolean | void;
    readonly hotObservables: HotObservable<any>[];
    readonly coldObservables: ColdObservable<any>[];
    private flushTests;
    private runMode;
    constructor(assertDeepEqual: (actual: any, expected: any) => boolean | void);
    createTime(marbles: string): number;
    /**
     * @param marbles A diagram in the marble DSL. Letters map to keys in `values` if provided.
     * @param values Values to use for the letters in `marbles`. If ommitted, the letters themselves are used.
     * @param error The error to use for the `#` marble (if present).
     */
    createColdObservable<T = string>(marbles: string, values?: {
        [marble: string]: T;
    }, error?: any): ColdObservable<T>;
    /**
     * @param marbles A diagram in the marble DSL. Letters map to keys in `values` if provided.
     * @param values Values to use for the letters in `marbles`. If ommitted, the letters themselves are used.
     * @param error The error to use for the `#` marble (if present).
     */
    createHotObservable<T = string>(marbles: string, values?: {
        [marble: string]: T;
    }, error?: any): HotObservable<T>;
    private materializeInnerObservable;
    expectObservable(observable: Observable<any>, subscriptionMarbles?: string): ({
        toBe: observableToBeFn;
    });
    expectSubscriptions(actualSubscriptionLogs: SubscriptionLog[]): ({
        toBe: subscriptionLogsToBeFn;
    });
    flush(): void;
    /** @nocollapse */
    static parseMarblesAsSubscriptions(marbles: string, runMode?: boolean): SubscriptionLog;
    /** @nocollapse */
    static parseMarbles(marbles: string, values?: any, errorValue?: any, materializeInnerObservables?: boolean, runMode?: boolean): TestMessage[];
    run<T>(callback: (helpers: RunHelpers) => T): T;
}


text:
<!DOCTYPE html>

  <title>icejs</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="X-UA-Compatible" content="chrome=1">
  <meta name="fragment" content="!">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="shortcut icon" type="image/ico" href="favicon.ico" />
  <link rel="stylesheet" href="resources/css/app-4689d2a5522dcd3c9e9923ca59c33f27.css" type="text/css" />
  <link rel="stylesheet" href="styles-8184dad50dadb76aad743829a7c19ed0.css" type="text/css" />

icejs

API Documentation

Others...

Others...

Ice

Guides


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Threading;
using System.Web.Services.Protocols;
using System.Windows.Forms;
using MLifter.BusinessLayer;
using MLifter.Components.Properties;
using MLifter.Generics;
using MRG.Controls.UI;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;
using System.ServiceModel.Syndication;
using System.Xml.Serialization;
using System.Net;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace MLifter.Components
{
	public partial class FolderTreeView : TreeView
	{
		/// <summary>
		/// Occurs when content loading throws an exception.
		/// </summary>
		/// <remarks>Documented by Dev02, 2009-05-14</remarks>
		public event MLifter.BusinessLayer.FolderIndexEntry.ContentLoadExceptionEventHandler ContentLoadException;
		/// <summary>
		/// Gets or sets the folders.
		/// </summary>
		/// <value>The folders.</value>
		/// <remarks>Documented by Dev05, 2009-03-12</remarks>
		public ObservableList<FolderIndexEntry> Folders { get; private set; }
		/// <summary>
		/// Gets the connections.
		/// </summary>
		/// <value>The connections.</value>
		/// <remarks>Documented by Dev05, 2009-03-12</remarks>
		public ObservableList<IConnectionString> Connections { get; private set; }
		/// <summary>
		/// Gets the feeds.
		/// </summary>
		/// <remarks>CFI, 2012-03-03</remarks>
		public ObservableCollection<ModuleFeedConnection> Feeds { get; private set; }

		/// <summary>
		/// Gets the collection of tree nodes that are assigned to the tree view control.
		/// </summary>
		/// <value></value>
		/// <returns>
		/// A <see cref="T:System.Windows.Forms.TreeNodeCollection"/> that represents the tree nodes assigned to the tree view control.
		/// </returns>
		/// <remarks>Documented by Dev05, 2009-03-12</remarks>
		public new List<FolderTreeNode> Nodes { get; private set; }
		/// <summary>
		/// Gets or sets the tree node that is currently selected in the tree view control.
		/// </summary>
		/// <value></value>
		/// <returns>
		/// The <see cref="T:System.Windows.Forms.TreeNode"/> that is currently selected in the tree view control.
		/// </returns>
		/// <PermissionSet>
		/// 	<IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/>
		/// 	<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/>
		/// 	<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/>
		/// 	<IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/>
		/// </PermissionSet>
		/// <remarks>Documented by Dev05, 2009-03-12</remarks>
		[Browsable(false)]
		public FolderIndexEntry SelectedFolder
		{
			get
			{
				try
				{
					if (SelectedNode is FolderTreeNode)
						return (SelectedNode as FolderTreeNode).Folder;
					else
						return null;
				}
				catch { return null; }
			}
			set
			{
				try
				{
					SelectedNode = Nodes.Find(n => n.Folder == value);
				}
				catch { }
			}
		}
		/// <summary>
		/// Gets or sets the tree node that is currently selected in the tree view control.
		/// </summary>
		/// <value></value>
		/// <returns>
		/// The <see cref="T:System.Windows.Forms.TreeNode"/> that is currently selected in the tree view control.
		/// </returns>
		/// <PermissionSet>
		/// 	<IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/>
		/// 	<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/>
		/// 	<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/>
		/// 	<IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/>
		/// </PermissionSet>
		/// <remarks>Documented by Dev05, 2009-03-12</remarks>
		public new TreeNode SelectedNode { get { return base.SelectedNode; } set { base.SelectedNode = value; } }

		/// <summary>
		/// Initializes a new instance of the <see cref="FolderTreeView"/> class.
		/// </summary>
		/// <remarks>Documented by Dev05, 2009-03-12</remarks>
		public FolderTreeView()
			: base()
		{
			this.DoubleBuffered = true;

			InitializeComponent();

			updateTimer.Interval = 1000;
			updateTimer.Tick += new EventHandler(updateTimer_Tick);

			this.ImageList = new ImageList();
			this.ImageList.Images.Add(Resources.learning_16_gif);
			this.ImageList.Images.Add(Resources.folder_gif);
			this.ImageList.Images.Add(Resources.folder_saved_search_gif);
			this.ImageList.Images.Add(Resources.network_gif);
			this.ImageList.Images.Add(Resources.network_offline_gif);
			this.ImageList.Images.Add(Resources.system_search_gif);
			this.ImageList.Images.Add(Resources.usbDrive);
			this.ImageList.Images.Add(Resources.ML);
			InitTreeView();
		}

		private FolderTreeNode mainNode = new FolderTreeNode();
		private void InitTreeView()
		{
			base.Nodes.Add(mainNode);
			mainNode.ContentLoadException += new FolderIndexEntry.ContentLoadExceptionEventHandler(mainNode_ContentLoadException);
			mainNode.Expand();
			mainNode.UpdateDetails();

			Nodes = new List<FolderTreeNode>();
			Nodes.Add(mainNode);
			Folders = new ObservableList<FolderIndexEntry>();
			Folders.ListChanged += new EventHandler<ObservableListChangedEventArgs<FolderIndexEntry>>(Folders_ListChanged);
			Connections = new ObservableList<IConnectionString>();
			Connections.ListChanged += new EventHandler<ObservableListChangedEventArgs<IConnectionString>>(Connections_ListChanged);
		}

		/// <summary>
		/// Sets the feeds.
		/// </summary>
		/// <param name="feeds">The feeds.</param>
		/// <remarks>CFI, 2012-03-03</remarks>
		public void SetFeeds(ObservableCollection<ModuleFeedConnection> feeds)
		{
			List<TreeNode> nodesToRemove = new List<TreeNode>();
			foreach (TreeNode node in base.Nodes)
				if (node is FeedTreeNode)
					nodesToRemove.Add(node);
			nodesToRemove.ForEach(n => base.Nodes.Remove(n));

			if(Feeds != null)
				Feeds.CollectionChanged -= feeds_CollectionChanged;
			Feeds = feeds;
			Feeds.CollectionChanged += new NotifyCollectionChangedEventHandler(feeds_CollectionChanged);

			foreach (ModuleFeedConnection feed in Feeds)
				base.Nodes.Add(new FeedTreeNode(feed));
		}

		/// <summary>
		/// Handles the CollectionChanged event of the feeds control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.Collections.Specialized.NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
		/// <remarks>CFI, 2012-03-03</remarks>
		protected void feeds_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			switch (e.Action)
			{
				case NotifyCollectionChangedAction.Add:
					foreach (ModuleFeedConnection item in e.NewItems)
						base.Nodes.Add(new FeedTreeNode(item));
					break;
				case NotifyCollectionChangedAction.Remove:
					break;
				case NotifyCollectionChangedAction.Replace:
				case NotifyCollectionChangedAction.Reset:
					SetFeeds(sender as ObservableCollection<ModuleFeedConnection>);
					break;
				case NotifyCollectionChangedAction.Move:
				default:
					break;
			}
		}

		/// <summary>
		/// Mains the node_ content load exception.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="exp">The exp.</param>
		/// <remarks>Documented by Dev02, 2009-05-14</remarks>
		private void mainNode_ContentLoadException(object sender, Exception exp)
		{
			if (ContentLoadException != null)
				ContentLoadException(sender, exp);
		}

		/// <summary>
		/// Replaces the connections and rebuilds the tree.
		/// </summary>
		/// <param name="connections">The connections.</param>
		/// <remarks>Documented by Dev03, 2009-03-20</remarks>
		public void ReplaceConnections(List<IConnectionString> connections)
		{
			if (Connections.Count == 0)
				Connections.AddRange(connections);
			else
			{
				Folders.ListChanged -= new EventHandler<ObservableListChangedEventArgs<FolderIndexEntry>>(Folders_ListChanged);
				Connections.ListChanged -= new EventHandler<ObservableListChangedEventArgs<IConnectionString>>(Connections_ListChanged);
				mainNode.Nodes.Clear();
				Folders.Clear();
				Connections.Clear();
				Folders.ListChanged += new EventHandler<ObservableListChangedEventArgs<FolderIndexEntry>>(Folders_ListChanged);
				Connections.ListChanged += new EventHandler<ObservableListChangedEventArgs<IConnectionString>>(Connections_ListChanged);
				Connections.AddRange(connections);
			}
		}

		/// <summary>
		/// Handles the Tick event of the updateTimer control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		/// <remarks>Documented by Dev05, 2009-03-16</remarks>
		private void updateTimer_Tick(object sender, EventArgs e)
		{
			BeginUpdate();
			try
			{
				lock (Nodes)
				{
					if (!Nodes.Exists(n => n.IsLoading))
						updateTimer.Enabled = false;
					Nodes.ForEach(n => n.UpdateDetails());
				}
			}
			catch (Exception exp) { Trace.WriteLine(exp.ToString()); }
			EndUpdate();
		}

		/// <summary>
		/// Handles the ListChanged event of the Connections control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="MLifter.Components.ObservableListChangedEventArgs<MLifter.BusinessLayer.IConnectionString>"/> instance containing the event data.</param>
		/// <remarks>Documented by Dev05, 2009-03-12</remarks>
		private void Connections_ListChanged(object sender, ObservableListChangedEventArgs<IConnectionString> e)
		{
			switch (e.ListChangedType)
			{
				case ListChangedType.ItemAdded:
					if (Folders.Find(f => f.Connection == e.Item) == null)
					{
						FolderTreeNode entry = new FolderTreeNode(e.Item);
						entry.ContentLoadException += new FolderIndexEntry.ContentLoadExceptionEventHandler(Folder_ContentLoadException);
						lock (Nodes)
						{
							Nodes.Add(entry);
						}
						if (InvokeRequired)
							Invoke((MethodInvoker)delegate { AddFolderToMainNode(entry); });
						else
							AddFolderToMainNode(entry);
						entry.UpdateDetails();
					}
					break;
				case ListChangedType.ItemDeleted:
					if (InvokeRequired)
						Invoke((MethodInvoker)delegate
						{
							lock (Nodes)
							{
								Nodes.FindAll(f => f.Connection == e.Item).ForEach(f => base.Nodes.Remove(f));
								Nodes.RemoveAll(f => f.Connection == e.Item);
							}
						});
					else
					{
						lock (Nodes)
						{
							Nodes.FindAll(f => f.Connection == e.Item).ForEach(f => base.Nodes.Remove(f));
							Nodes.RemoveAll(f => f.Connection == e.Item);
						}
					}
					break;
				case ListChangedType.ItemChanged:
					break;
				case ListChangedType.Reset:
					foreach (IConnectionString item in Connections)
					{
						if (Folders.Find(f => f.Connection == item) == null)
						{
							FolderTreeNode entry = new FolderTreeNode(item);
							entry.ContentLoadException += new FolderIndexEntry.ContentLoadExceptionEventHandler(Folder_ContentLoadException);
							lock (Nodes)
							{
								Nodes.Add(entry);
							}
							if (InvokeRequired)
								Invoke((MethodInvoker)delegate { AddFolderToMainNode(entry); });
							else
								AddFolderToMainNode(entry);
							entry.UpdateDetails();
						}
					}
					break;
				case ListChangedType.ItemMoved:
				default:
					throw new NotSupportedException();
			}

			updateTimer.Enabled = true;
		}
		private void AddFolderToMainNode(FolderTreeNode entry)
		{
			BeginUpdate();
			lock (Nodes)
			{
				Nodes.Find(n => n.IsMainNode).Nodes.Add(entry);
			}
			EndUpdate();
		}
		/// <summary>
		/// Handles the ListChanged event of the Folders list.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="MLifter.Components.ObservableListChangedEventArgs<MLifter.BusinessLayer.FolderIndexEntry>"/> instance containing the event data.</param>
		/// <remarks>Documented by Dev05, 2009-03-12</remarks>
		private void Folders_ListChanged(object sender, ObservableListChangedEventArgs<FolderIndexEntry> e)
		{
			switch (e.ListChangedType)
			{
				case ListChangedType.ItemAdded:
					if (!Connections.Contains(e.Item.Connection))
						Connections.Add(e.Item.Connection);
					if (e.Item.Parent != null)
					{
						try
						{
							FolderTreeNode entry = new FolderTreeNode(e.Item);
							entry.ContentLoadException += new FolderIndexEntry.ContentLoadExceptionEventHandler(Folder_ContentLoadException);
							lock (Nodes)
							{
								Nodes.Add(entry);
							}
							while (Nodes.Find(n => n.Folder == e.Item.Parent) == null) Thread.Sleep(10);
							if (InvokeRequired)
								Invoke((MethodInvoker)delegate { AddFolderToParent(e.Item.Parent, entry); });
							else
								entry.UpdateDetails();
						}
						catch (Exception exp) { Trace.WriteLine("Folder-Added: " + exp.ToString()); }
					}
					else
					{
						FolderTreeNode node = Nodes.Find(n => n.Connection == e.Item.Connection);
						if (node != null)
							node.SetFolder(e.Item);
						else
						{
							FolderTreeNode entry = new FolderTreeNode(e.Item);
							entry.ContentLoadException += new FolderIndexEntry.ContentLoadExceptionEventHandler(Folder_ContentLoadException);
							lock (Nodes)
							{
								Nodes.Add(entry);
							}
							Delegate add = (MethodInvoker)delegate
								{
									BeginUpdate();
									lock (Nodes)
									{
										Nodes.Find(n => n.IsMainNode).Nodes.Add(entry);
									}
									EndUpdate();
								};
							if (InvokeRequired)
								Invoke((MethodInvoker)add);
							else
								add.DynamicInvoke();
							entry.UpdateDetails();
						}
					}
					e.Item.ContentLoading += new EventHandler(Folder_ContentLoading);
					break;
				case ListChangedType.ItemDeleted:
					throw new NotImplementedException();
				case ListChangedType.ItemChanged:
					break;
				case ListChangedType.Reset:
				case ListChangedType.ItemMoved:
				default:
					throw new NotSupportedException();
			}

			updateTimer.Enabled = true;
		}

		/// <summary>
		/// Folder_s the content load exception.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="exp">The exp.</param>
		/// <remarks>Documented by Dev05, 2009-05-15</remarks>
		private void Folder_ContentLoadException(object sender, Exception exp)
		{
			if (ContentLoadException != null)
				ContentLoadException(sender, exp);
		}

		private void Folder_ContentLoading(object sender, EventArgs e)
		{
			updateTimer.Enabled = true;
		}
		private void AddFolderToParent(FolderIndexEntry parent, FolderTreeNode entry)
		{
			BeginUpdate();
			lock (Nodes)
			{
				Nodes.Find(n => n.Folder == parent).Nodes.Add(entry);
			}
			EndUpdate();
		}
	}
}