text:
//
//Copyright 2016 David Beales
//
//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.
//
using System;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.InteropServices;
using APE.Capture;
using APE.Communication;
using System.Threading;
using System.Drawing.Imaging;
using System.Security.Principal;
using NM = APE.Native.NativeMethods;

namespace APE.Language
{
    /// <summary>
    /// Automation class used to automate controls derived from the following:
    /// System.Windows.Forms.CheckBox
    /// </summary>
    public sealed class GUICheckStateControl : GUIFocusableObject
    {
        /// <summary>
        /// Constructor used for non-form controls
        /// </summary>
        /// <param name="parentForm">The top level form the control belongs to</param>
        /// <param name="descriptionOfControl">A description of the control which would make sense to a human.
        /// <para/>This text is used in the logging method.  For example: OK button</param>
        /// <param name="identParams">One or more identifier object(s) used to locate the control.
        /// <para/>Normally you would just use the name identifier</param>
        public GUICheckStateControl(GUIForm parentForm, string descriptionOfControl, params Identifier[] identParams)
            : base(parentForm, descriptionOfControl, identParams)
        {
        }

        /// <summary>
        /// Perform a mouse click with the specified button at the specified position relative to the control while pressing the specified key
        /// </summary>
        /// <param name="X">How far from the left edge of the control to click the mouse</param>
        /// <param name="Y">How far from the top edge of the control to click the mouse</param>
        /// <param name="Button">The button to click</param>
        /// <param name="Keys">The key to hold while clicking</param>
        public override void SingleClick(int X, int Y, MouseButton Button, MouseKeyModifier Keys)
        {
            int InitialState = GetState();
            base.SingleClick(X, Y, Button, Keys);
            if (Button == MouseButton.Left)
            {
                pollForState(InitialState, false);
            }
        }

        /// <summary>
        /// Perform a double mouse click with the specified button at the specified position relative to the control while pressing the specified key
        /// </summary>
        /// <param name="X">How far from the left edge of the control to double click the mouse</param>
        /// <param name="Y">How far from the top edge of the control to double click the mouse</param>
        /// <param name="Button">The button to double click</param>
        /// <param name="Keys">The key to hold while double clicking</param>
        public override void DoubleClick(int X, int Y, MouseButton Button, MouseKeyModifier Keys)
        {
            int InitialState = GetState();
            base.DoubleClick(X, Y, Button);
            if (Button == MouseButton.Left)
            {
                pollForState(InitialState, false);
            }
        }

        /// <summary>
        /// Perform a triple mouse click with the specified button at the specified position relative to the control while pressing the specified key
        /// </summary>
        /// <param name="X">How far from the left edge of the control to triple click the mouse</param>
        /// <param name="Y">How far from the top edge of the control to triple click the mouse</param>
        /// <param name="Button">The button to triple click</param>
        /// <param name="Keys">The key to hold while triple clicking</param>
        public override void TripleClick(int X, int Y, MouseButton Button, MouseKeyModifier Keys)
        {
            int InitialState = GetState();
            base.TripleClick(X, Y, Button);
            if (Button == MouseButton.Left)
            {
                pollForState(InitialState, false);
            }
        }

        /// <summary>
        /// Gets the state of the control
        /// </summary>
        public int State
        {
            get
            {
                return GetState();
            }
        }

        private int GetState()
        {
            //Get the number of items
            GUI.m_APE.AddFirstMessageFindByHandle(DataStores.Store0, Identity.ParentHandle, Identity.Handle);
            GUI.m_APE.AddQueryMessageReflect(DataStores.Store0, DataStores.Store1, "CurrentStateId", MemberTypes.Property);
            GUI.m_APE.AddRetrieveMessageGetValue(DataStores.Store1);
            GUI.m_APE.SendMessages(EventSet.APE);
            GUI.m_APE.WaitForMessages(EventSet.APE);
            //Get the value(s) returned MUST be done straight after the WaitForMessages call
            int state = GUI.m_APE.GetValueFromMessage();
            return state;
        }

        private void pollForState(int state, bool waitToBeThisState)
        {
            Stopwatch timer = Stopwatch.StartNew();
            while (true)
            {
                if (timer.ElapsedMilliseconds > GUI.m_APE.TimeOut)
                {
                    throw GUI.ApeException(Identity.Description + " failed to be set to state [" + state.ToString() + "]");
                }

                if (waitToBeThisState)
                {
                    if (GetState() == state)
                    {
                        break;
                    }
                }
                else
                {
                    if (GetState() != state)
                    {
                        break;
                    }
                }

                Thread.Sleep(15);
            }
            timer.Stop();
        }
    }
}


text:
from django.shortcuts import render, get_object_or_404

from sedastrela.events.models import Event

def event_view(request, id, _):
    event = get_object_or_404(Event, id=id)
    return render(request, 'sedastrela/events/event.html', {
        'event': event,
    })

redpajama_set_name: RedPajamaGithub


text:
require 'ecloud/spec_helper'

shared_examples_for "a failed vapp deletion" do
  it "should not change the mock data" do
    expect { subject }.to change { @mock_vdc.virtual_machines.count }.by(0)
  end

  it "should not change the model data" do
    expect { subject }.to change { vdc.reload.servers.reload.count }.by(0)
  end

  describe "#body" do
    its(:body) { should == '' }
  end

  describe "#headers" do
    its(:headers) { should_not include("Location") }
  end
end

#FIXME: Make this more sane with rspec2
if Fog.mocking?
  describe "Fog::Ecloud, initialized w/ the TMRK Ecloud module", :type => :mock_tmrk_ecloud_request do
    subject { @vcloud }

    it { should respond_to(:delete_vapp) }

    describe "#delete_vapp" do
      context "with a valid vapp uri" do
        subject { @vcloud.delete_vapp(@mock_vm.href) }
        let(:vdc) { @vcloud.vdcs.first }

        context "when there are no internet service nodes attached" do
          it_should_behave_like("all delete responses")

          it "should change the mock data" do
            expect { subject }.to change { @mock_vdc.virtual_machines.count }.by(-1)
          end

          it "should change the model data" do
            expect { subject }.to change { vdc.reload.servers.reload.count }.by(-1)
          end

          describe "#body" do
            its(:body) { should == '' }
          end

          describe "#headers" do
            its(:headers) { should include("Location") }
          end
        end

        context "when there are internet service nodes attached" do
          before do
            vdc.public_ips.first.internet_services.create(:name => "#{@mock_vm.name} service", :port => 1231, :protocol => "TCP", :description => "", :enabled => true).tap do |internet_service|
              internet_service.nodes.create(:name => "#{@mock_vm.name} node", :port => 1231, :description => "", :enabled => true, :ip_address => @mock_vm.ip)
            end
          end

          it_should_behave_like "all delete responses"
          it_should_behave_like "a failed vapp deletion"
        end

        context "when the VM is powered on" do
          before do
            @mock_vm.power_on!
          end

          it_should_behave_like "all delete responses"
          it_should_behave_like "a failed vapp deletion"
        end

        context "when the VM's IP has an rnat set" do
          before do
            @mock_vm.network_ip[:rnat] = "1.2.3.4"
          end

          it_should_behave_like "all delete responses"
          it_should_behave_like "a failed vapp deletion"
        end
      end

      context "with a vapp uri that doesn't exist" do
        subject { lambda { @vcloud.delete_vapp(URI.parse('https://www.fakey.c/piv8vc99')) } }

        it_should_behave_like "a request for a resource that doesn't exist"
      end
    end
  end
else
end


text:
//
//  MV3.h
//  JJ_Class_14_ReactiveCocoa
//
//  Created by Jay on 2016/9/18.
//  Copyright © 2016年 JayJJ. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <ReactiveCocoa/ReactiveCocoa.h>
#import "VM3Protocol.h"

@interface VM3 : NSObject

@property (nonatomic, strong) NSString *searchText;
@property (nonatomic, strong) NSString *title;

@property (strong, nonatomic) RACCommand *executeSearchCommand;

@property (nonatomic, strong) RACSubject *searchSubject;

/** TODO: */
- (instancetype)initWithVM3Imp:(id<VM3Protocol>)vm3Imp;

@end


text:
import { Fetch, UrlBuilder } from '@jenkins-cd/blueocean-core-js';
import { TypedError } from './TypedError';

const Base64 = {
    encode: data => btoa(data),
    decode: str => atob(str),
};

export const LoadError = {
    TOKEN_NOT_FOUND: 'TOKEN_NOT_FOUND',
    TOKEN_REVOKED: 'TOKEN_REVOKED',
    TOKEN_INVALID_SCOPES: 'TOKEN_INVALID_SCOPES',
    JENKINSFILE_NOT_FOUND: 'JENKINSFILE_NOT_FOUND',
};

/**
 * Load and save content to a pipeline's backing SCM provider.
 */
class ScmContentApi {
    loadContent({ organization, pipeline, branch, path = 'Jenkinsfile' }) {
        const pipelineUrl = UrlBuilder.buildRestUrl(organization, pipeline);
        let contentUrl = `${pipelineUrl}scm/content?path=${path}`;
        if (branch) {
            contentUrl += `&branch=${encodeURIComponent(branch)}`;
        }
        return Fetch.fetchJSON(contentUrl)
            .then(result => result)
            .catch(error => this._loadContentErrorHandler(error));
    }

    _loadContentErrorHandler(error) {
        const { status } = error.response;
        const { responseBody } = error;
        const { message } = responseBody || {};

        if (status === 404) {
            throw new TypedError(LoadError.JENKINSFILE_NOT_FOUND, responseBody);
        } else if (status === 428) {
            throw new TypedError(LoadError.TOKEN_NOT_FOUND, responseBody);
        } else if (message && message.indexOf('Invalid accessToken') !== -1) {
            throw new TypedError(LoadError.TOKEN_REVOKED, responseBody);
        }

        // TODO: TOKEN_INVALID_SCOPES

        throw error;
    }

    buildSaveContentRequest({ organization, pipeline, repo, sourceBranch, targetBranch, sha, message, path = 'Jenkinsfile', content }) {
        return {
            content: {
                message,
                path,
                branch: targetBranch,
                sourceBranch,
                repo,
                sha,
                base64Data: Base64.encode(content),
            },
        };
    }

    saveContent({ organization, pipeline, repo, sourceBranch, targetBranch, sha, message, path = 'Jenkinsfile', content }) {
        const contentUrl = `${UrlBuilder.buildRestUrl(organization, pipeline)}scm/content/`;

        const body = this.buildSaveContentRequest({
            organization,
            pipeline,
            repo,
            sourceBranch,
            targetBranch,
            sha,
            message,
            path,
            content,
        });

        const fetchOptions = {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body),
        };

        return Fetch.fetchJSON(contentUrl, { fetchOptions });
    }
}

export default ScmContentApi;


text:
.block-cr_gmap_block .block-settings .modal-body {
    overflow: hidden;
    padding: 0;
}
.circleflip-googlemaps-frame .cfgm-rightpanel {
    width: 40%;
    height: 100%;
    overflow: hidden;
    float: right;
    position: relative;
}
.circleflip-googlemaps-frame .cfgm-leftpanel {
    height: 100%;
    display: block;
    overflow: hidden;
}
.circleflip-googlemaps-frame .cfgm-map,
.circleflip-googlemaps-frame .cfgm-map-container,
.circleflip-googlemaps-frame {
    height: 100%;
}
.circleflip-googlemaps-frame .cfgm-error .error {
    margin: 15px 10px !important;
    background: #fcfcfc;
    -webkit-box-shadow: 0 1px 1px 0 rgba(0,0,0,0.2);
    box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.2);
}
/* -------------------------------------------------------------------------- */
/* # TABLE STRUCTURE */
.circleflip-googlemaps-frame .cfgm-locationlist {
    table-layout: fixed;
}
.circleflip-googlemaps-frame .cfgm-location-key {
    width: 40px;
    box-sizing: border-box;
}
.circleflip-googlemaps-frame .cfgm-location-title {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    cursor: default;
}
.circleflip-googlemaps-frame .cfgm-location-actions {
    width: 87px;
    white-space: nowrap;
    box-sizing: border-box;
}
.circleflip-googlemaps-frame .cfgm-location:nth-child(odd) {
    background-color: #f9f9f9;
}
/* #END TABLE STRUCTURE */
/* # USER CONTROLS */
.circleflip-googlemaps-frame .cfgm-location-hidden .cfgm-location-action-hide,
.circleflip-googlemaps-frame .cfgm-location-action-primary{
    opacity: 0.2;
}
.circleflip-googlemaps-frame .cfgm-location-primary .cfgm-location-action-primary {
    opacity: 1;
}
.circleflip-googlemaps-frame .cfgm-location-action-primary,
.circleflip-googlemaps-frame .cfgm-location-actions .dashicons {
    cursor: pointer;
}
.circleflip-googlemaps-frame .cfgm-location-primary .cfgm-location-action-primary {
    cursor: auto;
}
.circleflip-googlemaps-frame .cfgm-location.cfgm-location-selected {
    background: rgba(177, 232, 232, 0.6);
}
.cfgm-location {
    transition: transform .6s linear;
}
/* #END USER CONTROLS */
/* -------------------------------------------------------------------------- */
.circleflip-googlemaps-frame .cfgm-map-toolbar-search {
    overflow: hidden;
}
.circleflip-googlemaps-frame .cfgm-map-toolbar-pin {
    width: 52px;
    height: 52px;
    float: right;
}
.circleflip-googlemaps-frame .cfgm-map-toolbar-search .cfgm-map-search {
    width: 100%;
    font-size: 16px;
    border: none;
    border-left: 5px solid #c5c5c5;
    box-shadow: none;
    margin: 0;
    padding: 15px;
    transition: 150ms ease-out;
}
.circleflip-googlemaps-frame .cfgm-map-toolbar-search .cfgm-map-search:focus {
    border-left: 10px solid #0074a2;
}
.circleflip-googlemaps-frame .cfgm-map-toolbar-pin .cfgm-map-pin {
    height: 52px;

    width: 52px;
    font-size: 32px;
    padding: 10px;
    box-sizing: border-box;
}
/* ------------------------------------------------------------------------- */
/* Google Places API autocomplete container */
.pac-container {
    z-index: 99999;
    margin-left: 10px;
    box-shadow: none;
    border-top: none;
}
.pac-item:first-child {
    border-top: none;
}
/* ------------------------------------------------------------------------- */
.cfgm-content-panel {
    height: 100%;
    overflow: auto;
    padding: 10px;
    box-sizing: border-box;
}
/* -------------------------------------------------------------------------- */
.cfgm-edit {
    opacity: 0;
    padding: 0;
    overflow: hidden;
    transform: translateY(-100%);
    transition: opacity .15s linear;
}
.cfgm-edit.cfgm-edit-open {
    opacity: 1;
}
.cfgm-edit-header {
    height: 50px;
    background: #fcfcfc;
    border-bottom: 1px solid #e5e5e5;
    box-sizing: border-box;
    box-shadow: 0px -7px 17px 0px;

    /* for box shadow to appear */
    position: relative;
}

.cfgm-edit-header > [class*="cfgm-location-"] {
    padding: 15px 10px;
}

.cfgm-edit-header .cfgm-location-key {
    float: left;
}

.cfgm-edit-header .cfgm-location-actions {
    float: right;
    width: 63px;
}
.cfgm-edit-header .cfgm-location-title {
    overflow: hidden;
    margin: 0;
    white-space: nowrap;
    text-overflow: ellipsis;
    line-height: 20px;
}
.cfgm-edit-header .cfgm-edit-pretitle {
    font-weight: normal;
    font-style: italic;
}
.cfgm-edit-body {
    height: calc(100% - 100px);
    background: white;
    padding: 20px;
    box-sizing: border-box;
    overflow-y: auto;
}
.cfgm-edit-field-title {
    float: left;
    width: 20%;
    min-width: 100px;
    text-align: right;
    padding: 15px 15px;
    box-sizing: border-box;
}
.cfgm-edit-field {
  overflow: hidden;
  padding: 10px 15px;
  box-sizing: border-box;
}
.cfgm-edit-field textarea {
    resize: vertical;
}
.cfgm-edit-footer {
    height: 50px;
    padding: 10px 20px;
    text-align: right;
    border-top: 1px solid #e5e5e5;
    background: #fcfcfc;
    box-sizing: border-box;
}
.cfgm-media-box img {
    max-width: 100%;
}
.cfgm-media-box-controls {
    width: 100%;
}
.cfgm-media-box-controls [data-action] {
    width: calc(50% - 12px);
    margin: 5px;
    font-size: 20px;
    height: 1.5em;
}
.cfgm-media-box {
    width: 100%;
    box-sizing: border-box;
}
.cfgm-edit-field-row {
    width: 100%;
    clear: both;
}
.cfgm-settings {
    margin-top: 30px;
    border-top: 1px solid #e5e5e5;
    padding-top: 30px;
}
.cfgm-locationlist-body + tfoot {
    display: none;
}
.cfgm-locationlist-body + tfoot th {
    text-align: center;
}
.cfgm-locationlist-body:empty + tfoot {
    display: table-footer-group;
}


text:
package io.netty.handler.codec.xml;

/**
 * DTD (Document Type Definition)
 */
public class XmlDTD {

    private final String text;

    public XmlDTD(String text) {
        this.text = text;
    }

    public String text() {
        return text;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        XmlDTD xmlDTD = (XmlDTD) o;

        if (text != null ? !text.equals(xmlDTD.text) : xmlDTD.text != null) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        return text != null ? text.hashCode() : 0;
    }

    @Override
    public String toString() {
        return "XmlDTD{" +
                "text='" + text + '\'' +
                '}';
    }

}


text:
using System;
using System.Linq;
using Newtonsoft.Json;

namespace AldursLab.WurmAssistant3.Areas.Granger.DataLayer
{
    [JsonObject(MemberSerialization.OptIn)]
    public class TraitValueEntity
    {
        //primary key
        [JsonProperty("id")]
        public int Id;

        [JsonProperty("valuemapid")]
        public string ValueMapId;

        [JsonProperty("traitid")]
        string traitEnumIntStr;
        public CreatureTrait Trait
        {
            get
            {
                return CreatureTrait.FromEnumIntStr(traitEnumIntStr);
            }
            set
            {
                traitEnumIntStr = value.ToInt32().ToString();
            }
        }
        [JsonProperty("traitvalue")]
        public int Value;

        public static int GenerateNewTraitValueId(GrangerContext context)
        {
            try
            {
                return context.TraitValues.Max(x => x.Id) + 1;
            }
            catch (InvalidOperationException)
            {
                return 1;
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<screens xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="http://ofbiz.apache.org/dtds/widget-screen.xsd">

    <screen name="APDashboard">

            <actions>
                <set field="activeSubMenuItem" value="apmain"/>
                <set field="invoiceTypeId" value="PURCHASE_INVOICE"/>
                <set field="titleProperty" value="CommonOverview"/>
            </actions>
            <widgets>
                <decorator-screen name="CommonApDecorator" location="${parameters.mainDecoratorLocation}">
                    <decorator-section name="body">

                            <actions>
                                <set field="organizationPartyId" from-field="organizationPartyId" default-value="${defaultOrganizationPartyId}"/>


text:
require File.expand_path(File.dirname(__FILE__) + '/../acceptance_helper')

feature "API 1.0 map layers management" do

  before(:all) do
    Capybara.current_driver = :rack_test
    @user  = create_user({:username => 'test'})
  end

  before(:each) do
    delete_user_data @user
    @table = create_table(:user_id => @user.id)
    @map = create_map(:user_id => @user.id, :table_id => @table.id)
  end

  scenario "Create a new layer associated to a map" do
    opts = { "type" => "GMapsBase", "base_type" => "roadmap", "style" => "null", "order" => "0" }
    infowindow = ['column1', 'column2', 'column3']

    post_json v1_map_layers_url(:host => CartoDB.hostname.sub('http://', ''), :api_key => api_key, :map_id => @map.id), {
      :kind => 'gmapsbase',
      :infowindow => infowindow,
      :options => opts } do |response|
      response.status.should be_success
      @map.layers.size.should == 1
      response.body[:id].should == @map.layers.first.id
      response.body[:options].should == opts
      response.body[:infowindow].should == infowindow
      response.body[:order].should == 0
      response.body[:kind].should == 'gmapsbase'
    end
  end

  scenario "Get layer information" do
    layer = Layer.create :kind => 'carto', :order => 1
    @map.add_layer layer

    get_json v1_map_layer_url(:host => CartoDB.hostname.sub('http://', ''), :api_key => api_key, :id => layer.id, :map_id => @map.id) do |response|
      response.status.should be_success
      response.body[:id].should == layer.id
      response.body[:kind].should == 'carto'
      response.body[:order].should == 1
    end
  end

  scenario "Get all map layers" do
    layer  = Layer.create :kind => 'carto', :order => 3
    layer2 = Layer.create :kind => 'tiled', :order => 2
    layer3 = Layer.create :kind => 'tiled', :order => 1
    @map.add_layer layer
    @map.add_layer layer2
    @map.add_layer layer3

    get_json v1_map_layers_url(:host => CartoDB.hostname.sub('http://', ''), :api_key => api_key, :map_id => @map.id) do |response|
      response.status.should be_success
      response.body[:total_entries].should == 3
      response.body[:layers].size.should == 3
      response.body[:layers][0]['id'].should == layer3.id
      response.body[:layers][1]['id'].should == layer2.id
      response.body[:layers][2]['id'].should == layer.id
    end
  end

  scenario "Update a layer" do
    layer = Layer.create :kind => 'carto', :order => 0
    @map.add_layer layer

    put_json v1_map_layer_url(:host => CartoDB.hostname.sub('http://', ''), :api_key => api_key, :id => layer.id, :map_id => @map.id), {
      :options => { :opt1 => 'value' },
      :infowindow => ['column1', 'column2'],
      :order => 3,
      :kind => 'carto' } do |response|
      response.status.should be_success
      response.body[:id].should == layer.id
      response.body[:options].should == { 'opt1' => 'value' }
      response.body[:infowindow].should == ['column1', 'column2']
      response.body[:kind].should == 'carto'
      response.body[:order].should == 3
    end
  end

  scenario "Drop a layer" do
    layer = Layer.create :kind => 'carto'
    @map.add_layer layer

    delete_json v1_map_layer_url(:host => CartoDB.hostname.sub('http://', ''), :api_key => api_key, :id => layer.id, :map_id => @map.id) do |response|
      response.status.should be_success
      expect { layer.refresh }.to raise_error
    end
  end
end


text:
/* ###
 * IP: GHIDRA
 *
 * 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.
 */
package agent.dbgeng.jna.dbgeng.event;

import com.sun.jna.Pointer;
import com.sun.jna.WString;
import com.sun.jna.platform.win32.Guid.IID;
import com.sun.jna.platform.win32.WinDef.*;
import com.sun.jna.platform.win32.WinNT.HRESULT;

import agent.dbgeng.jna.dbgeng.WinNTExtra.EXCEPTION_RECORD64;
import agent.dbgeng.jna.dbgeng.breakpoint.WrapIDebugBreakpoint2;

public interface IDebugEventContextCallbacks {
	final IID IID_IDEBUG_EVENT_CONTEXT_CALLBACKS = new IID("61a4905b-23f9-4247-b3c5-53d087529ab7");

	HRESULT GetInterestMask(ULONGByReference Mask);

	HRESULT Breakpoint(WrapIDebugBreakpoint2.ByReference Bp, Pointer Context, ULONG ContextSize);

	HRESULT Exception(EXCEPTION_RECORD64.ByReference Exception, ULONG FirstChance, Pointer Context,
			ULONG ContextSize);

	HRESULT CreateThread(ULONGLONG Handle, ULONGLONG DataOffset, ULONGLONG StartOffset,
			Pointer Context, ULONG ContextSize);

	HRESULT ExitThread(ULONG ExitCode, Pointer Context, ULONG ContextSize);

	HRESULT CreateProcess(ULONGLONG ImageFileHandle, ULONGLONG Handle, ULONGLONG BaseOffset,
			ULONG ModuleSize, WString ModuleName, WString ImageName, ULONG CheckSum,
			ULONG TimeDateStamp, ULONGLONG InitialThreadHandle, ULONGLONG ThreadDataOffset,
			ULONGLONG StartOffset, Pointer Context, ULONG ContextSize);

	HRESULT ExitProcess(ULONG ExitCode, Pointer Context, ULONG ContextSize);

	HRESULT LoadModule(ULONGLONG ImageFileHandle, ULONGLONG BaseOffset, ULONG ModuleSize,
			WString ModuleName, WString ImageName, ULONG CheckSum, ULONG TimeDateStamp,
			Pointer Context, ULONG ContextSize);

	HRESULT UnloadModule(WString ImageBaseName, ULONGLONG BaseOffset, Pointer Context,
			ULONG ContextSize);

	HRESULT SystemError(ULONG Error, ULONG Level, Pointer Context, ULONG ContextSize);

	HRESULT SessionStatus(ULONG Status);

	HRESULT ChangeDebuggeeState(ULONG Flags, ULONGLONG Argument, Pointer Context,
			ULONG ContextSize);

	HRESULT ChangeEngineState(ULONG Flags, ULONGLONG Argument, Pointer Context, ULONG ContextSize);

	HRESULT ChangeSymbolState(ULONG Flags, ULONGLONG Argument);
}


text:
'use strict';

angular.module('mean.workspace', []);


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ldml SYSTEM "http://www.unicode.org/cldr/dtd/1.6/ldml.dtd">
<ldml>
	<identity>
		<version number="$Revision: 1.57 $"/>
		<generation date="$Date: 2008/06/15 08:09:47 $"/>
		<language type="en"/>
		<territory type="BE"/>
	</identity>
	<dates>
		<calendars>
			<calendar type="gregorian">
				<dateFormats>
					<dateFormatLength type="full">
						<dateFormat>
							<pattern>EEEE d MMMM yyyy</pattern>
						</dateFormat>
					</dateFormatLength>
					<dateFormatLength type="long">
						<dateFormat>
							<pattern>d MMM yyyy</pattern>
						</dateFormat>
					</dateFormatLength>
					<dateFormatLength type="medium">
						<dateFormat>
							<pattern>dd MMM yyyy</pattern>
						</dateFormat>
					</dateFormatLength>
					<dateFormatLength type="short">
						<dateFormat>
							<pattern>dd/MM/yy</pattern>
						</dateFormat>
					</dateFormatLength>
				</dateFormats>
				<timeFormats>
					<timeFormatLength type="full">
						<timeFormat>
							<pattern>HH 'h' mm 'min' ss 's' v</pattern>
						</timeFormat>
					</timeFormatLength>
					<timeFormatLength type="long">
						<timeFormat>
							<pattern>HH:mm:ss z</pattern>
						</timeFormat>
					</timeFormatLength>
					<timeFormatLength type="medium">
						<timeFormat>
							<pattern>HH:mm:ss</pattern>
						</timeFormat>
					</timeFormatLength>
					<timeFormatLength type="short">
						<timeFormat>
							<pattern>HH:mm</pattern>
						</timeFormat>
					</timeFormatLength>
				</timeFormats>
				<dateTimeFormats>
					<availableFormats>
						<dateFormatItem id="MMdd">dd/MM</dateFormatItem>
					</availableFormats>
					<intervalFormats>
						<intervalFormatFallback>{0} - {1}</intervalFormatFallback>
						<intervalFormatItem id="M">
							<greatestDifference id="M">M-M</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="MEd">
							<greatestDifference id="M">E dd/MM - E dd/MM</greatestDifference>
							<greatestDifference id="d">E dd/MM - E dd/MM</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="MMM">
							<greatestDifference id="M">MMM-MMM</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="MMMEd">
							<greatestDifference id="M">E d MMM - E d MMM</greatestDifference>
							<greatestDifference id="d">E d - E d MMM</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="MMMd">
							<greatestDifference id="M">d MMM - d MMM</greatestDifference>
							<greatestDifference id="d">d-d MMM</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="Md">
							<greatestDifference id="M">dd/MM - dd/MM</greatestDifference>
							<greatestDifference id="d">dd/MM - dd/MM</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="d">
							<greatestDifference id="d">d-d</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="h">
							<greatestDifference id="h">HH-HH</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="hm">
							<greatestDifference id="h">HH:mm-HH:mm</greatestDifference>
							<greatestDifference id="m">HH:mm-HH:mm</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="hmv">
							<greatestDifference id="h">HH:mm-HH:mm v</greatestDifference>
							<greatestDifference id="m">HH:mm-HH:mm v</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="hv">
							<greatestDifference id="h">HH-HH v</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="y">
							<greatestDifference id="y">y-y</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="yM">
							<greatestDifference id="M">MM/yy - MM/yy</greatestDifference>
							<greatestDifference id="y">MM/yy - MM/yy</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="yMEd">
							<greatestDifference id="M">E dd/MM/yy - E dd/MM/yy</greatestDifference>
							<greatestDifference id="d">E dd/MM/yy - E dd/MM/yy</greatestDifference>
							<greatestDifference id="y">E dd/MM/yy - E dd/MM/yy</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="yMMM">
							<greatestDifference id="M">MMM-MMM yyyy</greatestDifference>
							<greatestDifference id="y">MMM yyyy - MMM yyyy</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="yMMMEd">
							<greatestDifference id="M">E d MMM - E d MMM yyyy</greatestDifference>
							<greatestDifference id="d">E d - E d MMM yyyy</greatestDifference>
							<greatestDifference id="y">E d MMM yyyy - E d MMM yyyy</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="yMMMd">
							<greatestDifference id="M">d MMM - d MMM yyyy</greatestDifference>
							<greatestDifference id="d">d-d MMM yyyy</greatestDifference>
							<greatestDifference id="y">d MMM yyyy - d MMM yyyy</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="yMd">
							<greatestDifference id="M">dd/MM/yy - dd/MM/yy</greatestDifference>
							<greatestDifference id="d">dd/MM/yy - dd/MM/yy</greatestDifference>
							<greatestDifference id="y">dd/MM/yy - dd/MM/yy</greatestDifference>
						</intervalFormatItem>
					</intervalFormats>
				</dateTimeFormats>
			</calendar>
		</calendars>
	</dates>
	<numbers>
		<symbols>
			<decimal>,</decimal>
			<group>.</group>
		</symbols>
		<currencyFormats>
			<currencyFormatLength>
				<currencyFormat>
					<pattern>#,##0.00 ¤</pattern>
				</currencyFormat>
			</currencyFormatLength>
		</currencyFormats>
		<currencies>
			<currency type="BEF">
				<pattern>#,##0.00 ¤;-#,##0.00 ¤</pattern>
				<decimal>,</decimal>
				<group>.</group>
			</currency>
		</currencies>
	</numbers>
</ldml>


text:
class BackgroundModeManager;
class CRLSetFetcher;
class IOThread;
class MHTMLGenerationManager;
class NotificationUIManager;
class PrefService;
class WatchDogThread;

namespace content {
class NotificationService;
}

namespace policy {
class BrowserPolicyConnector;
class PolicyService;
}

namespace prerender {
class PrerenderTracker;
}

namespace ui {
class Clipboard;
}

class TestingBrowserProcess : public BrowserProcess {
 public:
  TestingBrowserProcess();
  virtual ~TestingBrowserProcess();

  virtual void ResourceDispatcherHostCreated() OVERRIDE;
  virtual void EndSession() OVERRIDE;
  virtual MetricsService* metrics_service() OVERRIDE;
  virtual IOThread* io_thread() OVERRIDE;
  virtual WatchDogThread* watchdog_thread() OVERRIDE;
  virtual ProfileManager* profile_manager() OVERRIDE;
  virtual PrefService* local_state() OVERRIDE;
  virtual chrome_variations::VariationsService* variations_service() OVERRIDE;
  virtual policy::BrowserPolicyConnector* browser_policy_connector() OVERRIDE;
  virtual policy::PolicyService* policy_service() OVERRIDE;
  virtual IconManager* icon_manager() OVERRIDE;
  virtual ThumbnailGenerator* GetThumbnailGenerator() OVERRIDE;
  virtual BackgroundModeManager* background_mode_manager() OVERRIDE;
  virtual StatusTray* status_tray() OVERRIDE;
  virtual SafeBrowsingService* safe_browsing_service() OVERRIDE;
  virtual safe_browsing::ClientSideDetectionService*
      safe_browsing_detection_service() OVERRIDE;
  virtual net::URLRequestContextGetter* system_request_context() OVERRIDE;

#if defined(OS_CHROMEOS)
  virtual chromeos::OomPriorityManager* oom_priority_manager() OVERRIDE;
#endif  // defined(OS_CHROMEOS)

  virtual ui::Clipboard* clipboard() OVERRIDE;
  virtual ExtensionEventRouterForwarder*
      extension_event_router_forwarder() OVERRIDE;
  virtual NotificationUIManager* notification_ui_manager() OVERRIDE;
  virtual IntranetRedirectDetector* intranet_redirect_detector() OVERRIDE;
  virtual AutomationProviderList* GetAutomationProviderList() OVERRIDE;
  virtual void InitDevToolsHttpProtocolHandler(
      Profile* profile,
      const std::string& ip,
      int port,
      const std::string& frontend_url) OVERRIDE;
  virtual unsigned int AddRefModule() OVERRIDE;
  virtual unsigned int ReleaseModule() OVERRIDE;
  virtual bool IsShuttingDown() OVERRIDE;
  virtual printing::PrintJobManager* print_job_manager() OVERRIDE;
  virtual printing::PrintPreviewTabController*
      print_preview_tab_controller() OVERRIDE;
  virtual printing::BackgroundPrintingManager*
      background_printing_manager() OVERRIDE;
  virtual const std::string& GetApplicationLocale() OVERRIDE;
  virtual void SetApplicationLocale(const std::string& app_locale) OVERRIDE;
  virtual DownloadStatusUpdater* download_status_updater() OVERRIDE;
  virtual DownloadRequestLimiter* download_request_limiter() OVERRIDE;
  virtual bool plugin_finder_disabled() const OVERRIDE;

#if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
  virtual void StartAutoupdateTimer() OVERRIDE {}
#endif

  virtual ChromeNetLog* net_log() OVERRIDE;
  virtual prerender::PrerenderTracker* prerender_tracker() OVERRIDE;
  virtual ComponentUpdateService* component_updater() OVERRIDE;
  virtual CRLSetFetcher* crl_set_fetcher() OVERRIDE;

  // Set the local state for tests. Consumer is responsible for cleaning it up
  // afterwards (using ScopedTestingLocalState, for example).
  void SetLocalState(PrefService* local_state);
  void SetProfileManager(ProfileManager* profile_manager);
  void SetIOThread(IOThread* io_thread);
  void SetBrowserPolicyConnector(policy::BrowserPolicyConnector* connector);
  void SetSafeBrowsingService(SafeBrowsingService* sb_service);

 private:
  scoped_ptr<content::NotificationService> notification_service_;
  unsigned int module_ref_count_;
  scoped_ptr<ui::Clipboard> clipboard_;
  std::string app_locale_;

  // Weak pointer.
  PrefService* local_state_;
  scoped_ptr<policy::BrowserPolicyConnector> browser_policy_connector_;
  scoped_ptr<policy::PolicyService> policy_service_;
  scoped_ptr<ProfileManager> profile_manager_;
  scoped_ptr<NotificationUIManager> notification_ui_manager_;
  scoped_ptr<printing::BackgroundPrintingManager> background_printing_manager_;
  scoped_refptr<printing::PrintPreviewTabController>
      print_preview_tab_controller_;
  scoped_ptr<prerender::PrerenderTracker> prerender_tracker_;
  IOThread* io_thread_;
  scoped_refptr<SafeBrowsingService> sb_service_;

  DISALLOW_COPY_AND_ASSIGN(TestingBrowserProcess);
};

#endif  // CHROME_TEST_BASE_TESTING_BROWSER_PROCESS_H_


text:
package jat.coreNOSA.measurements;

import jat.coreNOSA.algorithm.estimators.EKF;
import jat.coreNOSA.algorithm.estimators.MeasurementFileModel;
import jat.coreNOSA.algorithm.estimators.MeasurementModel;
import jat.coreNOSA.math.MatrixVector.data.VectorN;
import jat.coreNOSA.simulation.EstimatorSimModel;
import jat.coreNOSA.simulation.initializer;

import java.util.HashMap;
import java.util.Random;

public class GPSStateMeasurementModel implements MeasurementFileModel,MeasurementModel{

	public static VectorN R;
	public static int numStates;
	HashMap hm;// = closedLoopSim.hm;
	//* *NOTE* Added argument to default constructor instead of call to static var at instantiation
	Random generator;
	private int FILTER_states;

	public GPSStateMeasurementModel(HashMap h) {
		/*Add a sleep in here to insure that the Random Number
		 * Seeds don't allign with any other random number generator
		 */
		hm = h;
		this.FILTER_states = initializer.parseInt(hm,"FILTER.states");
		try {
			Thread.sleep(20);
			generator = new Random();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}
	}

	public VectorN getMeasurement()
	{
		String tmp;
		VectorN pointSolution = new VectorN(3);

		tmp = "MEAS."+EKF.measNum+".satellite";
		int sat = initializer.parseInt(hm,tmp);

		//double[] truth = closedLoopSim.truth[sat].sc.get_spacecraft().toStateVector();
		double[] truth = EstimatorSimModel.truth[sat].get_spacecraft().toStateVector();

		//Add in the measurement noise read out of the file
		for(int j = 0; j < 3; j++)
		{
			tmp = "MEAS."+EKF.measNum+".R."+j;
			double R = initializer.parseDouble(hm,tmp);

			/*Scale the error as Gaussian noise times the
			 square of the measurement noise*/
			//* TODO .nextGaussian() is already zero mean
			pointSolution.x[j] =  truth[j] +(2*(generator.nextGaussian()-0.5))*R*R;
		}
		return pointSolution;
	}

	public VectorN predictMeasurement(VectorN state){

			String tmp = "MEAS."+EKF.measNum+".satellite";
			int sat = initializer.parseInt(hm,tmp);

			VectorN range = new VectorN(3);
			range.set(0,state.get(0+(6*sat)));
			range.set(1,state.get(1+(6*sat)));
			range.set(2,state.get(2+(6*sat)));

			return range;
	}
	public VectorN predictMeasurement(int sat,VectorN state){

		//String tmp = "MEAS."+EKF.measNum+".satellite";
		//int sat = initializer.parseInt(hm,tmp);

		VectorN range = new VectorN(3);
		range.set(0,state.get(0+(6*sat)));
		range.set(1,state.get(1+(6*sat)));
		range.set(2,state.get(2+(6*sat)));

		return range;
}

	public double  zPred(int i, double time, VectorN state){
		String tmp = "MEAS."+EKF.measNum+".satellite";
		int sat = initializer.parseInt(hm,tmp);

		VectorN oMinusC;
		VectorN pred = predictMeasurement(state);
		VectorN obs = getMeasurement();
		oMinusC      = obs.minus(pred);

		//Ensure we are returning the correct state when there is more than
		//one satellite
		int j = i - 6*sat;
		return oMinusC.get(j);
	}
	public double  zPred(ObservationMeasurement om,int i, double time, VectorN state){
		//String tmp = "MEAS."+om.get_sc_id()+".satellite";
		//int sat = initializer.parseInt(hm,tmp);
		int whichState = om.get_whichState();		//* Note i = GPS_PRN  om.get_sc_id() = Sim_SC_ID
		VectorN oMinusC;
		VectorN pred = predictMeasurement(om.get_sc_id(),state);
		VectorN obs = om.get_state(3);
		oMinusC      = obs.minus(pred);

		//Ensure we are returning the correct state when there is more than
		//one satellite
		//int j = i - 6*sat;
		//return oMinusC.get(j);
		return oMinusC.get(whichState);
	}

	/** Return the measurement noise value for this measurement
	 *
	 *
	 */
	public double R()
	{
		int whichState = EKF.stateNum;
		int measNum    = EKF.measNum;

		//Ensure we are returning the correct state when there is more than
		//one satellite
		String tmp = "MEAS."+EKF.measNum+".satellite";
		int sat = initializer.parseInt(hm,tmp);
		int j = whichState - 6*sat;

		tmp = "MEAS."+measNum+".R."+j;
		double R = initializer.parseDouble(hm,tmp);
		return R;
	}
	/** Return the measurement noise value for this measurement
	 *
	 *
	 */
	public double R(ObservationMeasurement om)
	{
		int whichState = om.get_whichState();//EKF.stateNum;
		int measNum    = 0;//EKF.measNum;
		double R=0.0;

		try{
		//Ensure we are returning the correct state when there is more than
		//one satellite
		String tmp = "MEAS."+measNum+".satellite";
		int sat = initializer.parseInt(hm,tmp);
		int j = whichState - 6*sat;

		tmp = "MEAS."+measNum+".R."+j;
		R = initializer.parseDouble(hm,tmp);
		}catch(NumberFormatException e){
			System.err.println("Warning: Number format exception - return zero noise");
			//System.exit(0);
		}catch(NullPointerException ne){
			System.err.println("Warning: Null pointer exception - return zero noise");
			//System.exit(0);
		}
		return R;
	}

	public VectorN H(VectorN state)
	{
		/*Determine the number of states*/
		int whichState = EKF.stateNum;
		int numStates = initializer.parseInt(hm,"FILTER.states");

		/*for a Range measurement, the current state has H = 1, all other states H = 0 */
		VectorN H = new VectorN(numStates);
		H.set(0.0);
		H.set(whichState,1.0);
		return H;
	}
	public VectorN H(ObservationMeasurement om, VectorN state)
	{
		/*Determine the number of states*/
		int whichState = om.get_whichState();//EKF.stateNum;
		int numStates = this.FILTER_states;//initializer.parseInt(hm,"FILTER.states");

		/*for a Range measurement, the current state has H = 1, all other states H = 0 */
		VectorN H = new VectorN(numStates);
		H.set(0.0);
		H.set(whichState,1.0);
		return H;
	}

}


text:
import React from 'react';

// Libs
import * as THREE from 'three';
import styled from 'styled-components';
import { Canvas as FiberCanvas } from 'react-three-fiber';

type Props = {
  children: React.ReactNode;
};

const Root = styled(FiberCanvas)`
  height: 100vh;
  width: 100%;
`;

const Canvas: React.FC<Props> = ({ children }: Props) => (
  <Root
    camera={{ fov: 75, position: new THREE.Vector3(-5, 5, 5) }}
    colorManagement
    pixelRatio={window.devicePixelRatio}
    shadowMap
  >
    {children}
  </Root>
);

export default Canvas;


text:
from OpenGL import GL
from cocos.director import director
from .node import GUINode

def _anchor_to_position_a(anchor, window_size, self_size):
  abs_anchor = abs(anchor)
  if isinstance(abs_anchor, int):
    result = abs_anchor
  elif isinstance(abs_anchor, float):
    result = int(window_size * abs_anchor)
  # TODO px, em, etc.?
  if anchor < 0:
    result = window_size - result - self_size
  return result

def _anchor_to_position_c(anchor, window_size, self_size):
  abs_anchor = abs(anchor)
  if isinstance(abs_anchor, int):
    result = abs_anchor
  elif isinstance(abs_anchor, float):
    result = int(window_size * abs_anchor * 0.01) - self_size // 2
  # TODO px, em, etc.?
  if anchor < 0:
    result = window_size - result - self_size
  return result

class AttachedWindow(GUINode):

  def __init__(self, attach=None, **kwargs):
    super(AttachedWindow, self).__init__(**kwargs)
    self.attach = attach

  def get_content_size(self):
    nodes = self.get_nodes()
    if not nodes:
      return (0, 0)
    else:
      return nodes[0].width, nodes[0].height

  def evaluate_position(self):
    if self.attach is not None:
      ww, wh = director.window.width, director.window.height
      sw, sh = self.margin_box[2:4]
      anchor_x, anchor_y = self.attach
      x = _anchor_to_position_a(anchor_x, ww, sw)
      y = _anchor_to_position_a(anchor_y, wh, sh)
      self.position = (x, y)

  def visit(self):
    self.evaluate_position()
    super(AttachedWindow, self).visit()

  #def add(self, child, *args, **kwargs):
    #if len(self.get_children()) >= 1:
      #raise RuntimeError(
        #'Only one child is supported for %s. '
        #'Use layouts to add more objects.' % type(self).__name__)
    #super(AttachedWindow, self).add(child, *args, **kwargs)

class CenteredWindow(AttachedWindow):

  def evaluate_position(self):
    if self.attach is not None:
      ww, wh = director.window.width, director.window.height
      sw, sh = self.margin_box[2:4]
      anchor_x, anchor_y = self.attach
      x = _anchor_to_position_c(anchor_x, ww, sw)
      y = _anchor_to_position_c(anchor_y, wh, sh)
      self.position = (x, y)

class ModalWindow(CenteredWindow):
  def __init__(self, attach=None, fade_color=(0, 0, 0, 128), **kwargs):
    if attach is None:
      attach = (50., 50.) # exact center
    super(ModalWindow, self).__init__(attach=attach, **kwargs)
    self.fade_color = fade_color

  def apply_style(self, **options):
    super(ModalWindow, self).apply_style(**options)
    self.z = 777

  def draw(self):
    ww, wh = 2000, 2000
    GL.glPushMatrix()
    self.transform()
    GL.glPushAttrib(GL.GL_CURRENT_BIT)
    GL.glBegin(GL.GL_QUADS)
    GL.glColor4ubv(self.fade_color)
    map(GL.glVertex2fv, [(-ww, -wh), (ww, -wh), (ww, wh), (-ww, wh)])
    GL.glEnd()
    GL.glPopAttrib()
    GL.glPopMatrix()
    super(ModalWindow, self).draw()

  def on_mouse_press(self, x, y, button, modifiers):
    pass # TODO close itself

  def on_mouse_motion(self, *args):
    return False


text:
package ma.glasnost.orika.test.community;

import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.converter.BidirectionalConverter;
import ma.glasnost.orika.metadata.Type;
import org.junit.Test;

/**
 * problem generic types when subclassing.
 *

 *
 * @see https://github.com/orika-mapper/orika/issues
 */
public class Issue129TestCase {

    @Test
    public void testCustomMapperOneParameter() {
        new StringConverter();
    }

}
abstract class AbstractStringConverter<T> extends BidirectionalConverter<T, String> {}

class StringConverter extends AbstractStringConverter<String> {

    @Override
    public String convertTo(String source, Type<String> destinationType, MappingContext mappingContext) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public String convertFrom(String source, Type<String> destinationType, MappingContext mappingContext) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}


text:
package com.github.maxxkrakoa;

import com.fasterxml.jackson.annotation.JsonPropertyOrder;

/**
 * Created by mv on 2017-09-14.
 */
@JsonPropertyOrder({"TYPE", "CONTENT", "PRIORITY", "INDENT", "AUTHOR", "RESPONSIBLE", "DATE", "DATE_LANG" ,"TIMEZONE"})
public class TodoistLineItemJava {
    public String TYPE;
    public String CONTENT;
    public String PRIORITY;
    public String INDENT;
    public String AUTHOR;
    public String RESPONSIBLE;
    public String DATE;
    public String DATE_LANG;
    public String TIMEZONE;
}


text:
#ifndef DALI_INTERNAL_ANIMATOR_CONNECTOR_BASE_H
#define DALI_INTERNAL_ANIMATOR_CONNECTOR_BASE_H

// INTERNAL INCLUDES
#include <dali/internal/event/common/object-impl.h>
#include <dali/internal/update/common/property-resetter.h>
#include <dali/internal/update/manager/update-manager.h>
#include <dali/public-api/animation/alpha-function.h>
#include <dali/public-api/animation/time-period.h>
#include <dali/public-api/common/dali-common.h>

namespace Dali
{
namespace Internal
{
class Animation;

/**
 * An abstract base class to create animator connectors and property re-setters for them when needed.
 *
 * The scene-graph objects are created by a Object e.g. Actor is a proxy for SceneGraph::Node.
 * AnimatorConnectorBase observes the proxy object, in order to detect when a scene-graph object is created
 * to avoid having unnecessary animations on the scene-graph and allow apps to create animations in initialisation
 */
class AnimatorConnectorBase : public Object::Observer
{
public:
  /**
   * Constructor.
   */
  AnimatorConnectorBase(Object&           object,
                        Property::Index   propertyIndex,
                        int32_t           componentIndex,
                        AlphaFunction     alpha,
                        const TimePeriod& period)
  : mObject(&object),
    mAlphaFunction(alpha),
    mTimePeriod(period),
    mPropertyIndex(propertyIndex),
    mComponentIndex(componentIndex)
  {
    object.AddObserver(*this);
  }

  /**
   * Virtual destructor.
   */
  ~AnimatorConnectorBase() override
  {
    if(mObject)
    {
      mObject->RemoveObserver(*this);
    }
  }

  /**
   * Helper function to create a Scenegraph::Animator and PropertyResetter and add it to its correspondent
   * SceneGraph::Animation.
   *
   * @note This function will only be called the first time the object is added to the scene or at creation time if
   * the object was already in the scene
   */
  void CreateAnimator()
  {
    DALI_ASSERT_DEBUG(mAnimator == nullptr);
    DALI_ASSERT_DEBUG(mParent != nullptr);

    //Get the PropertyOwner the animator is going to animate
    const SceneGraph::PropertyOwner& propertyOwner = mObject->GetSceneObject();

    // Get SceneGraph::BaseProperty
    const SceneGraph::PropertyBase* baseProperty = mObject->GetSceneObjectAnimatableProperty(mPropertyIndex);
    DALI_ASSERT_ALWAYS(baseProperty && "Property is not animatable");

    // Check if property is a component of another property
    const int32_t componentIndex = mObject->GetPropertyComponentIndex(mPropertyIndex);
    if(componentIndex != Property::INVALID_COMPONENT_INDEX)
    {
      mComponentIndex = componentIndex;
    }

    // call the type specific method to create the concrete animator
    bool resetterRequired = DoCreateAnimator(propertyOwner, *baseProperty);

    DALI_ASSERT_DEBUG(mAnimator != nullptr);

    // Add the new SceneGraph::Animator to its correspondent SceneGraph::Animation via message
    const SceneGraph::Animation* animation = mParent->GetSceneObject();
    DALI_ASSERT_DEBUG(nullptr != animation);
    AddAnimatorMessage(mParent->GetEventThreadServices(), *animation, *mAnimator);

    // Add the new SceneGraph::PropertyResetter to the update manager via message
    if(resetterRequired)
    {
      OwnerPointer<SceneGraph::PropertyResetterBase> resetter = SceneGraph::AnimatorResetter::New(propertyOwner, *baseProperty, *mAnimator);
      AddResetterMessage(mParent->GetEventThreadServices().GetUpdateManager(), resetter);
    }
  }

  /**
   * Type specific extension of animator creation
   */
  virtual bool DoCreateAnimator(const SceneGraph::PropertyOwner& propertyOwner, const SceneGraph::PropertyBase& baseProperty) = 0;

  /**
   * Set the parent of the AnimatorConnector.
   * @pre The connector does not already have a parent.
   * @param [in] parent The parent object.
   */
  void SetParent(Animation& parent)
  {
    DALI_ASSERT_ALWAYS(mParent == nullptr && "AnimationConnector already has a parent");
    mParent = &parent;

    if(mObject)
    {
      CreateAnimator();
    }
  }

  /**
   * Retrieve the parent of the AnimatorConnector.
   * @return The parent object, or nullptr.
   */
  Animation* GetParent() const
  {
    return mParent;
  }

  Object* GetObject() const
  {
    return mObject;
  }

  Property::Index GetPropertyIndex() const
  {
    return mPropertyIndex;
  }

  int32_t GetComponentIndex() const
  {
    return mComponentIndex;
  }

private:
  /**
   * From Object::Observer
   */
  void SceneObjectAdded(Object& object) final
  {
    // If the animator has not been created yet, create it now.
    if(!mAnimator && mObject)
    {
      CreateAnimator();
    }
  }

  /**
   * From Object::Observer
   */
  void SceneObjectRemoved(Object& object) final
  {
  }

  /**
   * From Object::Observer
   */
  void ObjectDestroyed(Object& object) override
  {
    mObject = nullptr;
  }

protected:
  Animation*                mParent{nullptr}; ///< The parent owns the connector.
  Object*                   mObject;          ///< Not owned by the animator connector. Valid until ObjectDestroyed() is called.
  SceneGraph::AnimatorBase* mAnimator{nullptr};

  AlphaFunction mAlphaFunction;
  TimePeriod    mTimePeriod;

  Property::Index mPropertyIndex;
  int32_t         mComponentIndex;
};

} // namespace Internal

} // namespace Dali

#endif // DALI_INTERNAL_ANIMATOR_CONNECTOR_BASE_H


text:
package com.github.neuralnetworks.calculation.operations.aparapi;

import com.amd.aparapi.Kernel;
import com.github.neuralnetworks.calculation.operations.TensorFunction;
import com.github.neuralnetworks.tensor.Tensor;
import com.github.neuralnetworks.util.Environment;

/**
 * Base aparapi tensor function
 */
public abstract class AparapiTensorFunction extends Kernel implements TensorFunction
{

	private static final long serialVersionUID = 1L;

	protected float[] elements;
	protected int startIndex;

	@Override
	public void value(Tensor inputOutput)
	{
		if (elements == null || elements != inputOutput.getElements())
		{
			elements = inputOutput.getElements();
			startIndex = inputOutput.getStartIndex();
		}

		Environment.getInstance().getRuntimeConfiguration().getAparapiConfiguration().getExecutionStrategy().execute(this, inputOutput.getSize());
	}
}


text:
typedef UIViewController *(^ActiveTopController)(void);
typedef UINavigationController *(^ActiveNavigationController)(void);
typedef UITabBarController *(^ActiveTabBarController)(void);
typedef void (^FinderResetStatus)(void);

@protocol MSActiveControllerFinder <NSObject>

@property (nonatomic, copy) ActiveTopController activeTopController;
@property (nonatomic, copy) ActiveNavigationController activeNavigationController;
@property (nonatomic, copy) ActiveTabBarController activeTabBarController;
@property (nonatomic, copy) ActiveTabBarController rootTabBarController;
@property (nonatomic, copy) FinderResetStatus resetStatus;

@end

@interface MSActiveControllerFinder : NSObject <MSActiveControllerFinder>

@property (nonatomic, copy) ActiveTopController activeTopController;
@property (nonatomic, copy) ActiveNavigationController activeNavigationController;
@property (nonatomic, copy) ActiveTabBarController activeTabBarController;
@property (nonatomic, copy) ActiveTabBarController rootTabBarController;
@property (nonatomic, copy) FinderResetStatus resetStatus;

//
// 注意使用+sharedFinder, +setSharedFinder: 代替+finder, +setFinder:
// 后面会显式淘汰
//
+ (void)setSharedFinder:(id<MSActiveControllerFinder>)finder;
+ (instancetype)sharedFinder;

+ (void)setFinder:(id<MSActiveControllerFinder>)finder;
+ (instancetype)finder;

@end


text:
layout: post
title: '#10 Pulse of Design Exploration with Linus Lim'
categories:
- Learning
---

A Friday night out and dinner with Linus! I took him on a tour of the [heartland university](http://www.smu.edu.sg/) and we sat down chatting on his Pulses of Design Exploration.

Linus Lim is a web designer, a [Fireworks enthusiast](http://fireworksinterviews.com/) and [Creative Crew](http://creativecrew.org.sg/) VP, he has been my mentor in picking web design tools! So I thought of catching a dinner with him and ask him his journey on design exploration and some of the tools he loves to use. So let's hear from Linus about his design exploration on drawing, [Free Hand](http://www.adobe.com/products/freehand/), printing, [Photoshop](http://www.adobe.com/products/photoshop.html), [Flash](http://www.adobe.com/products/flash.html), Visual Arts and of course [Fireworks](http://www.adobe.com/products/fireworks.html).

![With Linus](/img/pulse10-linus.jpg)

Connect with Linus through [Facebook](http://www.facebook.com/chunwui), [Twitter](http://twitter.com/chunwui), [Blog](http://chunwui.posterous.com), [Fireworks Interviews](http://fireworksinterviews.com/) and [Creative Crew](http://creativecrew.org.sg/).

<audio controls="controls">
  <source src="/audio/Pulse-Ep10-200911.mp3" type="audio/mpeg">
</audio>


text:
package org.scalajs.testsuite.niobuffer

import java.nio._

import scala.language.implicitConversions
import scala.reflect._

sealed abstract class BufferFactory {
  type BufferType <: Buffer with Comparable[BufferType]
  type ElementType

  implicit val elemClassTag: ClassTag[ElementType]

  implicit def elemFromInt(value: Int): ElementType

  implicit def elemToAnyRef(elem: ElementType): AnyRef

  implicit def bufferAdapter(
      buffer: BufferType): BufferAdapter[BufferType, ElementType]

  def boxed(array: Array[ElementType]): Array[AnyRef] =
    array.map(elemToAnyRef)

  def boxedElemsFromInt(elems: Int*): Array[AnyRef] =
    boxed(elems.map(elemFromInt).toArray)

  val createsReadOnly: Boolean = false

  def allocBuffer(capacity: Int): BufferType

  def allocBuffer(pos: Int, limit: Int, capacity: Int): BufferType = {
    val buf = allocBuffer(capacity)
    buf.limit(limit).position(pos)
    buf
  }

  def elemRange(start: Int, end: Int): Array[ElementType] =
    (start until end).map(elemFromInt).toArray

  def withContent(capacity: Int, content: ElementType*): BufferType =
    withContent(0, capacity, capacity, content: _*)

  def withContent(pos: Int, limit: Int, capacity: Int,
      content: ElementType*): BufferType = {
    val buf = allocBuffer(pos, limit, capacity)
    buf.put(content.toArray)
    buf.position(pos)
    buf
  }
}

object BufferFactory {
  abstract class ByteBufferFactory extends BufferFactory {
    type BufferType = ByteBuffer
    type ElementType = Byte

    implicit val elemClassTag: ClassTag[ElementType] = ClassTag.Byte

    implicit def elemFromInt(value: Int): ElementType = value.toByte

    implicit def elemToAnyRef(elem: ElementType): AnyRef = elem: java.lang.Byte

    implicit def bufferAdapter(
        buffer: BufferType): BufferAdapter[BufferType, ElementType] =
      new BufferAdapter.ByteBufferAdapater(buffer)
  }

  abstract class CharBufferFactory extends BufferFactory {
    type BufferType = CharBuffer
    type ElementType = Char

    implicit val elemClassTag: ClassTag[ElementType] = ClassTag.Char

    implicit def elemFromInt(value: Int): ElementType = value.toChar

    implicit def elemToAnyRef(elem: ElementType): AnyRef = elem: java.lang.Character

    implicit def bufferAdapter(
        buffer: BufferType): BufferAdapter[BufferType, ElementType] =
      new BufferAdapter.CharBufferAdapater(buffer)
  }

  abstract class ShortBufferFactory extends BufferFactory {
    type BufferType = ShortBuffer
    type ElementType = Short

    implicit val elemClassTag: ClassTag[ElementType] = ClassTag.Short

    implicit def elemFromInt(value: Int): ElementType = value.toShort

    implicit def elemToAnyRef(elem: ElementType): AnyRef = elem: java.lang.Short

    implicit def bufferAdapter(
        buffer: BufferType): BufferAdapter[BufferType, ElementType] =
      new BufferAdapter.ShortBufferAdapater(buffer)
  }

  abstract class IntBufferFactory extends BufferFactory {
    type BufferType = IntBuffer
    type ElementType = Int

    implicit val elemClassTag: ClassTag[ElementType] = ClassTag.Int

    implicit def elemFromInt(value: Int): ElementType = value.toInt

    implicit def elemToAnyRef(elem: ElementType): AnyRef = elem: java.lang.Integer

    implicit def bufferAdapter(
        buffer: BufferType): BufferAdapter[BufferType, ElementType] =
      new BufferAdapter.IntBufferAdapater(buffer)
  }

  abstract class LongBufferFactory extends BufferFactory {
    type BufferType = LongBuffer
    type ElementType = Long

    implicit val elemClassTag: ClassTag[ElementType] = ClassTag.Long

    implicit def elemFromInt(value: Int): ElementType = value.toLong

    implicit def elemToAnyRef(elem: ElementType): AnyRef = elem: java.lang.Long

    implicit def bufferAdapter(
        buffer: BufferType): BufferAdapter[BufferType, ElementType] =
      new BufferAdapter.LongBufferAdapater(buffer)
  }

  abstract class FloatBufferFactory extends BufferFactory {
    type BufferType = FloatBuffer
    type ElementType = Float

    implicit val elemClassTag: ClassTag[ElementType] = ClassTag.Float

    implicit def elemFromInt(value: Int): ElementType = value.toFloat

    implicit def elemToAnyRef(elem: ElementType): AnyRef = elem: java.lang.Float

    implicit def bufferAdapter(
        buffer: BufferType): BufferAdapter[BufferType, ElementType] =
      new BufferAdapter.FloatBufferAdapater(buffer)
  }

  abstract class DoubleBufferFactory extends BufferFactory {
    type BufferType = DoubleBuffer
    type ElementType = Double

    implicit val elemClassTag: ClassTag[ElementType] = ClassTag.Double

    implicit def elemFromInt(value: Int): ElementType = value.toDouble

    implicit def elemToAnyRef(elem: ElementType): AnyRef = elem: java.lang.Double

    implicit def bufferAdapter(
        buffer: BufferType): BufferAdapter[BufferType, ElementType] =
      new BufferAdapter.DoubleBufferAdapater(buffer)
  }

  trait WrappedBufferFactory extends BufferFactory {
    protected def baseWrap(array: Array[ElementType]): BufferType

    protected def baseWrap(array: Array[ElementType],
        offset: Int, length: Int): BufferType

    def allocBuffer(capacity: Int): BufferType =
      baseWrap(new Array[ElementType](capacity))

    override def allocBuffer(pos: Int, limit: Int, capacity: Int): BufferType =
      baseWrap(new Array[ElementType](capacity), pos, limit-pos)

    override def withContent(pos: Int, limit: Int, capacity: Int,
        content: ElementType*): BufferType = {
      val after = capacity - (pos + content.size)
      val fullContent =
        (Seq.fill(pos)(elemFromInt(0)) ++
            content ++
            Seq.fill(after)(elemFromInt(0))).toArray
      baseWrap(fullContent, pos, limit - pos)
    }
  }

  trait WrappedTypedArrayBufferFactory extends WrappedBufferFactory {
    protected def baseWrap(array: Array[ElementType],
        offset: Int, length: Int): BufferType = {
      val buf = baseWrap(array)
      buf.limit(offset + length).position(offset)
      buf
    }
  }

  trait ReadOnlyBufferFactory extends BufferFactory {
    override val createsReadOnly = true

    abstract override def allocBuffer(capacity: Int): BufferType =
      super.allocBuffer(capacity).asReadOnlyBuffer()

    override def allocBuffer(pos: Int, limit: Int, capacity: Int): BufferType =
      super.allocBuffer(pos, limit, capacity).asReadOnlyBuffer()

    override def withContent(pos: Int, limit: Int, capacity: Int,
        content: ElementType*): BufferType =
      super.withContent(pos, limit, capacity, content: _*).asReadOnlyBuffer()
  }

  trait SlicedBufferFactory extends BufferFactory {
    abstract override def allocBuffer(capacity: Int): BufferType = {
      if (capacity < 0)
        throw new IllegalArgumentException
      val buf = super.allocBuffer(capacity+25)
      buf.position(17)
      buf.limit(17+capacity)
      buf.slice()
    }

    override def withContent(pos: Int, limit: Int, capacity: Int,
        content: ElementType*): BufferType = {
      if (!(0 <= pos && pos <= limit && limit <= capacity))
        throw new IllegalArgumentException
      val buf = super.allocBuffer(capacity+25)
      buf.position(9+pos)
      buf.put(content.toArray)
      buf.position(9)
      buf.limit(9+capacity)
      val buf2 = buf.slice()
      buf2.position(pos)
      buf2.limit(limit)
      buf2
    }
  }

  trait ByteBufferViewFactory extends BufferFactory {
    def baseAllocBuffer(capacity: Int): BufferType

    def allocBuffer(capacity: Int): BufferType =
      baseAllocBuffer(capacity)

    override def allocBuffer(pos: Int, limit: Int, capacity: Int): BufferType = {
      val buf = baseAllocBuffer(capacity)
      buf.limit(limit).position(pos)
      buf
    }

    override def withContent(pos: Int, limit: Int, capacity: Int,
        content: ElementType*): BufferType = {
      val buf = baseAllocBuffer(capacity)
      buf.limit(limit).position(pos)
      buf.put(content.toArray)
      buf.position(pos)
      buf
    }
  }
}


text:
from extract_image_features.video_utils import *
import numpy as np
from extract_image_features.keras_pretrained_models.imagenet_utils import preprocess_input
from keras.models import Model
from keras.preprocessing import image
from extract_image_features.keras_pretrained_models.vgg19 import VGG19

# file saving and loading destinations change whether you are working on laptop or desktop
USE_TITANX = True
### CHANGE THE FILE TO BE READ HERE!!!!

######## LOADING VIDEO FILENAMES
print ("--- Loading video and audio filenames...")
if USE_TITANX:
    video_dir = '/home/zanoi/ZANOI/auditory_hallucination_videos'
else: # Working on MacBook Pro
    video_dir = "/Volumes/SAMSUNG_SSD_256GB/ADV_CV/2-25_VIDAUD/EXPORTS"

video_files = [os.path.join(video_dir, file_i)
         for file_i in os.listdir(video_dir)
         if file_i.endswith('.mp4')]

num_videos = len(video_files)
print("num_videos: ", num_videos)

######## LOADING AUDIO FILENAMES
audio_feature_dir = "../audio_vectors"

audio_f_files = [os.path.join(audio_feature_dir, file_i)
                for file_i in os.listdir(audio_feature_dir)
                if file_i.endswith('.mat')]

num_audio_f = len(audio_f_files)
print (audio_f_files)
print("num_audio_f: ", num_audio_f)

for audio_idx in range(num_audio_f):  # Loop over all audio files
    audio_prefix, audio_vector_length, audio_features = returnAudioVectors(audio_idx, audio_f_files)

    # Find all the linked videos for the given audio vector
    linked_video_f = findMatchingVideos(audio_prefix, video_files)
    print(audio_f_files[audio_idx])
    print(linked_video_f)

    for video_filename in linked_video_f:
        # Return the angle_name to name the file correctly
        angle_name = returnAngleName(video_filename)
        print ("angle_name:", angle_name)

        # Process the videos linked to a particular audio vector
        ######## PROCESS VIDEO TO BLACK AND WHITE
        print("--- Processing video to greyscale...")
        processed_video = processOneVideo(audio_vector_length, video_filename, normalize=False)
        print("processed_video.shape:", processed_video.shape)

        ######### CONCATENATE INTO SPACETIME IMAGE
        print ("--- Concatenating into Spacetime image...")
        window = 3
        space_time_image = createSpaceTimeImagesforOneVideo(processed_video,window) # (1, 8377, 224, 224, 3)
        print ("space_time_image.shape:", space_time_image.shape)

        ########## RUN THE SPACETIME IMAGES THROUGH VGG19
        print ("--- Running through VGG19 FC2 layer...")
        # Build the model
        base_model = VGG19(weights='imagenet')
        model = Model(input=base_model.input, output=base_model.get_layer('fc1').output)  # Only take the FC2 layer output

        # Preallocate matrix output
        (num_frames, frame_h, frame_w, channels) = space_time_image.shape
        CNN_FC_output = np.zeros((num_frames,1,4096))  # (1,8377,1,4096) -> FC2 outputs dimensions (1,4096)

        for frame_num in tqdm(range(num_frames)):
            img = space_time_image[frame_num]
            x = np.expand_dims(img, axis=0)
            x = preprocess_input(x)
            fc2_features = model.predict(x)  # Predict the FC2 features from VGG19, output shape is (1,4096)

            CNN_FC_output[frame_num] = fc2_features  # Save the FC2 features to a matrix
        print("CNN_FC_output.shape:", CNN_FC_output.shape) # (1,8377,1,4096)

        ########### CREATE FINAL DATASET, concatenate FC output with audio vectors
        # Normalization of the audio_vectors occurs in this function -> Hanoi forgot to normalize in MATLAB!!!!
        final_audio_vector = createAudioVectorDatasetForOneVid(audio_features, space_time_image.shape) #(8377, 18)
        print ("final_audio_vector.shape:", final_audio_vector.shape)

        ############ PACKAGE AND SAVE THE DATASET
        if USE_TITANX:
            data_extern_dest = '/home/zanoi/ZANOI/auditory_hallucinations_data/FC_2_data/'
        else:  # Working on MacBook Pro
            data_extern_dest = '/Volumes/SAMSUNG_SSD_256GB/ADV_CV/data/'
        file_name = data_extern_dest + audio_prefix + angle_name + '_dataX_dataY.h5'

        with h5py.File(file_name, 'w') as hf:
            print ("Writing data to file...")
            hf.create_dataset('dataX', data=CNN_FC_output)
            hf.create_dataset('dataY', data=final_audio_vector)

print ("--- {EVERYTHING COMPLETE HOMIEEEEEEEEE} ---")


text:
<?php

namespace PUGX\Poser\UI;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Application;

/**
 * Application providing access to just one command.
 *
 * When a console application only consists of one
 * command, having to specify this command's name as first
 * argument is superfluous.
 * This class simplifies creating and using this
 * kind of applications.
 *
 * Usage:
 *
 * $cmd = new SimpleCommand();
 * $app = new SingleCommandApplication($cmd, '1.2');
 * $app->run();
 *
 * @author Stefaan Lippens <soxofaan@gmail.com>
 */
class SingleCommandApplication extends Application
{
    /**
     * Name of the single accessible command of this application
     * @var string
     */
    private $commandName;

    /**
     * Constructor to build a "single command" application, given a command.
     *
     * The application will adopt the same name as the command.
     *
     * @param Command $command The single (accessible) command for this application
     * @param string  $version The version of the application
     */
    public function __construct(Command $command, $version = 'UNKNOWN')
    {
        parent::__construct($command->getName(), $version);

        // Add the given command as single (accessible) command.
        $this->add($command);
        $this->commandName = $command->getName();

        // Override the Application's definition so that it does not
        // require a command name as first argument.
        $this->getDefinition()->setArguments();
    }

    /**
     * {@inheritdoc}
     */
    protected function getCommandName(InputInterface $input)
    {
        return $this->commandName;
    }

    /**
     * Adds a command object.
     *
     * This function overrides (public) Application::add()
     * but should should only be used internally.
     * Will raise \LogicException when called
     * after the single accessible command is set up
     * (from the constructor).
     *
     * @param Command $command A Command object
     *
     * @return Command The registered command
     *
     * @throws \LogicException
     */
    public function add(Command $command)
    {
        // Fail if we already set up the single accessible command.
        if ($this->commandName) {
            throw new \LogicException("You should not add additional commands to a SingleCommandApplication instance.");
        }

        return parent::add($command);
    }
}


text:
description: Learn how to troubleshoot your Docker Universal Control Plane cluster.
keywords: docker, ucp, troubleshoot
title: Troubleshoot your cluster
---

If you detect problems in your UCP cluster, you can start your troubleshooting
session by checking the logs of the
[individual UCP components](../../architecture.md). Only administrator users can
see information about UCP system containers.

## Check the logs from the UI

To see the logs of the UCP system containers, navigate to the **Containers**
page of UCP. By default the UCP system containers are hidden. Click the
**Show all containers** option for the UCP system containers to be listed as
well.

![](../../images/troubleshoot-with-logs-1.png){: .with-border}

You can click on a container to see more details like its configurations and
logs.

## Check the logs from the CLI

You can also check the logs of UCP system containers from the CLI. This is
specially useful if the UCP web application is not working.

1. Get a client certificate bundle.

    When using the Docker CLI client you need to authenticate using client
    certificates.
    [Learn how to use client certificates](../../user/access-ucp/cli-based-access.md).

    If your client certificate bundle is for a non-admin user, you won't have
    permissions to see the UCP system containers.

2.  Check the logs of UCP system containers.

    ```bash
    # By default system containers are not displayed. Use the -a flag to display them
    $ docker ps -a

    CONTAINER ID    IMAGE                             COMMAND                  CREATED         STATUS           PORTS                            NAMES
    922503c2102a    docker/ucp-controller:1.1.0-rc2   "/bin/controller serv"   4 hours ago     Up 30 minutes    192.168.10.100:444->8080/tcp     ucp/ucp-controller
    1b6d429f1bd5    docker/ucp-swarm:1.1.0-rc2        "/swarm join --discov"   4 hours ago     Up 4 hours       2375/tcp                         ucp/ucp-swarm-join

    # See the logs of the ucp/ucp-controller container
    $ docker logs ucp/ucp-controller

    {"level":"info","license_key":"PUagrRqOXhMH02UgxWYiKtg0kErLY8oLZf1GO4Pw8M6B","msg":"/v1.22/containers/ucp/ucp-controller/json","remote_addr":"192.168.10.1:59546","tags":["api","v1.22","get"],"time":"2016-04-25T23:49:27Z","type":"api","username":"dave.lauper"}
    {"level":"info","license_key":"PUagrRqOXhMH02UgxWYiKtg0kErLY8oLZf1GO4Pw8M6B","msg":"/v1.22/containers/ucp/ucp-controller/logs","remote_addr":"192.168.10.1:59546","tags":["api","v1.22","get"],"time":"2016-04-25T23:49:27Z","type":"api","username":"dave.lauper"}
    ```

## Get a support dump

Before making any changes to UCP, download a [support dump](../../get-support.md).
This allows you to troubleshoot problems which were already happening before
changing UCP configurations.

Then you can increase the UCP log level to debug, making it easier to understand
the status of the UCP cluster. Changing the UCP log level restarts all UCP
system components and introduces a small downtime window to UCP. Your
applications won't be affected by this.

To increase the UCP log level, navigate to the **UCP web UI**, go to the
**Admin Settings** tab, and choose **Logs**.

![](../../images/troubleshoot-with-logs-2.png){: .with-border}

Once you change the log level to **Debug** the UCP containers are restarted.
Now that the UCP components are creating more descriptive logs, you can download
again a support dump and use it to troubleshoot the component causing the
problem.

Depending on the problem you are experiencing, it's more likely that you'll
find related messages in the logs of specific components on manager nodes:

* If the problem occurs after a node was added or removed, check the logs
of the `ucp-reconcile` container.
* If the problem occurs in the normal state of the system, check the logs
of the `ucp-controller` container.
* If you are able to visit the UCP web UI but unable to log in, check the
logs of the `ucp-auth-api` and `ucp-auth-store` containers.

It's normal for the `ucp-reconcile` container to be in a stopped state. This
container is only started when the `ucp-agent` detects that a node needs to
transition to a different state, and it is responsible for creating and removing
containers, issuing certificates, and pulling missing images.

## Where to go next

* [Troubleshoot configurations](troubleshoot-configurations.md)


text:
import assert from 'assert'
import path from 'path'
import fs from 'fs'
import Rx from 'rx'
const of = Rx.Observable.of
const never = Rx.Observable.never
import rmdirSync from './utils'

import makeTingoDBDriver from '../src/tingodb-driver'

//some very annoying issues with mocha , see here : https://www.bountysource.com/issues/1401310-mocha-times-out-when-tests-fail-reports-nothing

describe("tingoDB-driver", function() {

  const dbPath = path.join(__dirname, 'dbTest')

  afterEach(()=> {
    //remove test db folder
    rmdirSync(dbPath)
  })

  it('should write input data to db ', (done) => {

    const tingoDBDriver = makeTingoDBDriver( dbPath )

    const data = {
      fieldOne: "some text"
      ,fieldTwo: 27.87
      ,fieldThree: {
        sub:true
      }
    }
    const collectionName = "testCollection"
    const out$ = of({method:'insert', collectionName, data})

    tingoDBDriver(out$)

    assert.strictEqual( true, fs.existsSync(dbPath) )

    done()
  })

  it('enables you to search for data, optionally converting output to array', function( done ){
    this.timeout(6000)
    const tingoDBDriver = makeTingoDBDriver( dbPath )

    const inData = {
      fieldOne: "some text"
      ,fieldTwo: 27.87
      ,fieldThree: {
        sub:true
      }
    }
    const expData = {
      fieldOne: 'some text',
      fieldTwo: 27.87,
      fieldThree: { sub: true },
      _id: {"id": 2} }

    const collectionName = "testCollection"
    const queries$       = new Rx.Subject()
    const db = tingoDBDriver(queries$)

    db
      .filter(res$ => res$.query.method === 'find')
      .mergeAll()
      .filter(data=>data.length>0)
      .map(data=>data[0])
      .forEach(function(obsData){
        try {// FIXME: have to use try catch , very annoying, see link on top
          //console.log("obsData",obsData,"expData",expData)
          assert.deepEqual(obsData,expData)
        } catch(e){ return done(e)}
        done()
      })

    queries$.onNext({method:'insert', collectionName, data:inData, eager:true})
    queries$.onNext({method:'find'  , collectionName, query:{}, options:{toArray:true} })
  })

  it('can update documents', function( done ){
    this.timeout(6000)
    const tingoDBDriver = makeTingoDBDriver( dbPath )

    const collectionName = "testCollection"
    const inData  = [{name:"joe"}]
    const expData = [{name:"malek",age:28, _id: {id:2} }]

    const queries$       = new Rx.Subject()
    const db = tingoDBDriver(queries$)

    db
      .filter(res$ => res$.query.method === 'find')
      .mergeAll()
      .forEach(function(obsData){
        try {// FIXME: have to use try catch , very annoying, see link on top
          //console.log("obsData",obsData,"expData",expData)
          assert.deepEqual(obsData,expData)
        } catch(e){ return done(e)}
        done()
      })

    queries$.onNext({method:'insert', collectionName, data:inData})
    queries$.onNext({method:'update', collectionName, query:{name:"joe"}, update:{name:"malek",age:28} })
    queries$.onNext({method:'find'  , collectionName, query:{}, options:{toArray:true} })

  })

  it('can delete documents', function( done ){
    this.timeout(6000)
    const tingoDBDriver = makeTingoDBDriver( dbPath )

    const collectionName = "testCollection"
    const inData         = [{name:"joe",foo:0},{name:"malek",foo:2}]
    const expData        = [{name:"malek",foo:2,_id:{id:3}}]

    const queries$       = new Rx.Subject()
    const db             = tingoDBDriver(queries$)

    db
      .filter(res$ => res$.query.method === 'find')
      .mergeAll()
      .forEach(function(obsData){
        try {// FIXME: have to use try catch , very annoying, see link on top
          assert.deepEqual(obsData,expData)
        } catch(e){ return done(e)}
        done()
      })

    queries$.onNext({method:'insert', collectionName, data:inData})
    queries$.onNext({method:'delete', collectionName, query:{name:"joe"} })
    queries$.onNext({method:'find'  , collectionName, query:{}, options:{toArray:true} })

  })

})


text:
var TwitterRoute = function(express, twitterClient, config){

  var instance;

  function init() {

    var router = express.Router();

    // Send tweet.
    router.post('/twitter/send', (req, res) => {

      if (req.body == null || req.body.text == null){

        res.send({code:500, message:'Request body cannot be null!'});
        return;
      }

      twitterClient.post('statuses/update', {status: req.body.text}, function(error, tweet, response) {

        if(error) {

          if(error.stack) {

            console.log(error.stack);
            res.send({code:500, message:'FAIL_SYSTEM', data:error.message});
            return;
          }

          res.send({code:500, message:'FAIL_SYSTEM', data:error});
          return;
        }

        res.send({code: 200, message:'SUCCESS'});
        return;

      });

    });

    // Gets profile info. of specified user.
    router.get('/twitter/profile', (req, res) => {

      if(!req.query.id) {

        res.send({code:500, message:'User id must be provided!'});
        return;
      }

      twitterClient.get('users/show', {user_id: req.query.id}, function(error, profile, response) {

        if(error) {

          if(response.body.code == 50) {

            res.send({code:404, message:'USER_NOT_FOUND'});
            return;
          }

          if(error.stack) {

            console.log(error.stack);
            res.send({code:500, message:'FAIL_SYSTEM', data:error.message});
            return;
          }

          res.send({code:500, message:'FAIL_SYSTEM', data:error});
          return;
        }

        res.send({code: 200, message:'SUCCESS', data:profile});
        return;

      });

    });

    // Gets tweets of specified user.
    router.get('/twitter/profile/tweets', (req, res) => {

      if(!req.query.id) {

        res.send({code:500, message:'User id must be provided!'});
        return;
      }

      var query = {
        include_entities: true,
        include_rts: true,
        user_id: req.query.id
      }

      twitterClient.get('statuses/user_timeline', query, function(error, tweets, response) {

        if(error) {

          if(error.stack) {

            console.log(error.stack);
            res.send({code:500, message:'FAIL_SYSTEM', data:error.message});
            return;
          }

          if(response.body.code == 50) {

            res.send({code:404, message:'USER_NOT_FOUND'});
            return;
          }

          res.send({code:500, message:'FAIL_SYSTEM', data:error});
          return;
        }

        // filter tweets including camping keywords
        var retval = [];
        var keywords = ['camp','camping','nature','tent','kamp','kamping','trekking','doğa','çadır'];
        tweets.forEach((item) => {

          keywords.forEach((keyword) =>{

            if(item.text.indexOf(keyword) != -1)
              retval.push(item);
          });
        });

        res.send({code: 200, message:'SUCCESS', data:retval});
        return;

      });

    });

    // Follow user.
    router.post('/twitter/follow', (req, res) => {

      if(!req.body.id) {

        res.send({code:500, message:'User id must be provided!'});
        return;
      }

      twitterClient.post('friendships/create', {user_id: req.body.id}, function(error, profile, response) {

        if(error) {

          if(error.stack) {

            console.log(error.stack);
            res.send({code:500, message:'FAIL_SYSTEM', data:error.message});
            return;
          }

          if(response.body.code == 50) {

            res.send({code:404, message:'USER_NOT_FOUND'});
            return;
          }

          res.send({code:500, message:'FAIL_SYSTEM', data:error});
          return;
        }

        res.send({code: 200, message:'SUCCESS', data:profile});
        return;

      });

    });

    return router;
  }

  return {

    getInstance: function () {

      if ( !instance )
        instance = init();

      return instance;
    }

  };

};

module.exports = exports = TwitterRoute;


text:
Meteor.startup(function () {
  Template.postShare.helpers({
    sourceLink: function(){
      return !!this.url ? this.url : Telescope.utils.getSiteUrl() + "posts/"+this._id;
    },
    viaTwitter: function () {
      return !!Settings.get('twitterAccount') ? 'via='+Settings.get('twitterAccount') : '';
    }
  });

  Template.postShare.events({
    'click .share-link': function(e){
      var $this = $(e.target).parents('.post-share').find('.share-link');
      var $share = $this.parents('.post-share').find('.share-options');
      e.preventDefault();
      $('.share-link').not($this).removeClass("active");
      $(".share-options").not($share).addClass("hidden");
      $this.toggleClass("active");
      $share.toggleClass("hidden");
    }
  });
});