text:
require 'benchmark'
require 'tmpdir'
require File.join(File.dirname(__FILE__), '..', 'lib', 'eq', 'boot', 'all')

EQ.logger.level = Logger::Severity::ERROR

class QueueBackendBenchmark < Struct.new(:executor)
  def run
    Benchmark.bm(50) do |benchmark|
      executor.benchmark = benchmark

      executor.report 'sequel with sqlite3 (in-memory)' do |config|
        config.queue = 'sequel'
      end

      executor.report 'sequel with sqlite3 (file)' do |config|
        config.queue = 'sequel'
        config.sequel = "sqlite://#{Dir.mktmpdir}/benchmark.sqlite3"
      end

      executor.report 'leveldb' do |config|
        config.queue = 'leveldb'
        config.leveldb = Dir.mktmpdir
      end
    end
  end
end


text:
require_relative 'base_service'

class ValidateNewBranchService < BaseService
  def execute(branch_name)
    valid_branch = Gitlab::GitRefValidator.validate(branch_name)

    unless valid_branch
      return error('Branch name is invalid')
    end

    repository = project.repository
    existing_branch = repository.find_branch(branch_name)

    if existing_branch
      return error('Branch already exists')
    end

    success
  rescue GitHooksService::PreReceiveError => ex
    error(ex.message)
  end
end

redpajama_set_name: RedPajamaGithub


text:
//******************************************************************************************************
//  LineView.cs - Gbtc
//
//  Copyright © 2017, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
//  not use this file except in compliance with the License. You may obtain a copy of the License at:
//
//      http://opensource.org/licenses/MIT
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  08/29/2017 - Billy Ernest
//       Generated original version of source code.
//  07/23/2019 - Christoph Lackner
//       Added Relay Alert Threshholds.
//
//******************************************************************************************************

using System.ComponentModel.DataAnnotations;
using GSF.Data.Model;

namespace openXDA.Model
{
    [TableName("LineView")]
    public class LineView
    {
        [PrimaryKey(true)]
        public int ID { get; set; }

        [Required]
        [StringLength(50)]
        [Searchable]
        public string AssetKey { get; set; }

        public float VoltageKV { get; set; }

        public float Length { get; set; }

        public float MaxFaultDistance { get; set; }

        public float MinFaultDistance { get; set; }

        public string Description { get; set; }

        [Searchable]
        public string AssetName { get; set; }
    }
}


text:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Xml.Serialization;

namespace Progressive.PecaStarter5.Models.Configurations
{
    public class Configuration
    {
        public Configuration()
        {
            Port = 7144;
            SelectedYellowPages = "DP";
            YellowPagesList = new List<YellowPages>();
            StreamUrl = "http://localhost:8080";
            NameHistory = new Collection<string>();
            GenreHistory = new Collection<string>();
            DescriptionHistory = new Collection<string>();
            CommentHistory = new Collection<string>();
            PeercastType = PeercastType.Peercast;
        }

        public double Left { get; set; }
        public double Top { get; set; }
        public double Width { get; set; }
        public double Height { get; set; }

        public string SelectedYellowPages { get; set; }
        public List<YellowPages> YellowPagesList { get; set; }
        public string StreamUrl { get; set; }
        public string Type { get; set; }
        public Collection<string> NameHistory { get; set; }
        public Collection<string> GenreHistory { get; set; }
        public Collection<string> DescriptionHistory { get; set; }
        public string ContactUrl { get; set; }
        public Collection<string> CommentHistory { get; set; }

        public bool HasNotifyIcon { get; set; }
        public PeercastType PeercastType { get; set; }
        public bool IsSavePosition { get; set; }
        public bool Logging { get; set; }
        private string m_logPath;
        public string LogPath
        {
            get { return m_logPath; }
            set
            {
                if (!string.IsNullOrWhiteSpace(value))
                    m_logPath = value;
                else
                    m_logPath = DefaultLogPath;
            }
        }
        public int Delay { get; set; }
        public int Port { get; set; }

        private string m_defaultLogPath;
        [XmlIgnore]
        public string DefaultLogPath
        {
            get { return m_defaultLogPath; }
            set
            {
                m_defaultLogPath = value;
                LogPath = LogPath;
            }
        }

        public class YellowPages
        {
            public string Name { get; set; }
            public int? AcceptedHash { get; set; }
            public string Prefix { get; set; }
        }
    }
}


text:
// Copyright 2022 Google LLC
//
// 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 com.google.api.ads.admanager.jaxws.v202208;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Gets a {@link LineItemPage} of {@link LineItem} objects that satisfy the
 *             given {@link Statement#query}. The following fields are supported for
 *             filtering:
 *
 *

 *

 *

 *             PQL property
 *             Entity property
 *

 *

 *
 *             {@code CostType}
 *
 *
 *             {@link LineItem#costType}
 *
 *

 *

 *
 *             {@code CreationDateTime}
 *
 *
 *             {@link LineItem#creationDateTime}
 *
 *

 *

 *
 *             {@code DeliveryRateType}
 *
 *
 *             {@link LineItem#deliveryRateType}
 *
 *

 *

 *
 *             {@code EndDateTime}
 *
 *
 *             {@link LineItem#endDateTime}
 *
 *

 *

 *
 *             {@code ExternalId}
 *
 *
 *             {@link LineItem#externalId}
 *
 *

 *

 *
 *             {@code Id}
 *
 *
 *             {@link LineItem#id}
 *
 *

 *

 *
 *             {@code IsMissingCreatives}
 *
 *
 *             {@link LineItem#isMissingCreatives}
 *
 *

 *

 *
 *             {@code IsSetTopBoxEnabled}
 *
 *
 *             {@link LineItem#isSetTopBoxEnabled}
 *
 *

 *

 *
 *             {@code LastModifiedDateTime}
 *
 *
 *             {@link LineItem#lastModifiedDateTime}
 *
 *

 *

 *
 *             {@code LineItemType}
 *
 *
 *             {@link LineItem#lineItemType}
 *
 *

 *

 *
 *             {@code Name}
 *
 *
 *             {@link LineItem#name}
 *
 *

 *

 *
 *             {@code OrderId}
 *
 *
 *             {@link LineItem#orderId}
 *
 *

 *

 *
 *             {@code StartDateTime}
 *
 *
 *             {@link LineItem#startDateTime}
 *
 *

 *

 *
 *             {@code Status}
 *
 *
 *             {@link LineItem#status}
 *
 *

 *

 *
 *             {@code UnitsBought}
 *
 *
 *             {@link LineItem#unitsBought}
 *
 *

 *

 *

 *
 *
 *
Java class for getLineItemsByStatement element declaration.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <element name="getLineItemsByStatement">
 *   <complexType>
 *     <complexContent>
 *       <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *         <sequence>
 *           <element name="filterStatement" type="{https://www.google.com/apis/ads/publisher/v202208}Statement" minOccurs="0"/>
 *         </sequence>
 *       </restriction>
 *     </complexContent>
 *   </complexType>
 * </element>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "filterStatement"
})
@XmlRootElement(name = "getLineItemsByStatement")
public class LineItemServiceInterfacegetLineItemsByStatement {

    protected Statement filterStatement;

    /**
     * Gets the value of the filterStatement property.
     *
     * @return
     *     possible object is
     *     {@link Statement }
     *
     */
    public Statement getFilterStatement() {
        return filterStatement;
    }

    /**
     * Sets the value of the filterStatement property.
     *
     * @param value
     *     allowed object is
     *     {@link Statement }
     *
     */
    public void setFilterStatement(Statement value) {
        this.filterStatement = value;
    }

}


text:
import json
import requests
import jwt
from jwt import DecodeError
from datetime import datetime, timedelta
from app.models import User
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.generic import View
from django.core import serializers

class social(View):

    def create_token(self, user):
        payload = {
            'sub': user.id,
            'iat': datetime.utcnow(),
            'exp': datetime.utcnow() + timedelta(days=14)
        }
        token = jwt.encode(payload, settings.TOKEN_SECRET)
        return token.decode('unicode_escape')

    def parse_token(self, req):
        token = req.META.get('HTTP_AUTHORIZATION').split()[1]
        return jwt.decode(token, settings.TOKEN_SECRET)

    def me(self, request, *args, **kwargs):
        try:
            payload = self.parse_token(request)
        except DecodeError:
            return HttpResponse(json.dumps({ 'destroy': True }), status=401)
        except Exception:
            return HttpResponse(None, status=401)

        id = payload['sub']
        user = User.objects.filter(id=id).first()
        if not user:
            return HttpResponse(json.dumps({ 'destroy': True }), status=401)

        serialized = serializers.serialize('json', [user])
        data = json.loads(serialized)
        return HttpResponse(json.dumps(data[0]))

    def callback(self, request, *args, **kwargs):

        access_token_url = 'https://graph.facebook.com/v2.3/oauth/access_token'
        graph_api_url = 'https://graph.facebook.com/v2.3/me?fields=name,email,picture'

        params = json.loads(request.body)

        params = {
            'client_id': params['clientId'],
            'redirect_uri': params['redirectUri'],
            'client_secret': settings.FACEBOOK_SECRET,
            'code': params['code'],
        }

        r = requests.post(access_token_url, params)
        access_token = json.loads(r.text)

        # GET => https://graph.facebook.com/v2.3/me
        # to get user profile (email, first_name, last_name, gender, id)
        r = requests.get(graph_api_url, params=access_token)
        profile = json.loads(r.text)

        if request.META.get('HTTP_AUTHORIZATION'):

            user = User.objects.filter(fb_id=profile['id']).first()

            if user:
                token = self.create_token(user)
                return HttpResponse(json.dumps({ 'token': token }))
            else:
                return HttpResponse(json.dumps({ 'destroy': True }), status=401)

            payload = parse_token(request)

            user = User.objects.filter(fb_id=payload['sub']).first()
            if not user:
                return HttpResponseBadRequest()

            user = User(fb_id   = profile['id'],
                        name    = profile['name'],
                        email   = profile['email'],
                        picture = profile['picture']['data']['url'])
            user.save()
            token = self.create_token(user)
            return HttpResponse(json.dumps({ 'token': token }))

        user = User.objects.filter(fb_id=profile['id']).first()

        if user:
            token = self.create_token(user)
            return HttpResponse(json.dumps({ 'token': token }))

        user = User(fb_id = profile['id'],
                    name  = profile['name'],
                    email = profile['email'],
                    picture = profile['picture']['data']['url'])
        user.save()

        token = self.create_token(user)
        return HttpResponse(json.dumps({ 'token': token }))


text:
#include "dlmalloc.h"

// fix undefined reference
size_t dlmalloc_usable_size(const void *mem) {
    return malloc_usable_size(mem);
}

void* dlpvalloc(size_t bytes) {
    return pvalloc(bytes);
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>Bar or Column Chart with Chart.js | Hands-On Data Visualization</title>
  <meta name="description" content="Tell your story and show it with data, using free and easy-to-learn tools on the web. This introductory book teaches you how to design interactive charts and customized maps for your website, beginning with easy drag-and-drop tools, such as Google Sheets, Datawrapper, and Tableau Public. You will also gradually learn how to edit open-source code templates built with Chart.js, Highcharts, and Leaflet on GitHub. Follow along with the step-by-step tutorials, real-world examples, and online resources. This book is ideal for students, non-profit organizations, small business owners, local governments, journalists, academics, or anyone who wants to tell their story and show the data. No coding experience is required." />
  <meta name="generator" content="bookdown 0.27 and GitBook 2.6.7" />

  <meta property="og:title" content="Bar or Column Chart with Chart.js | Hands-On Data Visualization" />
  <meta property="og:type" content="book" />
  <meta property="og:image" content="http://handsondataviz.github.io//images/cover-400wide.jpg" />
  <meta property="og:description" content="Tell your story and show it with data, using free and easy-to-learn tools on the web. This introductory book teaches you how to design interactive charts and customized maps for your website, beginning with easy drag-and-drop tools, such as Google Sheets, Datawrapper, and Tableau Public. You will also gradually learn how to edit open-source code templates built with Chart.js, Highcharts, and Leaflet on GitHub. Follow along with the step-by-step tutorials, real-world examples, and online resources. This book is ideal for students, non-profit organizations, small business owners, local governments, journalists, academics, or anyone who wants to tell their story and show the data. No coding experience is required." />
  <meta name="github-repo" content="handsondataviz/book" />

  <meta name="twitter:card" content="summary" />
  <meta name="twitter:title" content="Bar or Column Chart with Chart.js | Hands-On Data Visualization" />
  <meta name="twitter:site" content="@handsondataviz" />
  <meta name="twitter:description" content="Tell your story and show it with data, using free and easy-to-learn tools on the web. This introductory book teaches you how to design interactive charts and customized maps for your website, beginning with easy drag-and-drop tools, such as Google Sheets, Datawrapper, and Tableau Public. You will also gradually learn how to edit open-source code templates built with Chart.js, Highcharts, and Leaflet on GitHub. Follow along with the step-by-step tutorials, real-world examples, and online resources. This book is ideal for students, non-profit organizations, small business owners, local governments, journalists, academics, or anyone who wants to tell their story and show the data. No coding experience is required." />
  <meta name="twitter:image" content="http://handsondataviz.github.io//images/cover-400wide.jpg" />

<meta name="author" content="Jack Dougherty" />
<meta name="author" content="Ilya Ilyankou" />

<meta name="date" content="2022-07-26" />

  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black" />

  <link rel="shortcut icon" href="images/favicon.png" type="image/x-icon" />
<link rel="prev" href="chartcode.html"/>
<link rel="next" href="chartjs-error-bars.html"/>

<link href="libs/gitbook-2.6.7/css/style.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-table.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-bookdown.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-highlight.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-search.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-fontsettings.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-clipboard.css" rel="stylesheet" />

<link href="libs/anchor-sections-1.1.0/anchor-sections.css" rel="stylesheet" />
<link href="libs/anchor-sections-1.1.0/anchor-sections-hash.css" rel="stylesheet" />

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

Hands-On Data Visualization
by Jack Dougherty & Ilya Ilyankou

Preface

Audience and Overview

Authors & Acknowledgements

Our Open-Access Web Edition: Why and How

Introduction: Why Data Visualization?

What Can You Believe?

Some Pictures Are More Persuasive

Different Shades of the Truth

Organization of the Book

1 Choose Tools to Tell Your Story

Start Sketching Your Data Story

Ten Factors When Considering Tools

Our Recommended Tools

Use a Password Manager

2 Strengthen Your Spreadsheet Skills

Select your Spreadsheet Tools

Download to CSV or ODS Format

Make a Copy of a Google Sheet

Share Your Google Sheets

Upload and Convert to Google Sheets

Geocode Addresses in Google Sheets

Collect Data with Google Forms

Sort and Filter Data

Calculate with Formulas

Summarize Data with Pivot Tables

Match Columns with VLOOKUP

Spreadsheet vs. Relational Database

3 Find and Question Your Data

Guiding Questions for Your Search

Public and Private Data

Mask or Aggregate Sensitive Data

Open Data Repositories

Source Your Data

Recognize Bad Data

Question Your Data

4 Clean Up Messy Data

Smart Cleanup with Google Sheets

Find and Replace with Blank

Transpose Rows and Columns

Split Data into Separate Columns

Combine Data into One Column

Numbers-to-Text and Remove Characters

Extract Tables from PDFs with Tabula

Clean Data with OpenRefine

5 Make Meaningful Comparisons

Precisely Describe Comparisons

Normalize Your Data

Beware of Biased Comparisons

6 Chart Your Data

Chart Design Principles

Google Sheets Charts

- Bar and Column Charts

- Histograms

- Pie, Line, and Area Charts

Datawrapper Charts

- Annotated Charts

- Range Charts

- Scatter and Bubble Charts

Tableau Public Charts

- Scatter Chart

- Filtered Line Chart

7 Map Your Data

Map Design Principles

Design Choropleth Colors & Intervals

Normalize Choropleth Map Data

Point Map with Google My Maps

Locator Map with Datawrapper

Symbol Point Map with Datawrapper

Choropleth Map with Datawrapper

Choropleth Map with Tableau Public

Current Map with Socrata Open Data

8 Table Your Data

Table Design Principles

Datawrapper Table with Sparklines

Other Table-Making Tools

9 Embed On the Web

Static Image vs Interactive iframe

Get the Embed Code or iframe Tag

Paste Code or iframe to Website

10 Edit and Host Code with GitHub

Copy, Edit, and Host a Simple Leaflet Map Template

Convert GitHub Pages Link to iframe

Create a New Repo and Upload Files on GitHub

GitHub Desktop and Atom Editor to Code Efficiently

11 Chart.js and Highcharts Templates

Bar or Column Chart with Chart.js

Error Bars with Chart.js

Line Chart with Chart.js

Annotated Line Chart with Highcharts

Scatter Chart with Chart.js

Bubble Chart with Chart.js

12 Leaflet Map Templates

Leaflet Maps with Google Sheets

Leaflet Storymaps with Google Sheets

Get Your Google Sheets API Key

Leaflet Maps with CSV Data

Leaflet Heatmap Points with CSV Data

Leaflet Searchable Point Map

Leaflet Maps with Open Data APIs

13 Transform Your Map Data

Geospatial Data and GeoJSON

Find GeoJSON Boundary Files

Draw and Edit with GeoJson.io

Edit and Join with Mapshaper

Convert Compressed KMZ to KML

Georeference with Map Warper

Bulk Geocode with US Census

Pivot Points into Polygon Data

14 Detect Lies and Reduce Bias

How to Lie with Charts

How to Lie with Maps

Recognize and Reduce Data Bias

Recognize and Reduce Spatial Bias

15 Tell and Show Your Data Story

Build a Narrative on a Storyboard

Draw Attention to Meaning

Acknowledge Sources & Uncertainty

Decide On Your Data Story Format

Appendix

A Fix Common Problems

A.1 Tool or platform problems

A.2 Try a different browser

A.3 Diagnose with developer tools

A.4 Mac or Chromebook problems

A.5 Watch out for bad data

A.6 Common iframe errors

A.7 Fix your code on GitHub

B Publishing with Bookdown

Install and Set Up Bookdown

File Structure and Headers

Style Guide for Hands-On Data Visualization

Images and R Code-chunk Formatting

Tables in Markdown Format

Zotero and Better BibTeX for Notes and Biblio

Alternative Book Publishing Tools

References

Open-access web edition

Built with Bookdown + RStudio

            Hands-On Data Visualization

    #StandWithUkraine - Stop the Russian invasion

    Join us and donate. All 2022 book royalties will be donated to:
 Save Life in Ukraine and Ukraine Humanitarian Appeal.

Bar or Column Chart with Chart.js

In this section, we will show you how to create bar or column charts using Chart.js. To do so, we will be using a Chart.js code template that pulls data from a CSV file, as shown in Figure 11.1. This column chart shows how many students in five school districts in Connecticut were English-language learners in 2018-2019 academic year.

Figure 11.1: Bar chart with Chart.js: explore the interactive version.

To create your own bar or column chart with CSV data using our Chart.js template:

Go to our GitHub repo that contains the code for the chart in Figure 11.1, log into your GitHub account, and click Use this template to create a copy that you can edit.

Note: If you don't remember how to use GitHub, we recommend you revisit Chapter 10: Edit and Host Code with GitHub.

The repo contains three files that are directly related to the chart:

index.html contains HTML (markdown) and CSS (stylesheets) that tell the browser how to style the document that contains the chart, and what libraries to load,

script.js contains the JavaScript code that reads data from the CSV file and constructs the interactive chart, and

data.csv is the comma-separated file that keeps all the data in the chart, and can be edited in a text editor, or Google Sheets/Excel etc.

The two remaining files are a README.md that describes the contents of the repo, and bar.png that is just an image that you can see in the README. All other GitHub templates in this chapter will be similarly structured.

Prepare your data in CSV format and upload into a data.csv file. Place labels that will appear along the axis in the first column, and each data series in its own column. Your CSV must contain at least two columns (labels and one data series). You can add as many data series columns as you wish.

| district  | nonlearner | learner |
| Hartford  | 15656      | 4111    |
| New Haven | 17730      | 3534    |

In script.js, customize the values of variables. Since you may not be familiar with JavaScript, let's take a look at the code snippet that describes a single variable in the file:

// `false` for vertical column chart, `true` for horizontal bar chart
var HORIZONTAL = false;

The first line starts with // and is a comment to help you understand what the variable in the next line is responsible for. It does not affect the code. As you can see, if the variable HORIZONTAL is set to false, the chart would have vertical bars (also known as columns). If set to true, the chart will contain horizontal bars. The second line contains the variable declaration itself. The equal sign (=) assigns the value that you see on the right (false) to the variable (var) called HORIZONTAL to the left. This line ends with the semicolon (;).

Below are some of the variables available for you to customize in script.js:

var TITLE = 'English Learners by Select School Districts in CT, 2018-19';

// `false` for vertical column chart, `true` for horizontal bar chart
var HORIZONTAL = false;

// `false` for individual bars, `true` for stacked bars
var STACKED = false;

// Which column defines 'bucket' names?
var LABELS = 'district';

// For each column representing a data series, define its name and color
var SERIES = [
  {
    column: 'nonlearner',
    name: 'Non-Learners',
    color: 'grey'
  },
  {
    column: 'learner',
    name: 'Learners',
    color: 'blue'
  }
];

// x-axis label and label in tooltip
var X_AXIS = 'School Districts';

// y-axis label, label in tooltip
var Y_AXIS = 'Number of Enrolled Students';

// `true` to show the grid, `false` to hide
var SHOW_GRID = true;

// `true` to show the legend, `false` to hide
var SHOW_LEGEND = true;

These basic variables should be enough to get you started. It is natural that you will want to move the legend, edit the appearance of the tooltip, or change the colors of the grid lines. We recommend you look at the official Chart.js documentation to get help with that.

      Buy the print book at
      Amazon -
      Barnes & Noble -
      Bookshop -
      Powell's - or your local bookstore.

      Or begin a 30-day free trial to all books and digital content on the O'Reilly online learning platform.

      Share your feedback about the book by tagging @handsondataviz on Twitter or
      contact the authors.

      © 2021 Jack Dougherty & Ilya Ilyankou / Picturedigits Ltd.


text:
namespace IECore
{

/// A RadixSort implementation derived from Pierre Terdiman's OPCODE library, which has as "free for use in any commercial
/// or non-commercial program" licence. The RadixSort class maintains state so that successive calls to it are able to exploit any coherence
/// in the source data. Sorting is done in ascending order.
/// \ingroup mathGroup
class IECORE_API RadixSort
{
	public:

		BOOST_STATIC_ASSERT( sizeof( int ) == 4 );
		BOOST_STATIC_ASSERT( sizeof( unsigned int ) == 4 );
		BOOST_STATIC_ASSERT( sizeof( float ) == 4 );

		RadixSort();
		virtual ~RadixSort();

		/// Sort the given vector of floats, returning a vector of indices representing a mapping from
		/// the given input to the sorted result. For example, the position of input[3] in the sorted result can be
		/// found in indices[3].
		const std::vector<unsigned int> &operator()( const std::vector<float> &input );

		/// Sort the given vector of unsigned ints, returning a vector of indices representing a mapping from
		/// the given input to the sorted result. For example, the position of input[3] in the sorted result can be
		/// found in indices[3].
		const std::vector<unsigned int> &operator()( const std::vector<unsigned int> &input );

		/// Sort the given vector of signed ints, returning a vector of indices representing a mapping from
		/// the given input to the sorted result. For example, the position of input[3] in the sorted result can be
		/// found in indices[3].
		const std::vector<unsigned int> &operator()( const std::vector<int> &input );

	private:

		template<typename T>
		bool createHistograms( const std::vector<T> &input );

		unsigned int m_currentSize;

		unsigned int m_histogram[1024];
		unsigned int *m_link[256];

		UIntVectorDataPtr m_ranks;
		UIntVectorDataPtr m_ranks2;

		template<typename T>
		bool checkPassValidity( const std::vector<T> &input, unsigned int j, unsigned int* &curCount, unsigned char &uniqueVal );

		void resize( unsigned int s );
		void checkResize( unsigned int s );
};

} // namespace IECore

#endif // IE_CORE_RADIXSORT_H


text:
/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright (c) 2012, Intel Corporation.
 */
/*
 * This file is part of Lustre, http://www.lustre.org/
 * Lustre is a trademark of Sun Microsystems, Inc.
 *
 * Author: liang@whamcloud.com
 */

#define DEBUG_SUBSYSTEM S_LNET

#include "../../include/linux/libcfs/libcfs.h"

/** destroy cpu-partition lock, see libcfs_private.h for more detail */
void
cfs_percpt_lock_free(struct cfs_percpt_lock *pcl)
{
	LASSERT(pcl->pcl_locks != NULL);
	LASSERT(!pcl->pcl_locked);

	cfs_percpt_free(pcl->pcl_locks);
	LIBCFS_FREE(pcl, sizeof(*pcl));
}
EXPORT_SYMBOL(cfs_percpt_lock_free);

/**
 * create cpu-partition lock, see libcfs_private.h for more detail.
 *
 * cpu-partition lock is designed for large-scale SMP system, so we need to
 * reduce cacheline conflict as possible as we can, that's the
 * reason we always allocate cacheline-aligned memory block.
 */
struct cfs_percpt_lock *
cfs_percpt_lock_alloc(struct cfs_cpt_table *cptab)
{
	struct cfs_percpt_lock	*pcl;
	spinlock_t		*lock;
	int			i;

	/* NB: cptab can be NULL, pcl will be for HW CPUs on that case */
	LIBCFS_ALLOC(pcl, sizeof(*pcl));
	if (pcl == NULL)
		return NULL;

	pcl->pcl_cptab = cptab;
	pcl->pcl_locks = cfs_percpt_alloc(cptab, sizeof(*lock));
	if (pcl->pcl_locks == NULL) {
		LIBCFS_FREE(pcl, sizeof(*pcl));
		return NULL;
	}

	cfs_percpt_for_each(lock, i, pcl->pcl_locks)
		spin_lock_init(lock);

	return pcl;
}
EXPORT_SYMBOL(cfs_percpt_lock_alloc);

/**
 * lock a CPU partition
 *
 * \a index != CFS_PERCPT_LOCK_EX
 *     hold private lock indexed by \a index
 *
 * \a index == CFS_PERCPT_LOCK_EX
 *     exclusively lock @pcl and nobody can take private lock
 */
void
cfs_percpt_lock(struct cfs_percpt_lock *pcl, int index)
{
	int	ncpt = cfs_cpt_number(pcl->pcl_cptab);
	int	i;

	LASSERT(index >= CFS_PERCPT_LOCK_EX && index < ncpt);

	if (ncpt == 1) {
		index = 0;
	} else { /* serialize with exclusive lock */
		while (pcl->pcl_locked)
			cpu_relax();
	}

	if (likely(index != CFS_PERCPT_LOCK_EX)) {
		spin_lock(pcl->pcl_locks[index]);
		return;
	}

	/* exclusive lock request */
	for (i = 0; i < ncpt; i++) {
		spin_lock(pcl->pcl_locks[i]);
		if (i == 0) {
			LASSERT(!pcl->pcl_locked);
			/* nobody should take private lock after this
			 * so I wouldn't starve for too long time */
			pcl->pcl_locked = 1;
		}
	}
}
EXPORT_SYMBOL(cfs_percpt_lock);

/** unlock a CPU partition */
void
cfs_percpt_unlock(struct cfs_percpt_lock *pcl, int index)
{
	int	ncpt = cfs_cpt_number(pcl->pcl_cptab);
	int	i;

	index = ncpt == 1 ? 0 : index;

	if (likely(index != CFS_PERCPT_LOCK_EX)) {
		spin_unlock(pcl->pcl_locks[index]);
		return;
	}

	for (i = ncpt - 1; i >= 0; i--) {
		if (i == 0) {
			LASSERT(pcl->pcl_locked);
			pcl->pcl_locked = 0;
		}
		spin_unlock(pcl->pcl_locks[i]);
	}
}
EXPORT_SYMBOL(cfs_percpt_unlock);

/** free cpu-partition refcount */
void
cfs_percpt_atomic_free(atomic_t **refs)
{
	cfs_percpt_free(refs);
}
EXPORT_SYMBOL(cfs_percpt_atomic_free);

/** allocate cpu-partition refcount with initial value @init_val */
atomic_t **
cfs_percpt_atomic_alloc(struct cfs_cpt_table *cptab, int init_val)
{
	atomic_t	**refs;
	atomic_t	*ref;
	int		i;

	refs = cfs_percpt_alloc(cptab, sizeof(*ref));
	if (refs == NULL)
		return NULL;

	cfs_percpt_for_each(ref, i, refs)
		atomic_set(ref, init_val);
	return refs;
}
EXPORT_SYMBOL(cfs_percpt_atomic_alloc);

/** return sum of cpu-partition refs */
int
cfs_percpt_atomic_summary(atomic_t **refs)
{
	atomic_t	*ref;
	int		i;
	int		val = 0;

	cfs_percpt_for_each(ref, i, refs)
		val += atomic_read(ref);

	return val;
}
EXPORT_SYMBOL(cfs_percpt_atomic_summary);


text:
package ai.subut.kurjun.repo;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.transport.http.HTTPConduit;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;

import ai.subut.kurjun.common.service.KurjunConstants;
import ai.subut.kurjun.common.service.KurjunContext;
import ai.subut.kurjun.common.utils.InetUtils;
import ai.subut.kurjun.metadata.common.DefaultMetadata;
import ai.subut.kurjun.metadata.common.subutai.DefaultTemplate;
import ai.subut.kurjun.metadata.common.utils.MetadataUtils;
import ai.subut.kurjun.model.annotation.Nullable;
import ai.subut.kurjun.model.identity.User;
import ai.subut.kurjun.model.index.ReleaseFile;
import ai.subut.kurjun.model.metadata.Metadata;
import ai.subut.kurjun.model.metadata.SerializableMetadata;
import ai.subut.kurjun.repo.cache.PackageCache;
import ai.subut.kurjun.repo.util.http.WebClientFactory;

/**
 * Non-local templates repository implementation. <p> TODO: Refactor common methods of all non local repos into base
 * one.
 */
class RemoteTemplateRepository extends RemoteRepositoryBase
{

    private static final Logger LOGGER = LoggerFactory.getLogger( RemoteTemplateRepository.class );

    static final String TEMPLATE_PATH = "template";
    static final String INFO_PATH = "info";
    static final String LIST_PATH = "list";
    static final String GET_PATH = "get";
    static final String MD5_PATH = "md5";

    private WebClientFactory webClientFactory;
    private Gson gson;

    private PackageCache cache;

    private final URL url;
    private final User identity;

    private String token = null;

    private String md5Sum = "";
    private List<SerializableMetadata> remoteIndexChache = new LinkedList<>();

    private static final int CONN_TIMEOUT = 10000;
    private static final int READ_TIMEOUT = 1200000;
    private static final int CONN_TIMEOUT_FOR_URL_CHECK = 10000;

    private String context;
    private String search = "all";

    @Inject
    public RemoteTemplateRepository( PackageCache cache, WebClientFactory webClientFactory, Gson gson,
                                     @Assisted( "url" ) String url, @Assisted @Nullable User identity,
                                     @Assisted( "context" ) String kurjunContext,
                                     @Assisted( "token" ) @Nullable String token, @Assisted( "search" ) String search )
    {
        this.search = search;
        this.gson = gson;
        this.webClientFactory = webClientFactory;
        this.cache = cache;
        this.identity = identity;
        this.context = kurjunContext;
        this.token = token;

        try
        {
            this.url = new URL( url );
        }
        catch ( MalformedURLException ex )
        {
            throw new IllegalArgumentException( "Invalid url", ex );
        }
        _initCache();
    }

    private void _initCache()
    {
        this.remoteIndexChache = listPackages();
        this.md5Sum = getMd5();
    }

    @Override
    public User getIdentity()
    {
        return identity;
    }

    @Override
    public URL getUrl()
    {
        return url;
    }

    @Override
    public boolean isKurjun()
    {
        return true;
    }

    @Override
    public Set<ReleaseFile> getDistributions()
    {
        throw new UnsupportedOperationException( "Not supported in template repositories." );
    }

    @Override
    public SerializableMetadata getPackageInfo( Metadata metadata )
    {
        WebClient webClient =
                webClientFactory.makeSecure( this, TEMPLATE_PATH + "/" + INFO_PATH, makeParamsMap( metadata ) );

        LOGGER.debug( "Trying to get package info from remote Kurjun: {} with Id: {}", url, metadata.getId() );

        if ( identity != null )
        {
            webClient.header( KurjunConstants.HTTP_HEADER_FINGERPRINT, identity.getKeyFingerprint() );
        }

        Response resp = doGet( webClient );

        if ( resp != null && resp.getStatus() == Response.Status.OK.getStatusCode() )
        {
            LOGGER.debug( "Reading remote template info" );

            if ( resp.getEntity() instanceof InputStream )
            {
                try
                {
                    String json = IOUtils.toString( ( InputStream ) resp.getEntity() );

                    return toObject( json );
                }
                catch ( IOException ex )
                {
                    LOGGER.error( "Failed to read response data", ex );
                }
            }
        }

        assert resp != null;

        LOGGER.error( "Did not receive metadata info from remote Kurjun for request: {}, response code: {}",
                metadata.getId(), resp.getStatus() );

        return null;
    }

    @Override
    public InputStream getPackageStream( Metadata metadata, PackageProgressListener progressListener )
    {
        try
        {
            LOGGER.debug( "Trying to get stream from remote Kurjun: {} with Id: {}", url, metadata.getId() );

            InputStream cachedStream = checkCache( metadata );
            if ( cachedStream != null )
            {
                //                BufferedInputStream is = new BufferedInputStream( cachedStream );
                getPackageStream( cachedStream, progressListener );
                return cachedStream;
            }

            URLConnection conn = webClientFactory.openSecureConnection( this, TEMPLATE_PATH + "/" + GET_PATH, makeParamsMap( metadata ) );
            LOGGER.info( "Downloading template file {}", conn.getURL() );
            if ( identity != null )
            {
                conn.setRequestProperty( KurjunConstants.HTTP_HEADER_FINGERPRINT, identity.getKeyFingerprint() );
            }

            ByteArrayOutputStream barrout = getPackageStream( conn, progressListener );
            InputStream inputStream = new ByteArrayInputStream( barrout.toByteArray() );

            String md5Calculated = cacheStream( inputStream );

            // compare the requested and received md5 checksums
            if ( md5Calculated.equals( metadata.getMd5Sum() ) )
            {
                return cache.get( md5Calculated );
            }
            else
            {
                deleteCache( md5Calculated );

                LOGGER.error( "Md5 checksum mismatch after getting the package from remote host. "
                                + "Requested with md5={}, name={}, version={}", metadata.getMd5Sum(), metadata
                                .getName(),
                        metadata.getVersion() );
            }
        }
        catch(IOException e)
        {
            LOGGER.error( "Did not receive metadata info from remote Kurjun for request: " + metadata.getId(), e);
        }
        return null;
    }

    @Override
    public List<SerializableMetadata> listPackages()
    {

        String md5 = getMd5();

        LOGGER.debug( "Trying to get latest md5 sum of remote index. Current md5:{},remote md5:{}", this.md5Sum, md5 );

        if ( this.md5Sum.equalsIgnoreCase( md5 ) )
        {
            LOGGER.debug( "Remote index did not change, returning local index cache" );
            return this.remoteIndexChache;
        }
        Map<String, String> params = makeParamsMap( new DefaultMetadata() );

        //get only public Kurjun local packages
        WebClient webClient = webClientFactory.makeSecure( this, TEMPLATE_PATH + "/" + LIST_PATH, params );
        if ( identity != null )
        {
            webClient.header( KurjunConstants.HTTP_HEADER_FINGERPRINT, identity.getKeyFingerprint() );
        }

        Response resp = doGet( webClient );
        if ( resp != null && resp.getStatus() == Response.Status.OK.getStatusCode() )
        {
            LOGGER.debug( "Reading remote index cache" );
            if ( resp.getEntity() instanceof InputStream )
            {
                try
                {
                    List<String> items = IOUtils.readLines( ( InputStream ) resp.getEntity() );

                    this.remoteIndexChache = toObjectList( items.get( 0 ) );
                    LOGGER.debug( "Remote index contains: {} templates", remoteIndexChache.size() );

                    this.md5Sum = md5;
                    LOGGER.debug( "Updating remote md5 sum to :{}", this.md5Sum );

                    return this.remoteIndexChache;
                }
                catch ( IOException ex )
                {
                    LOGGER.error( "Failed to read packages list", ex );
                }
            }
        }
        assert resp != null;

        LOGGER.error( "Could not obtain remote index, returning empty list for remote Kurjun : {} ", url );

        return Collections.emptyList();
    }

    @Override
    protected Logger getLogger()
    {
        return LOGGER;
    }

    @Override
    public String getMd5()
    {
        WebClient webClient = webClientFactory.makeSecure( this, TEMPLATE_PATH + "/" + MD5_PATH, null );
        LOGGER.debug( "Getting remote index md5 checksum" );
        Response resp = doGet( webClient );
        if ( resp != null && resp.getStatus() == Response.Status.OK.getStatusCode() )
        {
            LOGGER.debug( "Reading remote index md5 checksum" );
            if ( resp.getEntity() instanceof InputStream )
            {
                try
                {
                    List<String> items = IOUtils.readLines( ( InputStream ) resp.getEntity() );
                    if ( items.size() > 0 )
                    {
                        return items.get( 0 );
                    }
                }
                catch ( IOException ex )
                {
                    LOGGER.error( "Failed to read packages list", ex );
                }
            }
        }
        LOGGER.error( "Failed to fetch remote index md5 checksum" );
        return "";
    }

    @Override
    public List<SerializableMetadata> getCachedData()
    {
        return this.remoteIndexChache;
    }

    private Response doGet( WebClient webClient )
    {
        try
        {
            URI remote = webClient.getCurrentURI();

            if ( InetUtils.isHostReachable( remote.getHost(), remote.getPort(), CONN_TIMEOUT_FOR_URL_CHECK ) )
            {
                HTTPConduit httpConduit = ( HTTPConduit ) WebClient.getConfig( webClient ).getConduit();
                httpConduit.getClient().setConnectionTimeout( CONN_TIMEOUT );
                httpConduit.getClient().setReceiveTimeout( READ_TIMEOUT );
                return webClient.get();
            }
            else
            {
                LOGGER.warn( "Remote host is not reachable {}:{}", remote.getHost(), remote.getPort() );
            }
        }
        catch ( Exception e )
        {
            LOGGER.error( "Failed to do GET.", e );
        }
        return null;
    }

    private Map<String, String> makeParamsMap( Metadata metadata )
    {
        Map<String, String> params = MetadataUtils.makeParamsMap( metadata );
        params.put( "repository", search );
        if ( token != null )
        {
            params.put( "sptoken", token );
        }

        // Set parameter kc=kurjun_client to indicate this request is going from Kurjun
        params.put( "kc", Boolean.TRUE.toString() );

        return params;
    }

    private List<SerializableMetadata> parseItems( String items )
    {
        Type collectionType = new TypeToken<LinkedList<DefaultTemplate>>()
        {
        }.getType();
        return gson.fromJson( items, collectionType );
    }

    private List<SerializableMetadata> toObjectList( String items )
    {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
        try
        {
            return objectMapper.readValue( items, new TypeReference<List<DefaultTemplate>>()
            {
            } );
        }
        catch ( IOException e )
        {
            LOGGER.error( " ***** Failed to convert object", e );
        }
        return null;
    }

    private SerializableMetadata toObject( String items )
    {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
        try
        {
            return objectMapper.readValue( items, DefaultTemplate.class );
        }
        catch ( IOException e )
        {
            LOGGER.error( " ***** Failed to convert object", e );
        }
        return null;
    }

    @Override
    public KurjunContext getContext()
    {
        return null;
    }
}


text:
#ifndef INCLUDE_H_PKCS11
#define INCLUDE_H_PKCS11

#include <vector>

#include "template.h"
#include "mech.h"
#include "strings.h"

using namespace v8;
using namespace node;

struct KEY_PAIR {
	CK_OBJECT_HANDLE privateKey;
	CK_OBJECT_HANDLE publicKey;
};

class PKCS11 {
public:
	void Load(Scoped<string> path);

	// PKCS11
	void C_Initialize();
	void C_Finalize();
	Scoped<CK_INFO> C_GetInfo();
	vector<CK_SLOT_ID> C_GetSlotList(CK_BBOOL tokenPresent);
	Scoped<CK_SLOT_INFO> C_GetSlotInfo(CK_SLOT_ID slotId);
	Scoped<CK_TOKEN_INFO> C_GetTokenInfo(CK_SLOT_ID slotID);
	vector<CK_MECHANISM_TYPE> C_GetMechanismList(CK_SLOT_ID slotID);
	Scoped<CK_MECHANISM_INFO> C_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type);
	Scoped<string> C_InitToken(CK_SLOT_ID slotID, Scoped<string> pin, Scoped<string> label);
	void C_InitPIN(CK_SESSION_HANDLE session, Scoped<string> pin);
	void C_SetPIN(CK_SESSION_HANDLE session, Scoped<string> oldPin, Scoped<string> newPin);
	CK_SESSION_HANDLE C_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags);
	void C_CloseSession(CK_SESSION_HANDLE session);
	void C_CloseAllSessions(CK_SLOT_ID slotID);
	Scoped<CK_SESSION_INFO> C_GetSessionInfo(CK_SESSION_HANDLE session);
	// C_GetOperationState);
	// C_SetOperationState);
	void C_Login(CK_SESSION_HANDLE session, CK_USER_TYPE userType, Scoped<string> pin);
	void C_Logout(CK_SESSION_HANDLE session);
	//
	///* Object management */
	CK_OBJECT_HANDLE C_CreateObject(CK_SESSION_HANDLE session, Scoped<Attributes> tmpl);
	CK_OBJECT_HANDLE C_CopyObject(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE object, Scoped<Attributes> tmpl);
	void C_DestroyObject(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE object);
	CK_ULONG C_GetObjectSize(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE object);
	void C_FindObjectsInit(CK_SESSION_HANDLE session, Scoped<Attributes> attrs);
	void C_FindObjectsInit(CK_SESSION_HANDLE session);
	CK_OBJECT_HANDLE C_FindObjects(CK_SESSION_HANDLE session);
	void C_FindObjectsFinal(CK_SESSION_HANDLE session);
	Scoped<Attributes> C_GetAttributeValue(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE object, Scoped<Attributes> tmpl);
	void C_SetAttributeValue(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE object, Scoped<Attributes> tmpl);

	///* Encryption and decryption */
	void C_EncryptInit(CK_SESSION_HANDLE hSession, Scoped<Mechanism> mech, CK_SESSION_HANDLE hObject);
	Scoped<string> C_Encrypt(CK_SESSION_HANDLE hSession, Scoped<string> msg, Scoped<string> encMsg);
	Scoped<string> C_EncryptUpdate(CK_SESSION_HANDLE hSession, Scoped<string> part, Scoped<string> encPart);
	Scoped<string> C_EncryptFinal(CK_SESSION_HANDLE hSession, Scoped<string> encPart);
	void C_DecryptInit(CK_SESSION_HANDLE hSession, Scoped<Mechanism> mech, CK_SESSION_HANDLE hObject);
	Scoped<string> C_Decrypt(CK_SESSION_HANDLE hSession, Scoped<string> encMsg, Scoped<string> msg);
	Scoped<string> C_DecryptUpdate(CK_SESSION_HANDLE hSession, Scoped<string> encPart, Scoped<string> decPart);
	Scoped<string> C_DecryptFinal(CK_SESSION_HANDLE hSession, Scoped<string> decPart);

	///* Message digesting */
	void C_DigestInit(CK_SESSION_HANDLE hSession, Scoped<Mechanism> mech);
	Scoped<string> C_Digest(CK_SESSION_HANDLE hSession, Scoped<string> msg, Scoped<string> output);
	void C_DigestUpdate(CK_SESSION_HANDLE hSession, Scoped<string> part);
	Scoped<string> C_DigestFinal(CK_SESSION_HANDLE hSession, Scoped<string> output);
	void C_DigestKey(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject);

	///* Signing and MACing */
	void C_SignInit(CK_SESSION_HANDLE hSession, Scoped<Mechanism> mech, CK_OBJECT_HANDLE hKey);
	Scoped<string> C_Sign(CK_SESSION_HANDLE hSession, Scoped<string> msg, Scoped<string> output);
	void C_SignUpdate(CK_SESSION_HANDLE hSession, Scoped<string> part);
	Scoped<string> C_SignFinal(CK_SESSION_HANDLE hSession, Scoped<string> output);
	void C_SignRecoverInit(CK_SESSION_HANDLE hSession, Scoped<Mechanism> mech, CK_OBJECT_HANDLE hKey);
	Scoped<string> C_SignRecover(CK_SESSION_HANDLE hSession, Scoped<string>data, Scoped<string> signature);

	///* Verifying signatures and MACs */
	void C_VerifyInit(CK_SESSION_HANDLE hSession, Scoped<Mechanism> mech, CK_OBJECT_HANDLE hKey);
	void C_Verify(CK_SESSION_HANDLE hSession, Scoped<string> msg, Scoped<string> signature);
	void C_VerifyUpdate(CK_SESSION_HANDLE hSession, Scoped<string> part);
	void C_VerifyFinal(CK_SESSION_HANDLE hSession, Scoped<string> signature);
	void C_VerifyRecoverInit(CK_SESSION_HANDLE hSession, Scoped<Mechanism> mech, CK_OBJECT_HANDLE hObject);
	Scoped<string> C_VerifyRecover(CK_SESSION_HANDLE hSession, Scoped<string> signature, Scoped<string> data);

	///* Key management */
	CK_OBJECT_HANDLE C_GenerateKey(CK_SESSION_HANDLE hSession, Scoped<Mechanism> mech, Scoped<Attributes> tmpl);
	Scoped<KEY_PAIR> C_GenerateKeyPair(CK_SESSION_HANDLE hSession, Scoped<Mechanism> mech, Scoped<Attributes> publicKeyTemplate, Scoped<Attributes> privateKeyTemplate);
	Scoped<string> C_WrapKey(
		CK_SESSION_HANDLE hSession,
		Scoped<Mechanism> mech,
		CK_OBJECT_HANDLE hWrappingKey,
		CK_OBJECT_HANDLE hKey,
		Scoped<string> wrappedKey
	);
	CK_OBJECT_HANDLE C_UnwrapKey(
		CK_SESSION_HANDLE hSession,
		Scoped<Mechanism> mech,
		CK_OBJECT_HANDLE hUnwrappingKey,
		Scoped<string> wrappedKey,
		Scoped<Attributes> tmpl
	);
	CK_OBJECT_HANDLE C_DeriveKey(
		CK_SESSION_HANDLE hSession,
		Scoped<Mechanism> mech,
		CK_OBJECT_HANDLE hBaseKey,
		Scoped<Attributes> tmpl
	);

	///* Random number generation */
	void C_SeedRandom(CK_SESSION_HANDLE hSession, char *data, size_t dataLen);
	void C_GenerateRandom(CK_SESSION_HANDLE hSession, char *data, size_t dataLen);

protected:

	void* dlHandle;
	CK_FUNCTION_LIST_PTR functionList;
};

#endif // INCLUDE_H_PKCS11


text:
using System.Net;

// ReSharper disable CheckNamespace
namespace SharpRemote
// ReSharper restore CheckNamespace
{
	/// <summary>
	/// </summary>
	public interface ISocketServer
		: IRemotingServer
	{
		/// <summary>
		///     The endpoint this socket is bound to.
		/// </summary>
		new IPEndPoint LocalEndPoint { get; }

		#region Bind

		/// <summary>
		///     Binds this socket to the given endpoint.
		/// </summary>
		/// <param name="ep"></param>
		void Bind(IPEndPoint ep);

		/// <summary>
		///     Binds this socket to the given address.
		/// </summary>
		/// <param name="localAddress"></param>
		void Bind(IPAddress localAddress);

		#endregion
	}
}


text:
import React from 'react';
import PropTypes from 'prop-types';

const Title = ({ title, titleText }) => {
  const isStringTitle = typeof title === 'string';

  return (
    <h3
      className="slds-tile__title slds-truncate"
      title={isStringTitle ? title : titleText}
    >
      {title}
    </h3>
  );
};

Title.propTypes = {
  title: PropTypes.node.isRequired,
  titleText: PropTypes.string.isRequired,
};

export default Title;


text:
#include "tensorflow/compiler/xla/service/cpu/disassembler.h"

#include <stdint.h>
#include <algorithm>
// IWYU pragma: no_include <system_error>
#include <type_traits>
#include <vector>

#include "absl/strings/str_format.h"
#include "llvm/MC/MCInst.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/raw_ostream.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"

namespace xla {
namespace cpu {

Disassembler::Disassembler(const llvm::TargetMachine& target_machine)
    : subtarget_info_(*target_machine.getMCSubtargetInfo()) {
  objfile_info_.reset(new llvm::MCObjectFileInfo());
  mc_context_.reset(new llvm::MCContext(target_machine.getMCAsmInfo(),
                                        target_machine.getMCRegisterInfo(),
                                        objfile_info_.get()));
  disassembler_.reset(target_machine.getTarget().createMCDisassembler(
      subtarget_info_, *mc_context_));
  inst_printer_.reset(target_machine.getTarget().createMCInstPrinter(
      target_machine.getTargetTriple(),
      /*SyntaxVariant=*/1,  // Use Intel syntax.
      *target_machine.getMCAsmInfo(), *target_machine.getMCInstrInfo(),
      *target_machine.getMCRegisterInfo()));
  inst_analysis_.reset(target_machine.getTarget().createMCInstrAnalysis(
      target_machine.getMCInstrInfo()));
}

// This code is based on llvm-objdump in llvm/tools.
StatusOr<DisassemblerResult> Disassembler::DisassembleObjectFile(
    const llvm::object::ObjectFile& object_file) const {
  if (disassembler_ == nullptr) {
    return NotFound("could not find a disassembler for this platform");
  }

  std::string buffer_string;
  llvm::raw_string_ostream ostream(buffer_string);
  uint64_t code_size_bytes = 0;

  // Iterate through sections. Disassemble symbols of the text section(s).
  for (auto& section : object_file.sections()) {
    if (!section.isText()) {
      continue;
    }

    // Gather symbols from the section.
    std::vector<llvm::object::SymbolRef> symbols;
    for (auto& symbol : object_file.symbols()) {
      if (section.containsSymbol(symbol)) {
        symbols.push_back(symbol);
      }
    }

    // Sort the symbols in increasing address order.
    absl::c_sort(symbols, [](const llvm::object::SymbolRef& a,
                             const llvm::object::SymbolRef& b) {
      // getAddress returns a Expected object. Assert there is no error
      // before extracting the address.
      llvm::Expected<uint64_t> a_address_or_error = a.getAddress();
      CHECK(a_address_or_error);
      llvm::Expected<uint64_t> b_address_or_error = b.getAddress();
      CHECK(b_address_or_error);
      return a_address_or_error.get() < b_address_or_error.get();
    });

    // Construct ArrayRef pointing to section contents.
    llvm::StringRef section_content_string;
    if (section.getContents(section_content_string)) {
      continue;
    }
    llvm::ArrayRef<uint8_t> section_content_bytes(
        reinterpret_cast<const uint8*>(section_content_string.data()),
        section_content_string.size());

    // Use int types from LLVM (eg, uint64_t) for values passed to and returned
    // from the LLVM API. These values map to different types in LLVM and
    // XLA (unsigned long vs unsigned long long).
    uint64_t section_address = section.getAddress();
    uint64_t section_size = section.getSize();

    // Iterate through symbols in increasing address order and disassemble each
    // one.
    for (int i = 0; i < symbols.size(); ++i) {
      auto symbol = symbols[i];
      llvm::Expected<uint64_t> address = symbol.getAddress();
      CHECK(address);
      uint64_t start_index = address.get() - section_address;

      // End of symbol is either the end of the section or the start of the next
      // symbol.
      uint64_t end_index;
      if (i < symbols.size() - 1) {
        llvm::Expected<uint64_t> next_address = symbols[i + 1].getAddress();
        CHECK(next_address);
        end_index = std::min(section_size, next_address.get());
      } else {
        end_index = section_size;
      }

      // Skip zero-length symbols.
      if (start_index == end_index) {
        continue;
      }

      llvm::Expected<llvm::StringRef> name_or_error = symbol.getName();
      TF_RET_CHECK(name_or_error);
      ostream << name_or_error.get().str() << ":\n";

      // Update the code size statistic.
      code_size_bytes += end_index - start_index;

      // Disassemble symbol instruction-by-instruction.
      uint64_t index = start_index;
      while (index < end_index) {
        llvm::MCInst instruction;
        uint64_t size;
        llvm::MCDisassembler::DecodeStatus decode_status =
            disassembler_->getInstruction(instruction, size,
                                          section_content_bytes.slice(index),
                                          /*Address=*/section_address + index,
                                          /*VStream=*/llvm::nulls(),
                                          /*CStream=*/llvm::nulls());
        // If we fail to disassemble, then we must skip past this address.
        if (size == 0) {
          size = 1;
        }

        ostream << absl::StrFormat("0x%08lx", index) << " ";

        if (decode_status == llvm::MCDisassembler::Success) {
          // For branches, try to determine the actual address and emit it as an
          // annotation.
          string annotation;
          if (inst_analysis_ &&
              (inst_analysis_->isUnconditionalBranch(instruction) ||
               inst_analysis_->isConditionalBranch(instruction))) {
            uint64_t target;
            if (inst_analysis_->evaluateBranch(
                    instruction, section_address + index, size, target)) {
              annotation = absl::StrFormat("[0x%08lx]", target);
            }
          }
          inst_printer_->printInst(&instruction, ostream, annotation.c_str(),
                                   subtarget_info_);
        } else {
          ostream << " <unknown>";
        }

        ostream << "\n";
        index += size;
      }
    }
  }

  ostream.flush();
  return DisassemblerResult{
      string(buffer_string.data(), buffer_string.length()), code_size_bytes};
}

}  // namespace cpu
}  // namespace xla


text:
require 'xcskarel'

describe XCSKarel do
  describe XCSKarel::Control do
    describe "blah" do
      it "is happy" do
        expect("a").to eq("a")
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one or more
  ~ contributor license agreements.  See the NOTICE file distributed with
  ~ this work for additional information regarding copyright ownership.
  ~ The ASF licenses this file to You under the Apache License, Version 2.0
  ~ (the "License"); you may not use this file except in compliance with
  ~ the License.  You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~  Unless required by applicable law or agreed to in writing, software
  ~  distributed under the License is distributed on an "AS IS" BASIS,
  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~  See the License for the specific language governing permissions and
  ~  limitations under the License.
  ~
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>eagle-topology-check</artifactId>
        <groupId>org.apache.eagle</groupId>
        <version>0.5.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>eagle-topology-app</artifactId>
    <name>Eagle::App::TopologyCheck::AppProvider</name>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.apache.eagle</groupId>
            <artifactId>eagle-app-base</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.eagle</groupId>
            <artifactId>eagle-topology-entity</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.eagle</groupId>
            <artifactId>eagle-app-utils</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>${powermock.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito</artifactId>
            <version>${powermock.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <descriptor>src/assembly/eagle-topology-check-assembly.xml</descriptor>
                    <finalName>eagle-topology-check-${project.version}</finalName>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <tarLongFileMode>posix</tarLongFileMode>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
package bits.glui;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import bits.draw3d.DrawEnv;
import bits.glui.event.*;
import bits.math3d.Vec4;

/**
 * @author decamp
 */
public class GButton extends GLabel {

    private final Action mAction;
    private String mActionCommand = null;

    private boolean mMouseOver = false;
    private boolean mDepressed = false;

    private ActionListener mCaster = null;
    private ButtonPalette mPalette;

    public GButton( String text ) {
        super( text );
        mAction = null;
        init();
    }

    public GButton( Action action ) {
        super( "" );
        if( action != null ) {
            Object n = action.getValue( Action.NAME );
            if( n != null ) {
                text( n.toString() );
            }
            action.addPropertyChangeListener( new ChangeListenerImpl() );
            addActionListener( action );
            mAction = action;
        } else {
            mAction = null;
        }
        init();
    }

    private void init() {
        horizontalAlignment( 0.0f, 0.1f );
        setSize( 50, 25 );
        setButtonPalette( ButtonPalette.DEFAULT );
        addMouseListener( new MouseListenerImpl() );
    }

    public Action getAction() {
        return mAction;
    }

    public ButtonPalette getButtonPalette() {
        return mPalette;
    }

    public void setButtonPalette( ButtonPalette bp ) {
        mPalette = bp;
        setFont( bp.mFont );
        setForeground( bp.mForeground );
        setBackground( bp.mBackground );
    }

    public void addActionListener( ActionListener al ) {
        mCaster = GluiMulticaster.add( mCaster, al );
    }

    public void removeActionListener( ActionListener al ) {
        mCaster = GluiMulticaster.remove( mCaster, al );
    }

    public String getActionCommand() {
        return mActionCommand;
    }

    public void setActionCommand( String actionCommand ) {
        mActionCommand = actionCommand;
    }

    @Override
    public void paintComponent( DrawEnv d ) {
        Vec4 foreground;
        Vec4 background;
        int offX = 0;
        int offY = 0;

        if( !isEnabled() || mAction != null && !mAction.isEnabled() ) {
            foreground = mPalette.mDisabledForeground;
            background = mPalette.mDisabledBackground;
        } else if( isDepressed() ) {
            foreground = mPalette.mPressedForeground;
            background = mPalette.mPressedBackground;
            offX = 1;
            offY = -1;
        } else if( isMouseOver() ) {
            foreground = mPalette.mRolloverForeground;
            background = mPalette.mRolloverBackground;
        } else {
            foreground = mWorkFore;
            background = mWorkBack;
            getForeground( foreground );
            getBackground( background );
        }

        paintLabel( d, background, foreground, offX, offY );
    }

    public boolean isMouseOver() {
        return mMouseOver;
    }

    public boolean isDepressed() {
        return mDepressed;
    }

    protected void fireClickAction() {
        String cmd = mActionCommand;
        if( cmd == null ) {
            cmd = text();
            if( cmd == null ) {
                cmd = "";
            }
        }
        fireAction( cmd );
    }

    protected void fireAction( String actionCommand ) {
        ActionListener caster = mCaster;
        if( caster == null ) {
            return;
        }
        caster.actionPerformed( new ActionEvent( this, ActionEvent.ACTION_PERFORMED, actionCommand ) );
    }

    private final class ChangeListenerImpl implements PropertyChangeListener {
        public void propertyChange( PropertyChangeEvent e ) {
            if( e.getPropertyName() == Action.NAME ) {
                text( e.getNewValue().toString() );
            }
        }
    }

    private final class MouseListenerImpl implements GMouseListener {

        private boolean mArmed    = false;

        public void mouseClicked( GMouseEvent e ) {}

        public void mousePressed( GMouseEvent e ) {
            if( e.getButton() != GMouseEvent.BUTTON1 ) {
                return;
            }
            if( isEnabled() ) {
                mDepressed = true;
                mArmed   = mMouseOver;
                repaint();
            }
        }

        public void mouseReleased( GMouseEvent e ) {
            if( e.getButton() != GMouseEvent.BUTTON1 ) {
                return;
            }
            mDepressed = false;
            if( mArmed ) {
                mArmed = false;
                fireClickAction();
            }

            repaint();
        }

        public void mouseEntered( GMouseEvent e ) {
            mMouseOver = true;
            repaint();
        }

        public void mouseExited( GMouseEvent e ) {
            mMouseOver = false;
            mArmed = false;
            repaint();
        }

    }

}


text:
namespace si = SageInterface;

namespace kff {
namespace translator {

static void AnalyzeGridAccess(SgFunctionDeclaration *decl,
                              TranslationContext &tx,
                              const set<SgInitializedName*> &gvs,
                              GridSet &grid_set,
                              SgInitializedNamePtrSet &grid_var_set) {
  SgTypePtrList relevantTypes;
  BOOST_FOREACH(SgInitializedName *gv, gvs) {
    relevantTypes.push_back(gv->get_type());
    LOG_DEBUG() << "Relevant type: " << gv->get_type()->unparseToString() << "\n";
    LOG_DEBUG() << "Used grid: " << gv->unparseToString() << "\n";
    const GridSet *gs = tx.findGrid(gv);
    assert(gs);
    FOREACH(it, gs->begin(), gs->end()) {
      if (*it) {
        LOG_DEBUG() << "gobj: " << (*it)->toString() << "\n";
      } else {
        LOG_DEBUG() << "gobj: NULL\n";
      }
    }
    grid_set.insert(gs->begin(), gs->end());
  }

  LOG_DEBUG() << "Analyzing grid var aliases\n";
  AliasGraph ag(decl, relevantTypes);
  LOG_DEBUG() << ag;
  if (ag.HasMultipleOriginVar()) {
    LOG_ERROR() << "Grid variables must not have multiple assignments.\n";
    abort();
  }
  if (ag.HasNullInitVar()) {
    LOG_ERROR() << "Grid variables must not have NULL initialization.\n";
    abort();
  }

  BOOST_FOREACH(SgInitializedName *gv, gvs) {
    SgInitializedName* originalVar = ag.FindOriginalVar(gv);
    grid_var_set.insert(originalVar);
  }
}

void Kernel::AnalyzeGridWrites(TranslationContext &tx) {
  SgFunctionCallExpPtrList calls =
      tx.getGridEmitCalls(decl_->get_definition());
  set<SgInitializedName*> gvs;
  BOOST_FOREACH (SgFunctionCallExp *fc, calls) {
    gvs.insert(GridType::getGridVarUsedInFuncCall(fc));
  }
  AnalyzeGridAccess(decl_, tx, gvs, wGrids_, wGridVars_);
}

void Kernel::AnalyzeGridReads(TranslationContext &tx) {
  SgFunctionCallExpPtrList calls =
      tx.getGridGetCalls(decl_->get_definition());
  set<SgInitializedName*> gvs;
  BOOST_FOREACH (SgFunctionCallExp *fc, calls) {
    gvs.insert(GridType::getGridVarUsedInFuncCall(fc));
  }
  AnalyzeGridAccess(decl_, tx, gvs, rGrids_, rGridVars_);
  calls =
      tx.getGridGetPeriodicCalls(decl_->get_definition());
  gvs.clear();
  BOOST_FOREACH (SgFunctionCallExp *fc, calls) {
    gvs.insert(GridType::getGridVarUsedInFuncCall(fc));
  }
  AnalyzeGridAccess(decl_, tx, gvs, rGrids_, rGridVars_);
}

static void CollectionReadWriteGrids(SgFunctionDefinition *fdef,
                                     set<SgInitializedName*> &read_grids,
                                     set<SgInitializedName*> &written_grids) {
  vector<SgDotExp*> grid_reads =
      si::querySubTree<SgDotExp>(fdef);
  BOOST_FOREACH(SgDotExp *de, grid_reads) {
    SgVarRefExp *gr = isSgVarRefExp(de->get_lhs_operand());
    PSAssert(gr);
    SgInitializedName *gv = si::convertRefToInitializedName(gr);
    if (!rose_util::GetASTAttribute<GridType>(gv)) {
      // Not a grid
      continue;
    }
    LOG_DEBUG() << "Access to grid var found: "
                << de->unparseToString() << "\n";
    // write access if located as lhs of assign op
    if (isSgAssignOp(de->get_parent()) &&
        isSgAssignOp(de->get_parent())->get_lhs_operand() == de) {
      written_grids.insert(gv);
    } else {
      read_grids.insert(gv);
    }
  }
}

Kernel::Kernel(SgFunctionDeclaration *decl, TranslationContext *tx,
               Kernel *parent) : parent_(parent) {
  this->decl_ =
      isSgFunctionDeclaration(decl->get_definingDeclaration());
  assert(this->decl_);
  if (si::is_C_language() || si::is_Cxx_language()) {
    AnalyzeGridWrites(*tx);
    AnalyzeGridReads(*tx);
  } else if (si::is_Fortran_language()) {
    set<SgInitializedName*> rg, wg;
    CollectionReadWriteGrids(decl->get_definition(), rg, wg);
    AnalyzeGridAccess(decl, *tx, rg, rGrids_, rGridVars_);
    AnalyzeGridAccess(decl, *tx, wg, wGrids_, wGridVars_);
  }
}

Kernel::Kernel(const Kernel &k):
    decl_(k.decl_), rGrids_(k.rGrids_), rGridVars_(k.rGridVars_),
    wGrids_(k.wGrids_), wGridVars_(k.wGridVars_), parent_(k.parent_),
    calls_(k.calls_) {
}

const GridSet& Kernel::GetInGrids() const {
  return rGrids_;
}

const GridSet& Kernel::GetOutGrids() const {
  return wGrids_;
}

#ifdef UNUSED_CODE
bool Kernel::isModified(Grid *g) const {
  if (wGrids_.count(g)) return true;
  FOREACH(it, calls_.begin(), calls_.end()) {
    Kernel *child = it->second;
    if (child->isModified(g)) return true;
  }
  return false;
}

bool Kernel::isModifiedAny(GridSet *gs) const {
  FOREACH (it, gs->begin(), gs->end()) {
    if (isModified(*it)) return true;
  }
  return false;
}
#endif

bool Kernel::IsGridUnmodified(Grid *g) const {
  assert(g != NULL);
  // If NULL is contained, g may be modified.
  if (wGrids_.find(NULL) != wGrids_.end()) return false;
  if (wGrids_.find(g) != wGrids_.end()) return false;
  FOREACH(it, calls_.begin(), calls_.end()) {
    Kernel *child = it->second;
    if (!child->IsGridUnmodified(g)) return false;
  }
  return true;
}

bool Kernel::IsGridParamModified(SgInitializedName *v) const {
  return wGridVars_.find(v) != wGridVars_.end();
}

#ifdef UNUSED_CODE
bool Kernel::isRead(Grid *g) const {
  if (rGrids_.find(g) != rGrids_.end()) return true;
  FOREACH(it, calls.begin(), calls.end()) {
    Kernel *child = it->second;
    if (child->isRead(g)) return true;
  }
  return false;
}

bool Kernel::isReadAny(GridSet *gs) const {
  FOREACH (it, gs->begin(), gs->end()) {
    if (isRead(*it)) return true;
  }
  return false;
}
#endif

bool Kernel::IsGridUnread(Grid *g) const {
  if (rGrids_.find(NULL) != rGrids_.end()) return false;
  if (rGrids_.find(g) != rGrids_.end()) return false;
  FOREACH(it, calls_.begin(), calls_.end()) {
    Kernel *child = it->second;
    if (!child->IsGridUnread(g)) return false;
  }
  return true;
}

bool Kernel::IsGridParamRead(SgInitializedName *v) const {
  return rGridVars_.find(v) != rGridVars_.end();
}

void Kernel::AppendChild(SgFunctionCallExp *call, Kernel *child) {
  assert(calls_.insert(std::make_pair(call, child)).second);
}

const std::string RunKernelAttribute::name = "RunKernel";

const std::string Kernel::name = "Kernel";

const std::string KernelBody::name = "KernelBody";

} // namespace translator
} // namespace kff


text:
title: "Cookie monster on the shirt"
excerpt: "PaperFaces portrait of @clamteeth drawn with Paper for iOS on an iPad."
image:
  path: &image /assets/images/paperfaces-clamteeth-twitter.jpg
  feature: *image
  thumbnail: /assets/images/paperfaces-clamteeth-twitter-150.jpg
categories: [paperfaces]
tags: [portrait, illustration, Paper for iOS]
---

PaperFaces portrait of [@clamteeth](https://twitter.com/clamteeth).

{% include_cached boilerplate/paperfaces.md %}


text:
define([], function ()
{
    var toLeftSlash = function(path)
    {
        return path.replace(/\\/g, '/');
    }

    var loadFromNative = function(ViewClass, require, name, success, fail)
    {
        var el = document.createElement('div');
        el.innerHTML = "

";
        el = el.firstElementChild;

        ViewClass = ViewClass.extend({});

        ViewClass.create = function(options)
        {
            options = options || {};
            options.el = el.cloneNode(true);

            return new ViewClass(options);
        }

        success(ViewClass);
    }

    var loadFromHtml = function(ViewClass, html, require, name, success, fail)
    {
        var el = document.createElement('div');
        el.innerHTML = html;
        if(el.childElementCount != 1)
        {
            var error = requirejs.makeError("binerror_multiplerootnode", "view只能拥有一个根节点,而["+name+".html]中却包含多个根节点", null, name);
            fail(error);

            return ;
        }
        el = el.firstElementChild;

        // Spawn a new class, avoid change the source class create method
        ViewClass = ViewClass.extend({});

        var oldCreate = ViewClass.create;
        ViewClass.create = function(options)
        {
            options = options || {};

            if(!options.html && !options.elem)
            {
                options.el = el.cloneNode(true);
            }

            return oldCreate ? oldCreate.call(this, options) : new this(options);
        }

        if(bin.resolveViewInjectDependencies)
        {
            var oldSuccess = success;
            success = function(ViewClass)
            {
                bin.viewInjectGlobalDeps["view!"+name] = ViewClass;
                bin.resolveViewInjectDependencies(el, function()
                {
                    oldSuccess(ViewClass);
                });
            }
        }

        var cssName = ViewClass.style;
        if(!cssName)
        {
            success(ViewClass);

            return ;
        }

        require(["css!"+toLeftSlash(cssName)], function()
        {
            success(ViewClass);
        }, fail);
    }

    var loadViewClass = function(require, name, success, fail)
    {
        require([name], function(ViewClass)
        {
            // Native
            // if(ViewClass.native)
            // {
            //     loadFromNative(ViewClass, require, name, success, fail);

            //     return ;
            // }

            // Class html
            if(ViewClass.html)
            {
                loadFromHtml(ViewClass, ViewClass.html, require, name, success, fail);

                return ;
            }

            // From view html
            var view = ViewClass.view || name+".html";

            require(['text!'+view], function(html)
            {
                if(!html)
                {
                    success(ViewClass);

                    return ;
                }

                loadFromHtml(ViewClass, html, require, name, success, fail);
            },function()
            {
                success(ViewClass);
            });

        }, fail);
    }

    var plugin =
    {
        load:function(name, req, onLoad, config)
        {
            name = toLeftSlash(name);

            loadViewClass(req, name,
                function(ViewClass)
                {
                    onLoad(ViewClass);
                },
                function(err)
                {
                    onLoad.error(err);
                }
            );
        },
        resolveViewInjectionDependencies:function(el, cb)
        {
            return loadViewDependencies(el, cb);
        }
    }

    return plugin;
});


text:
+++
title = "Note on May 10 EDT 2017 at 11:7"
publishdate = 2017-05-10T15:07:04+00:00
draft = false
syndicated = [ 'https://twitter.com/chrisjohndeluca/status/862323108488904700?s=20' ]
+++

Cultural Anxiety, Not Economic Anxiety, Drove White Working Class Voters to Trump (The Atlantic) https://t.co/2meaq8c1Hn


text:
// Copyright 2017 by PeopleWare n.v..
// 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.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

using JetBrains.Annotations;

using NHibernate;
using NHibernate.Cfg;
using NHibernate.Event;
using NHibernate.Mapping;

using PPWCode.Vernacular.NHibernate.III.SqlServer;
using PPWCode.Vernacular.Persistence.IV;

using Environment = NHibernate.Cfg.Environment;

namespace PPWCode.Vernacular.NHibernate.III.Test
{
    public abstract partial class NHibernateSqlServerFixture<TId, TAuditEntity>
        : NHibernateFixture<TId>
        where TId : IEquatable<TId>
        where TAuditEntity : AuditLog<TId>, new()
    {
        public class TestAuditLogEventListener
            : AuditLogEventListener<TId, TAuditEntity, AuditLogEventContext>
        {
            public TestAuditLogEventListener(
                [NotNull] IIdentityProvider identityProvider,
                [NotNull] ITimeProvider timeProvider,
                bool useUtc)
                : base(identityProvider, timeProvider, useUtc)
            {
            }

            /// <inheritdoc />
            protected override bool CanAuditLogFor(AbstractEvent @event, AuditLogItem auditLogItem, AuditLogActionEnum requestedLogAction)
                => true;

            /// <inheritdoc />
            protected override void OnAddAuditEntities(AuditLogEventContext context)
            {
                // NOP
            }

            /// <inheritdoc />
            protected override AuditLogEventContext CreateContext(IPostDatabaseOperationEventArgs postDatabaseOperationEventArgs)
                => new AuditLogEventContext(postDatabaseOperationEventArgs);
        }

        private Configuration _configuration;
        private string _connectionString;

        [NotNull]
        protected abstract string CatalogName { get; }

        protected abstract bool UseUtc { get; }

        [NotNull]
        protected virtual string ConnectionString
            => _connectionString ?? (_connectionString = RandomizedConnectionString);

        [NotNull]
        protected virtual string RandomizedConnectionString
        {
            get
            {
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(FixedConnectionString);
                Guid guid = Guid.NewGuid();
                builder.InitialCatalog = $"{builder.InitialCatalog}.{guid:D}";
                return builder.ConnectionString;
            }
        }

        [NotNull]
        protected override string FixedConnectionString
            => !string.IsNullOrWhiteSpace(base.FixedConnectionString)
                   ? base.FixedConnectionString
                   : DefaultFixedConnectionString;

        [NotNull]
        protected virtual string DefaultFixedConnectionString
        {
            get
            {
                SqlConnectionStringBuilder builder =
                    new SqlConnectionStringBuilder
                    {
                        DataSource = "localhost",
                        InitialCatalog = CatalogName,
                        IntegratedSecurity = true
                    };
                return builder.ToString();
            }
        }

        [NotNull]
        protected override Configuration Configuration
        {
            get
            {
                if (_configuration == null)
                {
                    _configuration = new Configuration()
                        .DataBaseIntegration(
                            db =>
                            {
                                db.Dialect<MsSqlDialect>();
                                db.ConnectionString = ConnectionString;
                                db.IsolationLevel = IsolationLevel.ReadCommitted;
                                db.BatchSize = 0;
                            })
                        .Configure()
                        .SetProperty(Environment.ShowSql, ShowSql.ToString())
                        .SetProperty(Environment.FormatSql, FormatSql.ToString())
                        .SetProperty(Environment.GenerateStatistics, GenerateStatistics.ToString());

                    IDictionary<string, string> props = _configuration.Properties;
                    if (props.ContainsKey(Environment.ConnectionStringName))
                    {
                        props.Remove(Environment.ConnectionStringName);
                    }

                    IInterceptor interceptor = Interceptor?.GetInterceptor();
                    if (interceptor != null)
                    {
                        _configuration.SetInterceptor(interceptor);
                    }

                    foreach (IRegisterEventListener registerListener in RegisterEventListeners)
                    {
                        registerListener.Register(_configuration);
                    }

                    IPpwHbmMapping ppwHbmMapping = PpwHbmMapping;
                    if (ppwHbmMapping != null)
                    {
                        _configuration.AddMapping(ppwHbmMapping.HbmMapping);
                    }

                    foreach (IAuxiliaryDatabaseObject auxiliaryDatabaseObject in AuxiliaryDatabaseObjects)
                    {
                        IPpwAuxiliaryDatabaseObject ppwAuxiliaryDatabaseObject = auxiliaryDatabaseObject as IPpwAuxiliaryDatabaseObject;
                        ppwAuxiliaryDatabaseObject?.SetConfiguration(_configuration);
                        _configuration.AddAuxiliaryDatabaseObject(auxiliaryDatabaseObject);
                    }
                }

                return _configuration;
            }
        }

        protected virtual void ResetConfiguration()
        {
            _configuration = null;
            _connectionString = null;
        }

        [CanBeNull]
        protected virtual IPpwHbmMapping PpwHbmMapping
            => null;

        [NotNull]
        protected virtual IEnumerable<IAuxiliaryDatabaseObject> AuxiliaryDatabaseObjects
        {
            get { yield break; }
        }

        [NotNull]
        protected virtual IEnumerable<IRegisterEventListener> RegisterEventListeners
        {
            get
            {
                yield return new CivilizedEventListener();
                yield return new TestAuditLogEventListener(new TestIdentityProvider(IdentityName), new TestTimeProvider(UtcNow), UseUtc);
            }
        }

        [CanBeNull]
        protected virtual INhInterceptor Interceptor
            => null;

        protected virtual void CreateCatalog()
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);
            if (SqlServerUtils.CatalogExists(ConnectionString, builder.InitialCatalog))
            {
                SqlServerUtils.DropCatalog(ConnectionString, builder.InitialCatalog);
            }

            SqlServerUtils.CreateCatalog(ConnectionString, builder.InitialCatalog, true);
        }

        protected virtual void DropCatalog()
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);
            if (SqlServerUtils.CatalogExists(ConnectionString, builder.InitialCatalog))
            {
                SqlServerUtils.DropCatalog(ConnectionString, builder.InitialCatalog);
            }
        }
    }
}


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Code Once Deploy Everywhere with Ionic | Julien Renaux, Mobile Era - Oslo, Norway, October 5th 2017</title>

		<meta name="description" content="Code Once Deploy Everywhere with Ionic slides">
		<meta name="author" content="Julien Renaux">

		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

		<link rel="stylesheet" href="../../css/reveal.css">
		<link rel="stylesheet" href="../../css/animate.css">
		<link rel="stylesheet" href="../../css/overwrite.css">
		<link rel="stylesheet" href="../../css/gridism.css">
		<link rel="stylesheet" href="../../css/font-awesome.min.css">
		<link rel="stylesheet" href="../../css/flex-grid.css">
		<link rel="stylesheet" href="../../css/theme/black.css" id="theme">

		<link rel="stylesheet" href="../../lib/css/zenburn.css">

		Back to talks


text:
import React, {
    Component,
    PropTypes,
} from 'react';

import {
    View,
    Platform,
    StyleSheet,
    Animated,
    Easing,
    Dimensions
} from 'react-native';

import { Button, Text } from '@components/ui/';
import { ButtonGroup } from 'react-native-elements';
import { connect } from 'react-redux';
import timer from 'react-native-timer';

import { AppColors, AppStyles, AppSizes} from '@theme/';

const Screen = Dimensions.get('window');

const styles = StyleSheet.create({

    container: {
        position: 'absolute',
        top: 0,
        width: Screen.width,
        overflow: 'hidden',
        alignItems: 'center',
        // borderRadius: 12,
        zIndex: 1
    },
    shadowContainer: {
        padding: 6,
        width: '100%',
        height: '90%',
        backgroundColor: AppColors.base.white,
        shadowColor: AppColors.base.greyDark,
        shadowOpacity: 0.5,
        borderBottomWidth: 1,
        borderBottomColor: AppColors.base.grey,

        //shadowRadius: 1,
        shadowOffset: {
            width: 3,
            height: 3
        },
    },
    message: {
        padding: AppSizes.paddingSml,
        fontSize: 18,
        textAlign: 'center'
    },
    content: {
        justifyContent: 'center',
        alignItems: 'center',
        height: 150,
        paddingBottom: AppSizes.paddingSml,
        //borderColor: AppColors.base.grey,
    },

});

const propTypes = {
    timeout: PropTypes.number,
    animationTime: PropTypes.number,
    heightClosed: PropTypes.number,
    heightOpen: PropTypes.number,
};

const defaultProps = {
    timeout: 3000,
    animationTime: 300,
    top: 0,
    topHidden: -150,
    okText: 'OK',
    cancelText: 'Cancel'

};

const mapStateToProps = (state) => {
    return {
        message: state.notification.message,
        deferred: state.notification.deferred,
        okText: state.notification.okText,
        cancelText: state.notification.cancelText
    }
}

class Notification extends Component {

    timerName = 'notificationTimer';

    constructor(props) {
        super(props);
        this.updateIndex = this.updateIndex.bind(this);
        this.open = this.open.bind(this);
        this.close = this.close.bind(this);
        this.state = {
            selectedIndex: 1,
            top: new Animated.Value(this.props.topHidden),
        };
    }

    updateIndex(selectedIndex) {
        this.setState({selectedIndex});
        if (selectedIndex === 1) {
            this.props.deferred.resolve();
        } else {
            this.props.deferred.reject();
        }
        const timeOut = selectedIndex === 0 ? 200 : 0;
        timer.setTimeout(this.timerName, () => {
            this.close();
        }, timeOut);
    }

    componentWillReceiveProps(nextProps) {
        console.log('nextProps: ' + JSON.stringify(nextProps));
        this.open();
        const timerId = setTimeout(() => {
            this.close();
            clearTimeout(timerId);
        }, this.props.timeout);

    }

    open = () => {
        Animated.timing(this.state.top, {
            duration: this.props.animationTime,
            toValue: this.props.top,
            easing: Easing.cubic
        }).start();
    }

    close = () => {
        Animated.timing(this.state.top, {
            duration: this.props.animationTime,
            toValue: this.props.topHidden,
            easing: Easing.cubic
        }).start(() => {
            this.setState({selectedIndex: 1});
        });
    }

    render() {
        return (
            <Animated.View style={[styles.container, {
                       top: this.state.top
                       }]}>
                <View style={styles.shadowContainer}>
                    <View style={styles.content}>
                        <View>
                            <Text style={[styles.message]}>{this.props.message}</Text>
                        </View>
                        <ButtonGroup
                            onPress={this.updateIndex}
                            selectedIndex={this.state.selectedIndex}
                            buttons={[this.props.cancelText, this.props.okText]}
                            containerStyle={{height: 50, width: AppSizes.screen.width * 0.50}}
                            selectedBackgroundColor={AppColors.base.green}
                        />
                    </View>
                </View>
            </Animated.View>
        );
    }

    componentWillUnmount() {
        timer.clearTimeout(this.timerName);
    }

}

Notification.propTypes = propTypes;
Notification.defaultProps = defaultProps;

export default connect(mapStateToProps)(Notification);


text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data></data>

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

        <android.support.design.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true">

            <include layout="@layout/toolbar" />

            <!-- body... -->
            <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:id="@+id/activity_help"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                android:paddingBottom="@dimen/activity_vertical_margin"
                app:layout_behavior="@string/appbar_scrolling_view_behavior"
                tools:context="info.puzz.graphanything.activities.HelpActivity">

                <WebView
                    android:id="@+id/help_viewer"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />

            </ScrollView>
            <!-- ...body -->

        </android.support.design.widget.CoordinatorLayout>

        <include layout="@layout/navigation" />

    </android.support.v4.widget.DrawerLayout>
</layout>


text:
package com.opitzconsulting.orcas.maven;

import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import de.opitzconsulting.orcas.diff.OrcasMain;
import de.opitzconsulting.orcas.diff.ParametersCall;

/**
 * This is the main mojo to update the database-schema according to the orcas-script files.
 */
@Mojo( name = "updateStatics" )
public class OrcasUpdateStatics extends BaseOrcasMojo
{
  /**
   * The logname for spooling.
   */
  @Parameter( defaultValue = "update-statics" )
  private String logname;

  @Override
  protected String getLogname()
  {
    return logname;
  }

  @Override
  protected void executeWithParameters( ParametersCall pParameters )
  {
    if( staticsfolder.exists() )
    {
      pParameters.setModelFile( staticsfolder.toString() );
      pParameters.setSqlplustable( false );
      pParameters.setOrderColumnsByName( false );

      new OrcasMain().mainRun( pParameters );
    }
    else
    {
      getLog().info( "no statics found" );
    }
  }
}


text:
(function( $ ) {

  var collapsedClass = 'collapsed',
      $searchInput = $('#search'),
      $questions = $('.js-question'),
      $questionInners = $questions.find('.question__inner'),
      $questionTitles = $questions.find('.question__title'),

  keyup = function() {
    // Value they've entered
    var val = this.value.toLowerCase();

    // Filter elements based on if their string exists in the product model
    $questions.each(function( i, el ) {
      var $el = $( el ),
          text = $.trim( $questionTitles.eq( i ).text() ).toLowerCase(),
          passes = text.indexOf( val ) !== -1;

      if ( passes ) {
        if ( $el.hasClass( collapsedClass ) ) {
          $el.removeClass( collapsedClass );
        }
      } else {
        if ( !$el.hasClass( collapsedClass ) ) {
          $el.addClass( collapsedClass );
        }
      }

    });
  },

  debouncedKeyup = $.debounce( 100, keyup ),

  // Height cannot be transitioned from auto to zero, so it must be set.
  setHeights = function() {
    var heights = [];

    // Remove current hegith
    $questions.css( 'height', '' );

    // Get new heights
    // Inner div needed because setting a height on the elements
    // self doesn't get the correct new height :\
    $questionInners.each(function() {
      heights.push( $( this ).css( 'height' ) );
    });

    // Set new heights
    $questions.each(function( i ) {
      $( this ).css( 'height', heights[ i ] );
    });
  },

  onWindowResize = function() {
    setHeights();
  };

  if ( !$searchInput.length ) {
    return;
  }

  $searchInput.on( 'keyup change', debouncedKeyup );
  $( window ).on( 'resize', $.debounce( 250, onWindowResize ) );
  onWindowResize();

}( jQuery ));


text:
@echo off
pushd %~dp0
"%VS120COMNTOOLS%..\IDE\mstest" /test:Microsoft.Protocols.TestSuites.MS_OXWSSYNC.S01_SyncFolderHierarchy.MSOXWSSYNC_S01_TC01_SyncFolderHierarchy_InboxFolder /testcontainer:..\..\MS-OXWSSYNC\TestSuite\bin\Debug\MS-OXWSSYNC_TestSuite.dll /runconfig:..\..\MS-OXWSSYNC\MS-OXWSSYNC.testsettings /unique
pause


text:
package de.samdev.absgdx.framework.map.background;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;

import de.samdev.absgdx.framework.map.TileMap;

/**
 * This is a parallax scrolling background.
 *
 * The given Texture should be smaller than the map.
 * The texture will then move slower than the actual map to provide a parallax effect
 *
 */
public class ParallaxBackground extends MapBackground {

	private final TextureRegion texture;
	private final float scale;

	/**
	 * Create a new parallax Background
	 *
	 * @param tex the background texture
	 * @param scale the scale to use for the background (bigger numbers scale down)
	 */
	public ParallaxBackground(TextureRegion tex, float scale) {
		this.texture = tex;
		this.scale = scale;
	}

	/**
	 * Create a new parallax Background
	 *
	 * @param tex the background texture
	 * @param scale the scale to use for the background (bigger numbers scale down)
	 */
	public ParallaxBackground(Texture tex, float scale) {
		this(new TextureRegion(tex), scale);
	}

	@Override
	public void draw(SpriteBatch sbatch, Vector2 map_offset, TileMap map, Rectangle visible) {
		float percentage_x = map_offset.x / (map.width - visible.width * 1f);
		float maximum_x = (map.width - (texture.getRegionWidth() / scale));
		float pos_x = percentage_x * maximum_x;

		float percentage_y = map_offset.y / (map.height - visible.height * 1f);
		float maximum_y = (map.height - (texture.getRegionHeight() / scale));
		float pos_y = percentage_y * maximum_y;

		sbatch.draw(texture, pos_x, pos_y, texture.getRegionWidth() / scale, texture.getRegionHeight() / scale);
	}

}