text:
/**
 * Loader constructor
 * @param parameters
 * @constructor
 */
function Loader(parameters) {

    // Variables
    this.previous = {
        link: '',
        target: 'content'
    };
    this.link = '';
    this.target = '';
    this.eventCounter = 0;

    // Loader default settings
    this.config = {
        domain: 'admin',
        csrf: '',
        root: '',
        targets: {
            content: 'body',
            subcontent: 'body',
            full: 'html'
        }
    };

    // Save given parameters
    this.parameters = parameters;

    // Apply given parameters
    this.applyParameters();

    // Run core
    this.core();

    // Callback
    if("callback" in this.config)
        this.config.callback(this.config.domain);

}

/**
 * Loader applyParameters Function
 * Save defined parameters to config
 */
Loader.prototype.applyParameters = function() {

    let allowedParameters = ['domain', 'callback', 'csrf', 'root', 'targets', 'onStart', 'onError', 'onDone'];
    for(let i in this.parameters) {
        if(allowedParameters.indexOf(i) === -1) continue;
        this.config[i] = this.parameters[i];
    }

};

/**
 * Loader core Function
 * Controls the entire instance and Loader events
 */
Loader.prototype.core = function() {

    // Create link events
    this.createEvents();

};

/**
 * Loader createEvents Function
 * Creates link events
 */
Loader.prototype.createEvents = function() {

    let links = document.querySelectorAll('[data-link]');
    for(let i = 0; i < links.length; ++i) {
        links[i].onclick = function() {
            if("onStart" in this.config)
                this.config.onStart();
            let link   = links[i].getAttribute('data-link');
            let target = links[i].getAttribute('data-target');
            this.executeEvent(link, target);
        }.bind(this);
        links[i].onmouseup = function(event) {
            if(event.which === 2) {
                if("onStart" in this.config)
                    this.config.onStart();
                let link   = links[i].getAttribute('data-link');
                this.executeEvent(link, 'blank');
                event.preventDefault();
            }
        }.bind(this);
    }

};

/**
 * Loader executeEvent Function
 * Controls flow of the fired link element events
 * @param link
 * @param target
 */
Loader.prototype.executeEvent = function(link, target) {

    // Save first state
    if(this.eventCounter === 0)
        this.saveCurrentState('', 'content');

    // Save event details
    this.link = link;
    this.target = target;

    if(this.target === 'blank') {
        this.openNewTab();
        this.config.onDone(false, this.link, true);
        return true;
    }

    // Load new content
    this.getContent();

};

/**
 * Loader openNewTab Function
 * Open link in the new tab
 */
Loader.prototype.openNewTab = function() {

    let newTab = window.open(this.config.root + this.link, '_blank');
    newTab.location;

};

/**
 * Loader saveCurrentState Function
 * Save first/default page state into browser history
 */
Loader.prototype.saveCurrentState = function(link, target) {

    let title = document.querySelector('title').getAttribute('data-locale');
    if(this.config.root.slice(-1) !== "/")
        this.config.root += '/';
    window.history.pushState({
        title: title,
        link: link,
        target: target
    }, '', this.config.root + link);
    ++this.eventCounter;

};

/**
 * Loader getContent Function
 * Get the new content for clicked link
 */
Loader.prototype.getContent = function() {

    let link = this.link;
    if(this.config.csrf !== '') {
        let csrf = document.querySelector('meta[name="' + this.config.csrf + '"]').getAttribute('content');
        link = this.config.root + this.link + '&' + this.config.csrf + '=' + csrf;
    }
    let url = link;
    let ajaxRequest = new XMLHttpRequest;
    ajaxRequest.onload = function() {
        this.handleContent(ajaxRequest);
    }.bind(this);
    ajaxRequest.open('GET', url);
    ajaxRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    ajaxRequest.send();

};

/**
 * Loader handleContent Function
 * Handle response content
 * @param response
 */
Loader.prototype.handleContent = function(response) {

    // Save response contents
    let status = response.status;
    let content = response.responseText;

    // Handle response by statuses
    if(status !== 200) {
        // onError
        if("onError" in this.config)
            this.config.onError(status);
    }

    // Handle response by content type
    try {
        let result = JSON.parse(content);
        // onError
        if("onError" in this.config)
            this.config.onError(result.code);
    } catch(error) {
        this.renderContent(content);
    }

};

/**
 * Loader renderContent Function
 * Render response content
 * @param content
 */
Loader.prototype.renderContent = function(content) {

    // Replaced element
    let element = document.querySelector(this.config.targets[this.target]);

    // Replace content
    element.remove();
    let body = document.querySelector('body');
    body.insertAdjacentHTML('beforeend', content);

    // Create window history event
    this.saveCurrentState(this.link, this.target);
    this.createEvents();

    // onDone
    if("onDone" in this.config)
        this.config.onDone(content, this.link);

};


text:
package com.infobip.numberdetector.sms;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

/**
 * Broadcast receiver used as argument when performing SMS message send.
 * SmsManager will provide status result which will be used to check whether message was sent or not.
 */
public class SmsSentBroadcastReceiver extends BroadcastReceiver {

	private Handler handler;

	public SmsSentBroadcastReceiver(Handler smsSentHandler) {
		handler = smsSentHandler;
	}

	@Override
	public void onReceive(Context context, Intent intent) {
        Message message = handler.obtainMessage();
        message.arg1 = getResultCode();

		handler.sendMessage(message);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.intel.analytics.bigdl.utils.tf.loaders

import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.utils.RandomGenerator.RNG
import com.intel.analytics.bigdl.utils.T
import com.intel.analytics.bigdl.utils.tf.Tensorflow.{listIntAttr, typeAttr}
import com.intel.analytics.bigdl.utils.tf.{PaddingType, TensorflowDataFormat, TensorflowSpecHelper}
import org.tensorflow.framework.{DataType, NodeDef}

class DepthwiseConv2dNativeBackpropInputSpec extends TensorflowSpecHelper {
  "DepthwiseConv2dNativeBackpropInput forward" should "be correct when depth multiplyer is 1" in {
    RNG.setSeed(100)
    val filter = Tensor[Float](2, 2, 3, 1).rand()
    val size = Tensor[Int](T(4, 24, 24, 3))
    compare[Float](
      NodeDef.newBuilder()
        .setName("depthwise_conv2d_backinput_test")
        .putAttr("T", typeAttr(DataType.DT_FLOAT))
        .putAttr("padding", PaddingType.PADDING_VALID.value)
        .putAttr("data_format", TensorflowDataFormat.NHWC.value)
        .putAttr("strides", listIntAttr(Seq(1, 1, 1, 1)))
        .setOp("DepthwiseConv2dNativeBackpropInput"),
      Seq(size, filter, Tensor[Float](4, 23, 23, 3).rand()),
      0
    )
  }

  "DepthwiseConv2dNativeBackpropInput forward" should "be correct when depth multiplyer is 2" in {
    RNG.setSeed(100)
    val filter = Tensor[Float](2, 2, 3, 2).rand()
    val size = Tensor[Int](T(4, 24, 24, 3))
    compare[Float](
      NodeDef.newBuilder()
        .setName("depthwise_conv2d_backinput_test")
        .putAttr("T", typeAttr(DataType.DT_FLOAT))
        .putAttr("padding", PaddingType.PADDING_VALID.value)
        .putAttr("data_format", TensorflowDataFormat.NHWC.value)
        .putAttr("strides", listIntAttr(Seq(1, 1, 1, 1)))
        .setOp("DepthwiseConv2dNativeBackpropInput"),
      Seq(size, filter, Tensor[Float](4, 23, 23, 6).rand()),
      0
    )
  }
}


text:
#ifndef INCLUDE_KLTQT_TRACKER_H_
#define INCLUDE_KLTQT_TRACKER_H_

#include <fstream>
#include <opencv2/core/core.hpp>
#include <vector>

#include <common_types.h>
#include <feature_tracker.h>
#include <quad_tree.h>

/*
* Short Baseline Feature Tracker extension:
* Kanade-Lucas-Tomasi (KLT) using a quadtree
* for feature selection.
*/
class KLTQTTracker : public FeatureTracker
{

protected:
    // Used in goodFeatureToTrack() to adjust  the quality of feature
    float quality_level_;

    // Mask of regions than will be used on goodFeatureToTrack()
    cv::Mat mask_;

    // Number of points in the last keyframe
    size_t num_points_last_kf_;

    /**
     * Detects keypoints in the current frame based on a qualityLevel
     */
    void detect_keypoints(const cv::Mat& mask);

    /**
     *  Adds keypoints detected in the previous frame to the tracker
     */
    void add_keypoints();

    /**
     * Updates internal buffers (updates the previous points (in the current frame)
     * with the current points (from the previous frame))
     */
    void update_buffers();

public:
    // Quadtree data structure
    std::unique_ptr<QuadTree> tree;

    // Debug
    std::vector<cv::Point2f> rejected_points_;

    // Default constructor
    KLTQTTracker();

    /**
     * Constructor
     * @param min_pts minimum number of tracked points
     * @param max_pts maximum number of tracked points
     * @param log_stats boolean for log statistics state default is false
     */
    KLTQTTracker(const int &min_pts, const int &max_pts, const bool &log_stats = false);

    /**
     * Main member function: tracks keypoints between the current frame and the previous.
     * @param img rgb image
     * @return true if the current frame is a keyframe.
     */
    bool track(const cv::Mat &img, const cv::Mat& mask = cv::Mat());
};

#endif /* INCLUDE_KLTQT_TRACKER_H_ */


text:
#ifndef SVGUnitTypes_h
#define SVGUnitTypes_h

#include "bindings/core/v8/ScriptWrappable.h"
#include "core/svg/SVGEnumeration.h"
#include "platform/heap/Handle.h"
#include "wtf/RefCounted.h"

namespace blink {

class SVGUnitTypes final : public RefCountedWillBeGarbageCollected<SVGUnitTypes>, public ScriptWrappable {
    DEFINE_WRAPPERTYPEINFO();
public:
    enum SVGUnitType {
        SVG_UNIT_TYPE_UNKNOWN               = 0,
        SVG_UNIT_TYPE_USERSPACEONUSE        = 1,
        SVG_UNIT_TYPE_OBJECTBOUNDINGBOX     = 2
    };

    void trace(Visitor*) { }

private:
    SVGUnitTypes(); // No instantiation.
};

template<> const SVGEnumerationStringEntries& getStaticStringEntries<SVGUnitTypes::SVGUnitType>();

} // namespace blink

#endif // SVGUnitTypes_h


text:
package com.github.lburgazzoli.sandbox;

/**
 */
public class MiscMain {
    public static void main(String[] args) throws Exception {
        CharSequence cs1 = new StringBuffer("test").toString();
        CharSequence cs2 = new StringBuffer("test");

        System.out.println("length1   : " + cs1.length());
        System.out.println("toString1 : " + cs1.toString());
        System.out.println("length2   : " + cs2.length());
        System.out.println("toString2 : " + cs2.toString());
    }
}


text:
NewDossier.widgets = {
	lbxMain: ["wm.Layout", {"horizontalAlign":"left","verticalAlign":"top"}, {}]
}


text:
import contextlib
import datetime
import json
import StringIO

from django.contrib.auth import logout as logout_user
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseRedirect, JsonResponse, Http404, HttpResponse, HttpResponseBadRequest
from django.db.models import Count
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.http import urlencode, urlquote

from django_ical import feedgenerator

from simpleoncall.forms.auth import AuthenticationForm, RegistrationForm
from simpleoncall.forms.account import EditAccountForm, ChangePasswordForm
from simpleoncall.forms.schedule import TeamScheduleForm
from simpleoncall.forms.team import CreateTeamForm, SelectTeamForm, InviteTeamForm
from simpleoncall.decorators import require_authentication, require_selected_team
from simpleoncall.models import APIKey, TeamMember, TeamInvite, User, TeamSchedule
from simpleoncall.models import Alert, EventStatus, NotificationSetting, NotificationType

@require_authentication()
@require_selected_team()
def dashboard(request):
    end = timezone.now()
    start = end - datetime.timedelta(hours=12)
    date_added__range = (start, end)

    alerts = Alert.objects.filter(team=request.team, date_added__range=date_added__range).order_by('-date_added')[:10]
    alert_statuses = Alert.objects.filter(
        team=request.team, date_added__range=date_added__range
    ).values('status').annotate(total=Count('status'))

    alert_times = Alert.objects.filter(
        team=request.team, date_added__range=date_added__range
    ).values('date_added').annotate(total=Count('date_added')).order_by('-date_added')

    alert_timeseries = {}
    while start <= end:
        bucket = start - datetime.timedelta(minutes=start.minute % 60,
                                            seconds=start.second,
                                            microseconds=start.microsecond)
        alert_timeseries[bucket.strftime('%s')] = 0
        start += datetime.timedelta(minutes=60)

    for alert in alert_times:
        added = alert['date_added']
        bucket = added - datetime.timedelta(minutes=added.minute % 60,
                                            seconds=added.second,
                                            microseconds=added.microsecond)
        alert_timeseries[bucket.strftime('%s')] += alert['total']

    context = {
        'title': 'Dashboard',
        'alerts': alerts,
        'statuses': dict((a['status'], a['total']) for a in alert_statuses),
        'timeseries': json.dumps(alert_timeseries),
    }
    return render(request, 'dashboard.html', context)

def login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('dashboard'))

    context = {
        'login_form': AuthenticationForm(),
        'register_form': RegistrationForm(),
        'login': True,
        'title': 'Login',
    }
    return render(request, 'login.html', context)

def register(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('dashboard'))

    context = {
        'login_form': AuthenticationForm(),
        'register_form': RegistrationForm(),
        'register': True,
        'title': 'Register',
        'next': urlquote(request.GET.get('next')),
    }
    return render(request, 'login.html', context)

def logout(request):
    logout_user(request)
    return HttpResponseRedirect(reverse('login'))

@require_authentication()
@require_selected_team()
def settings(request):
    api_keys = APIKey.objects.filter(team=request.team)
    members = TeamMember.objects.filter(team=request.team)

    context = {
        'title': '%s Settings' % (request.team.name, ),
        'api_keys': api_keys,
        'members': members,
        'invite_team_form': InviteTeamForm(),
    }
    return render(request, 'settings.html', context)

@require_authentication()
def account(request):
    alerts = request.user.get_notification_settings()
    if not alerts:
        alerts = [
            NotificationSetting(id=0, type=NotificationType.EMAIL, time=0)
        ]

    context = {
        'title': 'Account',
        'edit_account_form': EditAccountForm(instance=request.user),
        'change_password_form': ChangePasswordForm(instance=request.user),
        'alerts': alerts,
    }
    return render(request, 'account.html', context)

@require_authentication()
@require_selected_team()
def alerts(request):
    alert_count = Alert.objects.filter(team=request.team).count()
    alerts = Alert.objects.filter(team=request.team).order_by('-date_updated')[:10]
    context = {
        'title': 'Alerts',
        'alert_count': alert_count,
        'alerts': alerts,
    }
    return render(request, 'alerts.html', context)

@require_authentication()
@require_selected_team()
def schedule(request):
    schedule = request.team.get_active_schedule()
    oncall = None
    if schedule:
        oncall = schedule.get_currently_on_call()
    context = {
        'title': 'Schedule',
        'schedule': schedule,
        'oncall': oncall,
    }
    return render(request, 'schedule.html', context)

@require_authentication(require_team=False)
def create_team(request):
    create_team_form = CreateTeamForm(request.POST or None)
    if create_team_form.is_valid():
        team = create_team_form.save(request)
        messages.success(request, 'New team %s created' % team.name)
        return HttpResponseRedirect(reverse('dashboard'))

    context = {
        'title': 'Create New Team',
        'create_team_form': create_team_form,
    }
    return render(request, 'team/create.html', context)

@require_authentication()
def select_team(request):
    select_team_form = SelectTeamForm(request.POST or None, request.user)
    if select_team_form.is_valid():
        team = select_team_form.save(request)
        messages.success(request, 'Team changed to %s' % team.name)
        return HttpResponseRedirect(reverse('dashboard'))

    context = {
        'title': 'Select Team',
        'select_team_form': select_team_form,
    }
    return render(request, 'team/select.html', context)

def invite_accept(request):
    code = request.GET.get('code')
    email = request.GET.get('email')
    if not code or not email:
        return HttpResponseRedirect(reverse('dashboard'))

    invite = TeamInvite.objects.get(invite_code=code, email=email)
    if not invite:
        return HttpResponseRedirect(reverse('dashboard'))

    user = User.objects.get(email=email)
    if user:
        try:
            team_member = TeamMember.objects.get(team=invite.team, user=user)
        except ObjectDoesNotExist:
            team_member = None
        if team_member:
            messages.warning(request, 'already a member of team %s' % (invite.team.name, ))
        else:
            team_member = TeamMember(team=invite.team, user=user)
            team_member.save()
            messages.success(request, 'added to team %s' % (invite.team.name, ))
    else:
        args = {
            'code': code,
            'email': email,
        }
        next = '%s?%s' % (reverse('invite-accept'), urlencode(args))
        redirect = '%s?next=%s' % (reverse('register'), urlquote(next))
        return HttpResponseRedirect(redirect)

    return HttpResponseRedirect(reverse('dashboard'))

@require_authentication()
@require_selected_team()
def alert_ack(request, alert_id):
    alert = Alert.objects.get(id=alert_id)
    if not alert:
        messages.error(request, 'Alert %s was not found' % (alert_id, ))
    elif alert.status == EventStatus.ACKNOWLEDGED:
        messages.warning(request, 'Alert %s already acknowledged' % (alert_id, ))
    else:
        alert.status = EventStatus.ACKNOWLEDGED
        alert.save(user=request.user)
        messages.success(request, 'Alert %s was acknowledged' % (alert_id, ))

    return HttpResponseRedirect(reverse('alerts'))

@require_authentication()
@require_selected_team()
def alert_resolve(request, alert_id):
    alert = Alert.objects.get(id=alert_id, team=request.team)
    if not alert:
        messages.error(request, 'Alert %s was not found' % (alert_id, ))
    elif alert.status == EventStatus.RESOLVED:
        messages.warning(request, 'Alert %s already resolved' % (alert_id, ))
    else:
        alert.status = EventStatus.RESOLVED
        alert.save(user=request.user)
        messages.success(request, 'Alert %s was resolved' % (alert_id, ))

    return HttpResponseRedirect(reverse('alerts'))

@require_authentication()
@require_selected_team()
def alert_view(request, alert_id):
    alert = Alert.objects.get(id=alert_id, team=request.team)
    if not alert:
        messages.error(request, 'Alert %s was not found' % (alert_id, ))
        return HttpResponseRedirect(reverse('dashboard'))

    context = {
        'title': alert.title,
        'event': alert,
    }
    return render(request, 'alert.html', context)

@require_authentication()
@require_selected_team()
def edit_schedule(request):
    msg = None
    schedule_id = None
    if 'schedule_id' in request.POST:
        schedule_id = int(request.POST['schedule_id'])

    dummy_schedule = TeamSchedule(team=request.team)
    data = None if schedule_id else request.POST or None
    new_schedule_form = TeamScheduleForm(request.team, data, instance=dummy_schedule)
    saved = False
    if request.method == 'POST' and not schedule_id:
        if new_schedule_form.is_valid():
            new_schedule_form.save()
            saved = True
            msg = 'New Schedule Added'

    schedule_forms = []
    for schedule in request.team.get_schedules():
        data = None
        if schedule.id == schedule_id:
            data = request.POST
        schedule_form = TeamScheduleForm(request.team, data, instance=schedule)
        if data and schedule_form.is_valid():
            schedule_form.save()
            msg = 'Schedule Updated'
        schedule_forms.append(schedule_form)

    if msg:
        messages.success(request, msg)

    context = {
        'title': 'Edit Schedule',
        'active_schedule': request.team.get_active_schedule(),
        'schedule_forms': schedule_forms,
        'new_schedule_form': new_schedule_form,
        'hidden_schedule_form': not saved or request.method != 'POST',
    }
    return render(request, 'edit_schedule.html', context)

@require_authentication()
@require_selected_team()
def delete_schedule(request):
    id = request.GET.get('id')
    if id:
        schedule = TeamSchedule.objects.get(team=request.team, id=id)
        schedule.delete()
        messages.success(request, 'Schedule %s Deleted' % (schedule.name, ))
    else:
        messages.error(request, 'Unknown Schedule Id')
    return HttpResponseRedirect(reverse('edit-schedule'))

@require_authentication()
@require_selected_team()
def partial(request, partial):
    context = {
        'request': request,
        'user': request.user,
        'team': request.team,
    }
    html = render_to_string('partials/%s.html' % (partial, ), context)
    return JsonResponse({'html': html})

@require_authentication()
@require_selected_team()
def team_calendar(request):
    schedule = request.team.get_active_schedule()
    if not schedule:
        return Http404('Unkown Calendar')

    feed = feedgenerator.ICal20Feed(
        title='Team %s On-Call Schedule %s' % (request.team.name, schedule.name),
        link=request.build_absolute_uri(request.path),
        description='Team %s On-Call Schedule %s' % (request.team.name, schedule.name),
        language='en',
        subtitle='Generated by SimpleOnCall',
        author_email='service@simpleoncall.com',
        author_link='http://simpleoncall.com',
        author_name='SimpleOnCall',
        feed_url=request.build_absolute_uri(request.path)
    )
    now = timezone.now()
    starting_time = datetime.datetime(now.year, now.month, now.day, schedule.starting_time, tzinfo=timezone.utc)
    next_start_time = None
    currently_oncall = None
    for i in xrange(90):
        now = starting_time + datetime.timedelta(days=i)
        oncall = schedule.get_currently_on_call(now)
        if next_start_time is None:
            next_start_time = now
            currently_oncall = oncall
        elif currently_oncall.id != oncall.id:
            feed.add_item(
                title='%s On-Call' % (oncall.get_display_name(), ),
                link=request.build_absolute_uri(reverse('schedule')),
                description='%s On-Call' % (currently_oncall.get_display_name(), ),
                start_datetime=next_start_time,
                end_datetime=now
            )
            next_start_time = now
            currently_oncall = oncall

    feed.add_item(
        title='%s On-Call' % (oncall.get_display_name(), ),
        link=request.build_absolute_uri(reverse('schedule')),
        description='%s On-Call' % (currently_oncall.get_display_name(), ),
        start_datetime=next_start_time,
        end_datetime=now
    )

    results = None
    with contextlib.closing(StringIO.StringIO()) as output:
        feed.write(output, 'utf-8')
        results = output.getvalue()
    if results is not None:
        return HttpResponse(results, content_type='text/calendar; charset=utf-8')
    return HttpResponseBadRequest('Could not generate iCal at this time')


text:
/* eslint-disable */

'use strict';

/*::
import type { ClientRequest, ClientQuery } from 'relay-runtime';
import {example_client_object as queryExampleClientObjectResolver} from "../../../relay-runtime/store/__tests__/resolvers/ExampleClientObjectResolver.js";
// Type assertion validating that `queryExampleClientObjectResolver` resolver is correctly implemented.
// A type error here indicates that the type signature of the resolver module is incorrect.
(queryExampleClientObjectResolver: () => ?Query__example_client_object$normalization);
import type { Query__example_client_object$normalization } from "./../../../relay-runtime/store/__tests__/resolvers/__generated__/Query__example_client_object$normalization.graphql";
export type ExampleWithOutputTypeTestQuery$variables = {||};
export type ExampleWithOutputTypeTestQuery$data = {|
  +example_client_object: ?{|
    +description: ?string,
  |},
|};
export type ExampleWithOutputTypeTestQuery = {|
  response: ExampleWithOutputTypeTestQuery$data,
  variables: ExampleWithOutputTypeTestQuery$variables,
|};
*/

var node/*: ClientRequest*/ = {
  "fragment": {
    "argumentDefinitions": [],
    "kind": "Fragment",
    "metadata": {
      "hasClientEdges": true
    },
    "name": "ExampleWithOutputTypeTestQuery",
    "selections": [
      {
        "kind": "ClientEdgeToClientObject",
        "concreteType": "ClientObject",
        "backingField": {
          "alias": null,
          "args": null,
          "fragment": null,
          "kind": "RelayResolver",
          "name": "example_client_object",
          "resolverModule": require('./../../../relay-runtime/store/__tests__/resolvers/ExampleClientObjectResolver').example_client_object,
          "path": "example_client_object",
          "normalizationInfo": {
            "concreteType": "ClientObject",
            "plural": false,
            "normalizationNode": require('./../../../relay-runtime/store/__tests__/resolvers/__generated__/Query__example_client_object$normalization.graphql')
          }
        },
        "linkedField": {
          "alias": null,
          "args": null,
          "concreteType": "ClientObject",
          "kind": "LinkedField",
          "name": "example_client_object",
          "plural": false,
          "selections": [
            {
              "alias": null,
              "args": null,
              "kind": "ScalarField",
              "name": "description",
              "storageKey": null
            }
          ],
          "storageKey": null
        }
      }
    ],
    "type": "Query",
    "abstractKey": null
  },
  "kind": "Request",
  "operation": {
    "argumentDefinitions": [],
    "kind": "Operation",
    "name": "ExampleWithOutputTypeTestQuery",
    "selections": [
      {
        "kind": "ClientExtension",
        "selections": [
          {
            "name": "example_client_object",
            "args": null,
            "fragment": null,
            "kind": "RelayResolver",
            "storageKey": null
          }
        ]
      }
    ]
  },
  "params": {
    "cacheID": "9c67ea6ed47a1a5f70890647fefbc8c9",
    "id": null,
    "metadata": {},
    "name": "ExampleWithOutputTypeTestQuery",
    "operationKind": "query",
    "text": null
  }
};

if (__DEV__) {
  (node/*: any*/).hash = "6af44b9f4263bf177df8d084dc79d494";
}

module.exports = ((node/*: any*/)/*: ClientQuery<
  ExampleWithOutputTypeTestQuery$variables,
  ExampleWithOutputTypeTestQuery$data,
>*/);


text:
<!DOCTYPE html>

<TITLE>Manpage of CONSOLE</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">

linux manpages

{"type":"documentation"}

CONSOLE

Section: Linux Programmer's Manual (4)
Updated: 1994-10-31
Index
Return to Main Contents

NAME

console - console terminal and virtual consoles

DESCRIPTION

A Linux system has up to 63 virtual consoles
(character devices with major number 4 and minor number 1 to 63),
usually called /dev/ttyn with 1 < n < 63.
The current console is also addressed by
/dev/console or /dev/tty0, the character device with
major number 4 and minor number 0.
The device files /dev/* are usually created using the script MAKEDEV,
or using
mknod(1),

usually with mode 0622 and owner root.tty.

Before kernel version 1.1.54 the number of virtual consoles was
compiled into the kernel (in tty.h: #define NR_CONSOLES 8)
and could be changed by editing and recompiling.
Since version 1.1.54 virtual consoles are created on the fly,
as soon as they are needed.

Common ways to start a process on a console are:
(a) tell
init(8)

(in
inittab(5))

to start a
mingetty(8)

(or
agetty(8))

on the console;
(b) ask
openvt(1)

to start a process on the console;
(c) start X --- it will find the first unused console,
and display its output there.
(There is also the ancient
doshell(8).)

Common ways to switch consoles are: (a) use Alt+Fn or
Ctrl+Alt+Fn to switch to console n; AltGr+Fn
might bring you to console n+12 [here Alt and AltGr refer
to the left and right Alt keys, respectively];
(b) use Alt+RightArrow or Alt+LeftArrow to cycle through
the presently allocated consoles; (c) use the program
chvt(1).

(The key mapping is user settable, see
loadkeys(1);

the above mentioned key combinations are according to the default settings.)

The command
deallocvt(1)

(formerly disalloc)
will free the memory taken by the screen buffers for consoles
that no longer have any associated process.

Properties

Consoles carry a lot of state.
I hope to document that some other time.
The most important fact is that the consoles simulate vt100 terminals.
In particular, a console is reset to the initial state by printing the two
characters ESC c.
All escape sequences can be found in
console_codes(4).

FILES

/dev/console

/dev/tty*

SEE ALSO

chvt(1),

deallocvt(1),

loadkeys(1),

mknod(1),

openvt(1),

console_codes(4),

console_ioctl(4),

tty(4),

ttyS(4),

charsets(7),

agetty(8),

init(8),

mapscrn(8),

mingetty(8),

resizecons(8),

setfont(8)

COLOPHON

This page is part of release 3.22 of the Linux
man-pages

project.
A description of the project,
and information about reporting bugs,
can be found at
http://www.kernel.org/doc/man-pages/.

Index

NAME

DESCRIPTION

Properties

FILES

SEE ALSO

COLOPHON

This document was created by
man2html,
using the manual pages.

Time: 05:33:53 GMT, December 24, 2015


text:
import test from 'ava';
import Button from '../src/button';

/* eslint-disable max-len */

export function createWidget(attrs = {}, service = 'facebook') {
	let widget = document.createElement('div');
	widget.className = widget.innerHTML = service;
	for (let name in attrs) {
		widget.setAttribute(name, attrs[name]);
	}
	return widget;
}

test('Button constructor should initialize a button object', t => {
	let widget = createWidget();
	let button = new Button(widget, {});

	t.is(button.service, 'facebook');
});

test('Button constructor should accept service name as a data-attribute', t => {
	let widget = createWidget({
		'data-service': 'facebook',
	});
	widget.className = '';
	let button = new Button(widget, {});

	t.is(button.service, 'facebook');
});

test('Button should merge user buttons with default buttons', t => {
	let widget = createWidget({}, 'pony');
	let button = new Button(widget, {});

	t.is(button.service, 'pony');
});

test('User should be able to overwrite base buttons options', t => {
	let widget = createWidget({}, 'twitter');
	let button = new Button(widget, {});

	t.is(button.service, 'twitter');
	t.is(button.options.popupUrl, 'http://facebook.com/');
});

test('Button constructor should read widget's data-attributes', t => {
	let widget = createWidget({
		'data-url': 'http://example.com',
	});
	let button = new Button(widget, {});

	t.same(button.data, {
		url: 'http://example.com',
	});
});

test('Button constructor should merge widget's data-attributes, options passed to constructor and service options', t => {
	let widget = createWidget({
		'data-title': 'Foo',
	});
	let button = new Button(widget, {
		url: 'http://example.com',
		title: 'Bar',
	});

	t.same(button.options, {
		url: 'http://example.com',
		title: 'Foo',
		icon: 'M13 0H3C1 0 0 1 0 3v10c0 2 1 3 3 3h5V9H6V7h2V5c0-2 2-2 2-2h3v2h-3v2h3l-.5 2H10v7h3c2 0 3-1 3-3V3c0-2-1-3-3-3z',
		popupUrl: 'https://www.facebook.com/sharer/sharer.php?u={url}',
		popupWidth: 600,
		popupHeight: 500,
	});
});

test('Button constructor should create a button markup', t => {
	let widget = createWidget();
	let button = new Button(widget, {});

	let w = button.widget;
	t.is(w.className, 'social-likes__widget social-likes__widget_facebook');

	let svg = w.querySelector('svg');
	t.ok(svg);
	t.is(svg.className, 'social-likes__icon social-likes__icon_facebook');

	let btn = w.querySelector('div');
	t.ok(btn);
	t.is(btn.className, 'social-likes__button social-likes__button_facebook');
	t.is(btn.innerHTML.trim(), 'facebook');
});

test('Button should preserve HTML in a widget', t => {
	const html = '<b>facebook</b>';
	let widget = createWidget();
	widget.innerHTML = html;
	let button = new Button(widget, {});

	let btn = button.widget.querySelector('div');
	t.is(btn.innerHTML.trim(), html);
});

test('Button should make an <a> tag if a service has a clickUrl option', t => {
	let widget = createWidget({}, 'clickable');
	let button = new Button(widget, {});

	let btn = button.widget.querySelector('a');
	t.ok(btn);
	t.is(btn.href, 'http://example.com/');
});

test('Button should add __invisible-button class if a service has a clickUrl option but a widget has no text', t => {
	let widget = createWidget({}, 'clickable');
	widget.innerHTML = '';
	let button = new Button(widget, {});

	let btn = button.widget.querySelector('a');
	t.ok(btn);
	t.is(btn.className, 'social-likes__invisible-button social-likes__invisible-button_clickable');
});

test('Button should not create a button element if a widget has no text', t => {
	let widget = createWidget({});
	widget.innerHTML = '';
	let button = new Button(widget, {});

	t.true(button.widget.classList.contains('social-likes__widget_notext'));
	t.notOk(button.widget.querySelector('div'));
	t.notOk(button.widget.querySelector('a'));
});

test('Button.makeUrl should return a URL with URL and title of the current button', t => {
	let widget = createWidget({});
	let button = new Button(widget, {
		url: 'http://foo.com/',
		title: 'Pony',
	});

	let r = button.makeUrl('http://bar.com/?url={url}&title={title}');

	t.is(r, 'http://bar.com/?url=http%3A%2F%2Ffoo.com%2F&title=Pony');
});

test('Button.makeUrlWithParams should return a URL with appended data-attributes, should ignore service, url, etc.', t => {
	let widget = createWidget({
		'data-service': 'facebook',
		'data-media': 'http://foo.com/pony.jpg',
		'data-url': 'http://bar.com/',
		'data-title': 'Pony',
	});
	let button = new Button(widget);

	let r = button.makeUrlWithParams('http://baz.com/?url={url}&title={title}');

	t.is(r, 'http://baz.com/?url=http%3A%2F%2Fbar.com%2F&title=Pony&media=http%3A%2F%2Ffoo.com%2Fpony.jpg');
});

test('Button.update should update options', t => {
	let widget = createWidget();
	let button = new Button(widget, {
		title: 'Bar',
	});

	button.update({
		title: 'Foo',
	});

	t.is(button.options.title, 'Foo');
});


text:
#include <aws/redshift-data/model/GetStatementResultResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::RedshiftDataAPIService::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

GetStatementResultResult::GetStatementResultResult() :
    m_totalNumRows(0)
{
}

GetStatementResultResult::GetStatementResultResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
    m_totalNumRows(0)
{
  *this = result;
}

GetStatementResultResult& GetStatementResultResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("ColumnMetadata"))
  {
    Array<JsonView> columnMetadataJsonList = jsonValue.GetArray("ColumnMetadata");
    for(unsigned columnMetadataIndex = 0; columnMetadataIndex < columnMetadataJsonList.GetLength(); ++columnMetadataIndex)
    {
      m_columnMetadata.push_back(columnMetadataJsonList[columnMetadataIndex].AsObject());
    }
  }

  if(jsonValue.ValueExists("NextToken"))
  {
    m_nextToken = jsonValue.GetString("NextToken");

  }

  if(jsonValue.ValueExists("Records"))
  {
    Array<JsonView> recordsJsonList = jsonValue.GetArray("Records");
    for(unsigned recordsIndex = 0; recordsIndex < recordsJsonList.GetLength(); ++recordsIndex)
    {
      Array<JsonView> fieldListJsonList = recordsJsonList[recordsIndex].AsArray();
      Aws::Vector<Field> fieldListList;
      fieldListList.reserve((size_t)fieldListJsonList.GetLength());
      for(unsigned fieldListIndex = 0; fieldListIndex < fieldListJsonList.GetLength(); ++fieldListIndex)
      {
        fieldListList.push_back(fieldListJsonList[fieldListIndex].AsObject());
      }
      m_records.push_back(std::move(fieldListList));
    }
  }

  if(jsonValue.ValueExists("TotalNumRows"))
  {
    m_totalNumRows = jsonValue.GetInt64("TotalNumRows");

  }

  return *this;
}


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute

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.

=cut

=head1 CONTACT

 Please email comments or questions to the public Ensembl
 developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

 Questions may also be sent to the Ensembl help desk at
 <http://www.ensembl.org/Help/Contact>.

=cut

# Ensembl module for Bio::EnsEMBL::Variation::SampleGenotypeFeature
#
#

=head1 NAME

Bio::EnsEMBL::Variation::SampleGenotypeFeature-Module representing the genotype
of a single sample at a single position

=head1 SYNOPSIS

    print $genotype->variation()->name(), "\n";
    print $genotype->allele1(), '/', $genotype->allele2(), "\n";
    print $genotype->sample()->name(), "\n";

=head1 DESCRIPTION

This is a class representing the genotype of a single diploid sample at
a specific position

=head1 METHODS

=cut

use strict;
use warnings;

package Bio::EnsEMBL::Variation::SampleGenotypeFeature;

use Bio::EnsEMBL::Variation::SampleGenotype;
use Bio::EnsEMBL::Feature;
use Bio::EnsEMBL::Utils::Argument qw(rearrange);
use Bio::EnsEMBL::Utils::Exception qw(throw warning);

use vars qw(@ISA);

@ISA = qw(Bio::EnsEMBL::Variation::SampleGenotype Bio::EnsEMBL::Feature);

=head2 new

  Arg [-adaptor] :
    Bio::EnsEMBL::Variation::DBSQL::IndividualAdaptor
  Arg [-START] :
    see superclass constructor
  Arg [-END] :
    see superclass constructor
  Arg [-STRAND] :
    see superclass constructor
  Arg [-SLICE] :
    see superclass constructor
  Arg [-genotype] :
    arrayref - arrayref of alleles making up this genotype (in haplotype order)
  Arg [-variation] :
    Bio::EnsEMBL::Variation::Variation - The variation associated with this
    genotype
  Arg [-sample] :
    Bio::EnsEMBL::Sample - The sample this genotype is for.
  Example    : $ind_genotype = Bio:EnsEMBL::Variation::SampleGenotype->new(
					-start      => 100,
					-end        => 100,
					-strand     => 1,
					-slice      => $slice,
					-genotype   => ['A','T'],
					-variation  => $variation,
					-sample => $sample
				);
  Description: Constructor.  Instantiates SampleGenotype object.
  Returntype : Bio::EnsEMBL::Variation::SampleGenotype
  Exceptions : throw on bad argument
  Caller     : general
  Status     : Stable

=cut

sub new {
	my $caller = shift;
	my $class = ref($caller) || $caller;

	my $self = $class->SUPER::new(@_);

	my ($adaptor, $genotype, $var, $var_id, $sample) =
	rearrange([qw(adaptor genotype variation _variation_id sample)],@_);

	if(defined($var) && (!ref($var) || !$var->isa('Bio::EnsEMBL::Variation::Variation'))) {
		throw("Bio::EnsEMBL::Variation::Variation argument expected");
	}

	if(defined($sample) && (!ref($sample) || !$sample->isa('Bio::EnsEMBL::Variation::Sample'))) {
		throw("Bio::EnsEMBL::Variation::Sample argument expected");
	}

	$self->{'adaptor'} = $adaptor;
	$self->{'genotype'} = $genotype;
	$self->{'sample'} = $sample;
	$self->{'variation'} = $var;
	$self->{'_variation_id'} = $var_id;

	return $self;
}

sub variation_feature {
  my $self = shift;

  $self->{variation_feature} = shift if @_;

  if(!defined($self->{variation_feature})) {
    $self->{variation_feature} = (grep {$_->{start} == $self->{start} && $_->seq_region_name cmp $self->{slice}->seq_region_name} @{$self->variation->get_all_VariationFeatures})[0];
  }

  return $self->{variation_feature};
}

=head2 differences
  Arg [1]    : Hashref $differences (optional)
  Example    : $differences = $sample_genotype_feature->differences();
               while (my ($sample_name, $genotype_string) = each %$differences) {
                 print "$sample_name $genotype_string\n";
               }
  Description: Getter/Setter for Hashref of differences as computed in
               Bio::EnsEMBL::Variation::DBSQL::SampleGenotypeFeatureAdaptor::fetch_all_differences_by_Slice.
               Keys are the sample names and corresponding values are the genotype strings.
  Returntype : Hashref
  Exceptions : None
  Caller     : General
  Status     : Stable
=cut
sub differences {
  my $self = shift;
  $self->{differences} = shift if @_;
  return $self->{differences};
}

1;


text:
RamDataQuery::RamDataQuery()
{
    m_cache.resize(1);

}

void RamDataQuery::getData()
{
    //Update the data in the cache , this function also returns
    //the instant memory usage but we discard it since we actually
    // need the cache
    m_mem.getMemoryUsage();
    //Get the ordered data
    m_mem.getOrderedMemoryUsageCache(m_cache[0]);

}


text:
/**
 * Node that creates a transfomration matrix in 2d from values.
 */
dbm.registerClass("dbm.flow.nodes.math.transformation.TransformationTo2dMatrixNode", "dbm.core.FlowBaseObject", function(objectFunctions, staticFunctions, ClassReference) {
	//console.log("dbm.flow.nodes.math.transformation.TransformationTo2dMatrixNode");

	//Self reference
	var TransformationTo2dMatrixNode = dbm.importClass("dbm.flow.nodes.math.transformation.TransformationTo2dMatrixNode");

	//Error report

	//Depenencies
	var Matrix = dbm.importClass("dbm.core.data.matrices.Matrix");

	//Utils

	//Constants

	/**
	 * Constructor
	 */
	objectFunctions._init = function() {
		//console.log("dbm.flow.nodes.math.transformation.TransformationTo2dMatrixNode::_init");

		this.superCall();

		this._x = this.createProperty("x", 0);
		this._y = this.createProperty("y", 0);
		this._rotate = this.createProperty("rotate", 0);
		this._scaleX = this.createProperty("scaleX", 1);
		this._scaleY = this.createProperty("scaleY", 1);
		this._outputMatrix = this.createProperty("outputMatrix", Matrix.createIdentity(3, 3));

		this.createUpdateFunction("default", this._update, [this._x, this._y, this._rotate, this._scaleX, this._scaleY], [this._outputMatrix]);

		return this;
	};

	/**
	 * Updates the flow for this node.
	 *
	 * @param	aFlowUpdateNumber	Number	The integer that keeps track of when the flow was updated.
	 */
	objectFunctions._update = function(aFlowUpdateNumber) {
		//console.log("dbm.flow.nodes.math.transformation.TransformationTo2dMatrixNode::_update");

		var rotate = this._rotate.getValueWithoutFlow();
		var scaleX = this._scaleX.getValueWithoutFlow();
		var scaleY = this._scaleY.getValueWithoutFlow();

		var theMatrix = this._outputMatrix.getValueWithoutFlow();
		theMatrix.setValue(0, 0, Math.cos(rotate)*scaleX);
		theMatrix.setValue(1, 0, -1*Math.sin(rotate)*scaleX);
		theMatrix.setValue(0, 1, Math.sin(rotate)*scaleY);
		theMatrix.setValue(1, 1, Math.cos(rotate)*scaleY);
		theMatrix.setValue(2, 0, this._x.getValueWithoutFlow());
		theMatrix.setValue(2, 1, this._y.getValueWithoutFlow());

		this._outputMatrix.setFlowAsUpdated(aFlowUpdateNumber);
	};

	/**
	 * Sets all the references to null. Part of the destroy function.
	 */
	objectFunctions.setAllReferencesToNull = function() {

		this._x = null;
		this._y = null;
		this._rotate = null;
		this._scaleX = null;
		this._scaleY = null;
		this._outputMatrix = null;

		this.superCall();
	};

	/**
	 * Creates a new object of this class.
	 *
	 * @param	aX			Property|Number		The x positon to set to the matrix. (Optional)
	 * @param	aY			Property|Number		The y positon to set to the matrix. (Optional)
	 * @param	aRotate		Property|Number		The rotation to set to the matrix. (Optional)
	 * @param	aScaleX		Property|Number		The x scale to set to the matrix. (Optional)
	 * @param	aScaleY		Property|Number		The y scale to set to the matrix. (Optional)
	 *
	 * @return	DisplayBaseObject	The newly created object.
	 */
	staticFunctions.create = function(aX, aY, aRotate, aScaleX, aScaleY) {
		//console.log("dbm.flow.nodes.math.transformation.TransformationTo2dMatrixNode::create");
		var newNode = (new ClassReference()).init();
		newNode.setPropertyInputWithoutNull("x", aX);
		newNode.setPropertyInputWithoutNull("y", aY);
		newNode.setPropertyInputWithoutNull("rotate", aRotate);
		newNode.setPropertyInputWithoutNull("scaleX", aScaleX);
		newNode.setPropertyInputWithoutNull("scaleY", aScaleY);
		return newNode;
	};
});


text:
int sun3_memory_io_open(char const *file_name, sun3_memory_file *fid)
{
	return (*fid= open(file_name, O_RDONLY)) != -1;
}

int sun3_memory_io_read(sun3_memory_file fid, sun3_memory *mem, sun3_memory_address addr, size_t len)
{
	assert(sun3_memory_inv(mem));
	if (addr < mem->write_start || addr+len > mem->end) {
		sun3_errors_bus_error(mem->errors);
	}
	return read(fid, mem->data+addr, len);
}

int sun3_memory_io_write(sun3_memory_file fid, sun3_memory *mem, sun3_memory_address addr, size_t len)
{
	assert(sun3_memory_inv(mem));
	if (addr < mem->read_start || addr+len > mem->end) {
		sun3_errors_bus_error(mem->errors);
	}
	return write(fid, mem->data+addr, len);
}

int sun3_memory_io_close(sun3_memory_file fid)
{
	return close(fid) == 0;
}


text:
*******************************
Image reprojection (resampling)
*******************************

Introduction
============

The *reproject* package implements image reprojection (resampling) methods
for astronomical images and more generally n-dimensional data. These assume
that the WCS information contained in the data are correct. This package does
**not** do image registration, which is the process of aligning images where
one or more images may have incorrect or missing WCS.

Requirements
============

This package has the following hard run time dependencies:

* `Python <http://www.python.org/>`__ 2.7 or 3.5 or later

* `Numpy <http://www.numpy.org/>`__ 1.10 or later

* `Astropy <http://www.astropy.org/>`__ 2.0 or later

* `Scipy <http://www.scipy.org/>`__ 0.9 or later

* `astropy-healpix <https://astropy-healpix.readthedocs.io>`_ 0.2 or later for HEALPIX image reprojection

* `six <http://pypi.python.org/pypi/six/>`__

and the following optional dependencies:

* `shapely <https://toblerity.org/shapely/project.html>`_ 1.6 or later for some of the mosaicking functionality

If you build the package from the source, the following additional packages
are required:

* `Cython <http://cython.org>`__

and to run the tests, you will also need:

* `Matplotlib <http://matplotlib.org/>`__

* `pytest-arraydiff <https://github.com/astrofrog/pytest-fits>`__

Installation
============

Using pip
---------

To install *reproject* with `pip <http://www.pip-installer.org/en/latest/>`_,
simply run:

    pip install reproject

Using conda
-----------

To install *reproject* with `anaconda <https://continuum.io/>`_, simply run::

    conda install -c astropy reproject

.. _quickstart:

Quick start
===========

A common use case is that you have two FITS images, and want to reproject one
to the same header as the other. This can easily be done with the *reproject*
package, and we demonstrate this in the following example. We start off by
downloading two example images from `http://data.astropy.org <http://data.astropy.org>`_,
namely a 2MASS K-band image and an MSX band E image of the Galactic center::

    from astropy.io import fits
    from astropy.utils.data import get_pkg_data_filename
    hdu1 = fits.open(get_pkg_data_filename('galactic_center/gc_2mass_k.fits'))[0]
    hdu2 = fits.open(get_pkg_data_filename('galactic_center/gc_msx_e.fits'))[0]

We can examine the two images (this makes use of the
`wcsaxes <wcsaxes.readthedocs.io>`_ package behind the scenes)::

    from astropy.wcs import WCS
    import matplotlib.pyplot as plt

    ax1 = plt.subplot(1,2,1, projection=WCS(hdu1.header))
    ax1.imshow(hdu1.data, origin='lower', vmin=-100., vmax=2000.)
    ax1.coords.grid(color='white')
    ax1.coords['ra'].set_axislabel('Right Ascension')
    ax1.coords['dec'].set_axislabel('Declination')
    ax1.set_title('2MASS K-band')

    ax2 = plt.subplot(1,2,2, projection=WCS(hdu2.header))
    ax2.imshow(hdu2.data, origin='lower', vmin=-2.e-4, vmax=5.e-4)
    ax2.coords.grid(color='white')
    ax2.coords['glon'].set_axislabel('Galactic Longitude')
    ax2.coords['glat'].set_axislabel('Galactic Latitude')
    ax2.coords['glat'].set_axislabel_position('r')
    ax2.coords['glat'].set_ticklabel_position('r')
    ax2.set_title('MSX band E')

.. image:: images/index-2.png
   :align: center
   :width: 80%

We now reproject the MSX image to be in the same projection as the 2MASS image::

    from reproject import reproject_interp
    array, footprint = reproject_interp(hdu2, hdu1.header)

The :func:`~reproject.reproject_interp` function above returns the
reprojected array as well as an array that provides information on the
footprint of the first image in the new reprojected image plane (essentially
which pixels in the new image had a corresponding pixel in the old image). We
can now visualize the reprojected data and footprint::

    from astropy.wcs import WCS
    import matplotlib.pyplot as plt

    ax1 = plt.subplot(1,2,1, projection=WCS(hdu1.header))
    ax1.imshow(array, origin='lower', vmin=-2.e-4, vmax=5.e-4)
    ax1.coords.grid(color='white')
    ax1.coords['ra'].set_axislabel('Right Ascension')
    ax1.coords['dec'].set_axislabel('Declination')
    ax1.set_title('Reprojected MSX band E image')

    ax2 = plt.subplot(1,2,2, projection=WCS(hdu1.header))
    ax2.imshow(footprint, origin='lower', vmin=0, vmax=1.5)
    ax2.coords.grid(color='white')
    ax1.coords['ra'].set_axislabel('Right Ascension')
    ax1.coords['dec'].set_axislabel('Declination')
    ax2.coords['dec'].set_axislabel_position('r')
    ax2.coords['dec'].set_ticklabel_position('r')
    ax2.set_title('MSX band E image footprint')

.. image:: images/index-4.png
   :align: center
   :width: 80%

We can then write out the image to a new FITS file. Note that, as for
plotting, we can use the header from the 2MASS image since both images are
now in the same projection::

   fits.writeto('msx_on_2mass_header.fits', array, hdu1.header, clobber=True)

The *reproject* package supports a number of different algorithms for
reprojection (interpolation, flux-conserving reprojection, etc.) and
different types of data (images, spectral cubes, HEALPIX images, etc.). For
more information, we encourage you to read the full documentation below!

Documentation
=============

The reproject package consists of a few high-level functions to do
reprojection using different algorithms, which depend on the type of data
that you want to reproject.

.. toctree::
   :maxdepth: 2

   celestial
   healpix
   noncelestial
   footprints

Reference/API
=============

.. automodapi:: reproject
   :no-inheritance-diagram:


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Caesar Cipher</title>
  <meta name="description" content="Jerry Chen's website">

  <link rel="stylesheet" href="/assets/main.css">
  <link rel="canonical" href="http://jerryjrchen.com/intro/proj/caesar/">

  <link rel="alternate" type="application/rss+xml" title="jerryjrchen" href="http://jerryjrchen.com/feed.xml">

  <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#000000">
<meta name="theme-color" content="#ffffff">

  <meta name="twitter:card" content="summary">

  <meta name="twitter:title" content="Caesar Cipher">
  <meta name="twitter:description" content="Jerry Chen's website">

  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Bitter:400,400i,700" rel="stylesheet">

Caesar Cipher  Download

Introduction

The Caesar cipher is named
after Julius Caesar, who used it to encrypt his secret communications.  It's a
type of substitution cipher where every letter is shifted a fixed number of
positions down the alphabet to produce the encrypted result.

Your challenge is to implement the Caesar cipher in Python! Fill in the
code so that we can both encode and decode text. All code you need to
edit is located in caesar.py.

You do not need to read or understand the contents of cipher.py.

Examples

For example, with a right shift of 3, the letter 'a' is replaced with 'd', 'm'
is replaced with 'p', and so on.

If we encrypted the following message with a right shift of 4:

"Julius Caesar"

It would come out as:

"Nypmyw Geiwev"

Which looks like gibberish to the untrained eye.  If you want to try some
examples out yourself, here's an online Caesar encoder/decoder.

Additional Details

It's recommended that you fill in the functions from top to bottom:

shift_letter

caesar_encode

caesar_decode

Test each function as you finish it! It's easier to fix bugs if you easily
pinpoint their location.

There is a hint in the docstring for shift_letter if you need help
figuring it out.

Assume that your inputs will not require any wrapping. This means that you
will not get an input of 'y' with a right shift of 2 (going to 'a'). As a
bonus challenge, you may implement this behavior.

Testing

Run the doctests to check your work by doing python3 -m doctest
caesar.py.

Once you've passed all the tests, you can either call the functions
yourself from the interpreter or run cipher.py.

© Jerry Chen.
Jekyll +
whiteglass,
and hosted by GitHub Pages.


text:
#ifndef INCLUDED_IMATHEXC_H
#define INCLUDED_IMATHEXC_H

//-----------------------------------------------
//
//	Imath library-specific exceptions
//
//-----------------------------------------------

#include "IexBaseExc.h"

namespace Imath {

DEFINE_EXC (NullVecExc, ::Iex::MathExc)		// Attempt to normalize
						// null vector

DEFINE_EXC (NullQuatExc, ::Iex::MathExc) 	// Attempt to normalize
						// null quaternion

DEFINE_EXC (SingMatrixExc, ::Iex::MathExc)	// Attempt to invert
						// singular matrix

DEFINE_EXC (ZeroScaleExc, ::Iex::MathExc)	// Attempt to remove zero
						// scaling from matrix

DEFINE_EXC (IntVecNormalizeExc, ::Iex::MathExc)	// Attempt to normalize
						// a vector of whose elements
                                                // are an integer type

} // namespace Imath

#endif


text:
package org.apache.commons.collections4;

/**
 * Defines a simple key value pair.
 * <p>
 * A Map Entry has considerable additional semantics over and above a simple
 * key-value pair. This interface defines the minimum key value, with just the
 * two get methods.
 * </p>
 *
 * @param <K> the type of the key
 * @param <V> the type of the value
 * @since 3.0
 */
public interface KeyValue<K, V> {

    /**
     * Gets the key from the pair.
     *
     * @return the key
     */
    K getKey();

    /**
     * Gets the value from the pair.
     *
     * @return the value
     */
    V getValue();

}


text: Copyright (c) Linnéa H-Muje | Unicorn


text:
package	org.apache.derby.impl.sql.compile;

import java.sql.Types;
import java.util.List;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.reference.ClassName;
import org.apache.derby.iapi.reference.SQLState;
import org.apache.derby.iapi.services.context.ContextManager;
import org.apache.derby.shared.common.sanity.SanityManager;
import org.apache.derby.iapi.types.DataTypeDescriptor;
import org.apache.derby.iapi.types.TypeId;

/**
 * This node represents a unary XXX_length operator
 *
 */

public final class LengthOperatorNode extends UnaryOperatorNode
{
	private int parameterType;
	private int parameterWidth;

    LengthOperatorNode(ValueNode operator, ContextManager cm)
            throws StandardException {
        super(operator, cm);

        String op = "char_length";
        String methodNam = "charLength";
        parameterType = Types.VARCHAR;
        parameterWidth = TypeId.VARCHAR_MAXWIDTH;

        setOperator(op);
        setMethodName(methodNam);
	}

	/**
	 * Bind this operator
	 *
	 * @param fromList			The query's FROM list
	 * @param subqueryList		The subquery list being built as we find SubqueryNodes
     * @param aggregates        The aggregate list being built as we find AggregateNodes
	 *
	 * @return	The new top of the expression tree.
	 *
	 * @exception StandardException		Thrown on error
	 */
    @Override
    ValueNode bindExpression(
        FromList fromList, SubqueryList subqueryList, List<AggregateNode> aggregates)
			throws StandardException
	{
		TypeId	operandType;

        bindOperand(fromList, subqueryList, aggregates);

		/*
		** Check the type of the operand - this function is allowed only on
		** string value types.
		*/
		operandType = operand.getTypeId();
		switch (operandType.getJDBCTypeId())
		{
				case Types.CHAR:
				case Types.VARCHAR:
				case Types.BINARY:
				case Types.VARBINARY:
				case Types.LONGVARBINARY:
				case Types.LONGVARCHAR:
                case Types.BLOB:
                case Types.CLOB:
					break;

				default:
					throw StandardException.newException(SQLState.LANG_UNARY_FUNCTION_BAD_TYPE,
											getOperatorString(),
											operandType.getSQLTypeName());
		}

		/*
		** The result type of XXX_length is int.
		*/
		setType(new DataTypeDescriptor(
							TypeId.INTEGER_ID,
							operand.getTypeServices().isNullable()
						)
				);
		return this;
	}

	/**
	 * Bind a ? parameter operand of the XXX_length function.
	 *
	 * @exception StandardException		Thrown on error
	 */
    @Override
	void bindParameter()
			throws StandardException
	{
		/*
		** According to the SQL standard, if XXX_length has a ? operand,
		** its type is varchar with the implementation-defined maximum length
		** for a varchar.
		** Also, for XXX_length, it doesn't matter what is VARCHAR's collation
		** (since for XXX_length, no collation sensitive processing is
		** is required) and hence we will not worry about the collation setting
		*/

		operand.setType(DataTypeDescriptor.getBuiltInDataTypeDescriptor(parameterType, true,
												parameterWidth));
	}

	/**
	 * This is a length operator node.  Overrides this method
	 * in UnaryOperatorNode for code generation purposes.
	 */
    @Override
    String getReceiverInterfaceName() {
	    return ClassName.ConcatableDataValue;
	}
}


text:
require "spec_helper"

describe Lob::V1::Check do

  before :each do
    @sample_address_params = {
      name:    "TestAddress",
      email:   "test@test.com",
      address_line1: "123 Test Street",
      address_line2: "Unit 199",
      city:    "Mountain View",
      state:   "CA",
      country: "US",
      zip:     94085
    }

    @sample_bank_account_params = {
      routing_number: "122100024",
      account_number: "123456789"
    }
  end

  subject { Lob(api_key: ENV["LOB_API_KEY"]) }

  describe "list" do
    it "should list checks" do
      VCR.use_cassette('list_checks') do
        new_address = subject.addresses.create @sample_address_params

        new_bank_account = subject.bank_accounts.create(
          routing_number: @sample_bank_account_params[:routing_number],
          bank_address: @sample_address_params,
          account_number: @sample_bank_account_params[:account_number],
          account_address: @sample_address_params,
          signatory: "John Doe"
        )

        new_check = subject.checks.create(
          bank_account: new_bank_account["id"],
          to: @sample_address_params,
          amount: 2000
        )

        list_result = subject.checks.list
        assert /#{new_check["id"]}/i =~ list_result.to_s
      end
    end
  end

  describe "create" do
    it "should create a check with bank account id" do
      VCR.use_cassette('create_check_with_bank_account_id') do
        new_address = subject.addresses.create @sample_address_params

        new_bank_account = subject.bank_accounts.create(
          routing_number: @sample_bank_account_params[:routing_number],
          bank_address: @sample_address_params,
          account_number: @sample_bank_account_params[:account_number],
          account_address: @sample_address_params,
          signatory: "John Doe"
        )

        result = subject.checks.create(
          bank_account: new_bank_account["id"],
          to: new_address["id"],
          amount: "2000"
        )

        result["amount"].to_s.must_equal("2000.00")
      end
    end
  end

  describe "find" do
    it "should find a check" do
      VCR.use_cassette('find_check') do
        new_address = subject.addresses.create @sample_address_params

        new_bank_account = subject.bank_accounts.create(
          routing_number: @sample_bank_account_params[:routing_number],
          bank_address: @sample_address_params,
          account_number: @sample_bank_account_params[:account_number],
          account_address: @sample_address_params,
          signatory: "John Doe"
        )

        new_check = subject.checks.create(
          bank_account: new_bank_account["id"],
          to: new_address["id"],
          amount: 2000
        )

        result = subject.checks.find(new_check["id"])
        result["id"].must_equal(new_check["id"])
      end
    end
  end

end


text:
<?php // content="text/plain; charset=utf-8"
require_once ('jpgraph/jpgraph.php');
require_once ('jpgraph/jpgraph_line.php');

// Some (random) data
$ydata = array(11,3,8,12,5,1,9,13,5,7);

// Size of the overall graph
$width=350;
$height=250;

// Create the graph and set a scale.
// These two calls are always required
$graph = new Graph($width,$height);
$graph->SetScale('intlin');

// Create the linear plot
$lineplot=new LinePlot($ydata);

// Add the plot to the graph
$graph->Add($lineplot);

// Display the graph
$graph->Stroke();
?>


text:
const gulp              = require('gulp');
const customPlumber     = require('../custom-modules/plumber');
const sassLint          = require('gulp-sass-lint');

// require config
const config            = require('../config');

// Linting Sass files
gulp.task('lint:scss', () => {
    return gulp.src(config.sass.src)
        .pipe(sassLint({
            config: config.scsslint.config
        }))
        .pipe(sassLint.format())
        .pipe(sassLint.failOnError())
});


text:
<?php

namespace Bootstrap\Form\View\Helper;

use Zend\Form\View\Helper\FormCheckbox as ZfFormCheckbox;
use Zend\Form\ElementInterface;
use Zend\Form\Element\Checkbox as CheckboxElement;
use Zend\Form\Exception;

/**
 *
 * @author AT21572
 *
 */
class FormCheckbox extends ZfFormCheckbox {

	public function render(ElementInterface $element)
	{
		if (!$element instanceof CheckboxElement) {
			throw new Exception\InvalidArgumentException(sprintf(
				'%s requires that the element is of type Zend\Form\Element\Checkbox',
				__METHOD__
			));
		}

		$name = $element->getName();
		if (empty($name) && $name !== 0) {
			throw new Exception\DomainException(sprintf(
				'%s requires that the element has an assigned name; none discovered',
				__METHOD__
			));
		}

		$attributes            = $element->getAttributes();
		$attributes['name']    = $name;
		$attributes['type']    = $this->getInputType();
		$attributes['value']   = $element->getCheckedValue();
		$closingBracket        = $this->getInlineClosingBracket();

		if ($element->isChecked()) {
			$attributes['checked'] = 'checked';
		}

		$rendered = sprintf(
			'
<input %s%s',
			$this->createAttributesString($attributes),
			$closingBracket . $element->getOption('checked_label') . '
'
		);

		if ($element->useHiddenElement()) {
			$hiddenAttributes = array(
				'name'  => $attributes['name'],
				'value' => $element->getUncheckedValue(),
			);

			$rendered = sprintf(
				'<input type="hidden" %s%s',
				$this->createAttributesString($hiddenAttributes),
				$closingBracket
			) . $rendered;
		}

		return $rendered;
	}
}

?>


text:
#include "middleware/khronos/glsl/glsl_common.h"

#include "middleware/khronos/glsl/glsl_dataflow_visitor.h"
#include "middleware/khronos/glsl/glsl_dataflow_print.h"
#include "middleware/khronos/glsl/glsl_map.h"
#include "middleware/khronos/glsl/glsl_fastmem.h"
#include "middleware/khronos/glsl/2708/glsl_allocator_4.h"

#ifndef NDEBUG

#include <stdlib.h>

#define GRAPHVIZ_GRAPH_NAME			"Dataflow"
#define GRAPHVIZ_CLUSTER_PREFIX		"line_num"

static void dpostv_gather_by_line_num(Dataflow* dataflow, void* data)
{
   Map *map = (Map *)data;

	// See whether dataflow->line_num is in the map.
	DataflowChain* chain = (DataflowChain *)glsl_map_get(map, (void *)dataflow->line_num, true);

	// If it's not in the map, insert it.
	if (!chain)
	{
		chain = (DataflowChain *)malloc_fast(sizeof(DataflowChain));

		// Init.
		glsl_dataflow_chain_init(chain);

		// Insert.
		glsl_map_put(map, (void *)dataflow->line_num, chain);
	}

	// Add this node to the chain.
	glsl_dataflow_chain_append(chain, dataflow);
}

typedef enum
{
   EDGE_SOLID,
   EDGE_DASHED,
   EDGE_SEQUENCE,

	EDGE_STYLE_COUNT
} EdgeStyle;

static void print_edge(FILE* f, EdgeStyle style, Dataflow* supplier, Dataflow* consumer)
{
   fprintf(f, "\tn%x -> n%x", (size_t)consumer, (size_t)supplier);

   switch (style) {
   case EDGE_SOLID:
      break;
   case EDGE_DASHED:
      fprintf(f, " [style=dashed]");
      break;
   case EDGE_SEQUENCE:
      fprintf(f, " [constraint=false,color=red]");
      break;
   default:
      UNREACHABLE();
      break;
   }

   fprintf(f, ";\n");
}

static void print_edges(FILE* f, Dataflow* dataflow, bool cross)
{
   DataflowChainNode *node;

   // cross: print only edges that do cross a cluster boundary
   // !cross: print only edges that do not cross a cluster boundary
   switch (dataflow->flavour)
	{
		case DATAFLOW_CONST_BOOL:
		case DATAFLOW_CONST_INT:
		case DATAFLOW_CONST_FLOAT:
      case DATAFLOW_CONST_SAMPLER:
#ifdef __VIDEOCORE4__
#ifdef __BCM2708A0__
      case DATAFLOW_INDEXED_UNIFORM_SAMPLER:
#else
      case DATAFLOW_UNIFORM_ADDRESS:
#endif
#endif
			break;

		case DATAFLOW_UNIFORM:
		case DATAFLOW_ATTRIBUTE:
		case DATAFLOW_VARYING:
         break;

      case DATAFLOW_UNIFORM_OFFSET:
         if (cross == (dataflow->line_num != dataflow->u.linkable_value_offset.linkable_value->line_num))
			{
				print_edge(f, EDGE_SOLID, dataflow->u.linkable_value_offset.linkable_value, dataflow);
			}
         if (cross == (dataflow->line_num != dataflow->u.linkable_value_offset.offset->line_num))
			{
				print_edge(f, EDGE_SOLID, dataflow->u.linkable_value_offset.offset, dataflow);
			}
			break;

		case DATAFLOW_ARITH_NEGATE:
		case DATAFLOW_LOGICAL_NOT:
      case DATAFLOW_INTRINSIC_FLOATTOINT_TRUNC:
      case DATAFLOW_INTRINSIC_FLOATTOINT_NEAREST:
      case DATAFLOW_INTRINSIC_FLOATTOBOOL:
      case DATAFLOW_INTRINSIC_INTTOFLOAT:
      case DATAFLOW_INTRINSIC_INTTOBOOL:
      case DATAFLOW_INTRINSIC_BOOLTOINT:
      case DATAFLOW_INTRINSIC_BOOLTOFLOAT:
		case DATAFLOW_INTRINSIC_RSQRT:
		case DATAFLOW_INTRINSIC_RCP:
		case DATAFLOW_INTRINSIC_LOG2:
		case DATAFLOW_INTRINSIC_EXP2:
      case DATAFLOW_INTRINSIC_CEIL:
      case DATAFLOW_INTRINSIC_FLOOR:
      case DATAFLOW_INTRINSIC_SIGN:
      case DATAFLOW_MOV:
      case DATAFLOW_COERCE_TOFLOAT:
      case DATAFLOW_COERCE_TOINT:
#ifdef __VIDEOCORE4__
      case DATAFLOW_UNPACK_COL_R:
      case DATAFLOW_UNPACK_COL_G:
      case DATAFLOW_UNPACK_COL_B:
      case DATAFLOW_UNPACK_COL_A:
      case DATAFLOW_UNPACK_16A:
      case DATAFLOW_UNPACK_16A_F:
      case DATAFLOW_UNPACK_16B:
      case DATAFLOW_UNPACK_16B_F:
      case DATAFLOW_UNPACK_8A:
      case DATAFLOW_UNPACK_8B:
      case DATAFLOW_UNPACK_8C:
      case DATAFLOW_UNPACK_8D:
      case DATAFLOW_UNPACK_8R:
      case DATAFLOW_UNPACK_FB_R:
      case DATAFLOW_UNPACK_FB_B:
#endif
         if (cross == (dataflow->line_num != dataflow->u.unary_op.operand->line_num))
			{
				print_edge(f, EDGE_SOLID, dataflow->u.unary_op.operand, dataflow);
			}
			break;

		case DATAFLOW_MUL:
		case DATAFLOW_ADD:
		case DATAFLOW_SUB:
		case DATAFLOW_RSUB:
		case DATAFLOW_LESS_THAN:
		case DATAFLOW_LESS_THAN_EQUAL:
		case DATAFLOW_GREATER_THAN:
		case DATAFLOW_GREATER_THAN_EQUAL:
		case DATAFLOW_EQUAL:
		case DATAFLOW_NOT_EQUAL:
		case DATAFLOW_LOGICAL_AND:
		case DATAFLOW_LOGICAL_XOR:
		case DATAFLOW_LOGICAL_OR:
		case DATAFLOW_INTRINSIC_MIN:
		case DATAFLOW_INTRINSIC_MAX:
#ifdef __VIDEOCORE4__
      case DATAFLOW_BITWISE_NOT:
      case DATAFLOW_BITWISE_AND:
      case DATAFLOW_BITWISE_OR:
      case DATAFLOW_BITWISE_XOR:
      case DATAFLOW_V8MULD:
      case DATAFLOW_V8MIN:
      case DATAFLOW_V8MAX:
      case DATAFLOW_V8ADDS:
      case DATAFLOW_V8SUBS:
      case DATAFLOW_INTEGER_ADD:
      case DATAFLOW_SHIFT_RIGHT:
      case DATAFLOW_LOGICAL_SHR:
#endif
         if (cross == (dataflow->line_num != dataflow->u.binary_op.left->line_num))
			{
				print_edge(f, EDGE_SOLID, dataflow->u.binary_op.left, dataflow);
			}
         if (cross == (dataflow->line_num != dataflow->u.binary_op.right->line_num))
			{
				print_edge(f, EDGE_SOLID, dataflow->u.binary_op.right, dataflow);
			}
			break;

#ifdef __VIDEOCORE4__
      case DATAFLOW_PACK_COL_R:
      case DATAFLOW_PACK_COL_G:
      case DATAFLOW_PACK_COL_B:
      case DATAFLOW_PACK_COL_A:
      case DATAFLOW_PACK_16A:
      case DATAFLOW_PACK_16B:
      case DATAFLOW_PACK_FB_R:
      case DATAFLOW_PACK_FB_B:
         if (cross == (dataflow->line_num != dataflow->u.pack.operand->line_num))
			{
				print_edge(f, EDGE_SOLID, dataflow->u.pack.operand, dataflow);
			}
         if (cross == (dataflow->line_num != dataflow->u.pack.background->line_num))
			{
				print_edge(f, EDGE_SOLID, dataflow->u.pack.background, dataflow);
			}
			break;
#endif
		case DATAFLOW_CONDITIONAL:
         if (cross == (dataflow->line_num != dataflow->u.cond_op.cond->line_num))
			{
				print_edge(f, EDGE_SOLID, dataflow->u.cond_op.cond, dataflow);
			}
         if (cross == (dataflow->line_num != dataflow->u.cond_op.true_value->line_num))
			{
				print_edge(f, EDGE_SOLID, dataflow->u.cond_op.true_value, dataflow);
			}
         if (cross == (dataflow->line_num != dataflow->u.cond_op.false_value->line_num))
			{
				print_edge(f, EDGE_SOLID, dataflow->u.cond_op.false_value, dataflow);
			}
			break;

		case DATAFLOW_TEX_SET_COORD_S:
		case DATAFLOW_TEX_SET_COORD_T:
		case DATAFLOW_TEX_SET_COORD_R:
      case DATAFLOW_TEX_SET_BIAS:
		case DATAFLOW_TEX_SET_LOD:
#ifdef __VIDEOCORE4__
#ifndef __BCM2708A0__
      case DATAFLOW_TEX_SET_DIRECT:
#endif
#endif
         if (cross == (dataflow->line_num != dataflow->u.texture_lookup_set.sampler->line_num))
			{
				print_edge(f, EDGE_SOLID, dataflow->u.texture_lookup_set.sampler, dataflow);
			}
         if (cross == (dataflow->line_num != dataflow->u.texture_lookup_set.param->line_num))
			{
				print_edge(f, EDGE_SOLID, dataflow->u.texture_lookup_set.param, dataflow);
			}
			break;

		case DATAFLOW_TEX_GET_CMP_R:
		case DATAFLOW_TEX_GET_CMP_G:
		case DATAFLOW_TEX_GET_CMP_B:
		case DATAFLOW_TEX_GET_CMP_A:
         if (cross == (dataflow->line_num != dataflow->u.texture_lookup_get.sampler->line_num))
			{
				print_edge(f, EDGE_SOLID, dataflow->u.texture_lookup_get.sampler, dataflow);
			}
			break;

      case DATAFLOW_THREADSWITCH:
      case DATAFLOW_FRAG_GET_X:
      case DATAFLOW_FRAG_GET_Y:
      case DATAFLOW_FRAG_GET_Z:
      case DATAFLOW_FRAG_GET_W:
      case DATAFLOW_FRAG_GET_PC_X:
      case DATAFLOW_FRAG_GET_PC_Y:
      case DATAFLOW_FRAG_GET_FF:
#ifdef __VIDEOCORE4__
      case DATAFLOW_VARYING_C:
      case DATAFLOW_FRAG_GET_COL:
      case DATAFLOW_SCOREBOARD_WAIT:
#endif
         break;

		case DATAFLOW_FRAG_SET_R:
		case DATAFLOW_FRAG_SET_G:
		case DATAFLOW_FRAG_SET_B:
		case DATAFLOW_FRAG_SET_A:
#ifdef __VIDEOCORE4__
      case DATAFLOW_FRAG_SUBMIT_STENCIL:
      case DATAFLOW_FRAG_SUBMIT_Z:
      case DATAFLOW_FRAG_SUBMIT_MS:
      case DATAFLOW_FRAG_SUBMIT_ALL:
      case DATAFLOW_FRAG_SUBMIT_R0:
      case DATAFLOW_FRAG_SUBMIT_R1:
      case DATAFLOW_FRAG_SUBMIT_R2:
      case DATAFLOW_FRAG_SUBMIT_R3:
      case DATAFLOW_TMU_SWAP:
      case DATAFLOW_VERTEX_SET:
      case DATAFLOW_VPM_READ_SETUP:
      case DATAFLOW_VPM_WRITE_SETUP:
#endif
         if (cross == (dataflow->line_num != dataflow->u.fragment_set.param->line_num))
			{
				print_edge(f, EDGE_SOLID, dataflow->u.fragment_set.param, dataflow);
			}
         if (dataflow->u.fragment_set.discard && cross == (dataflow->line_num != dataflow->u.fragment_set.discard->line_num))
			{
				print_edge(f, EDGE_SOLID, dataflow->u.fragment_set.discard, dataflow);
			}
			break;

		default:
			UNREACHABLE();
			break;
	}

   for (node = dataflow->iodependencies.first; node; node = node->next)
   {
      if (cross == (dataflow->line_num != node->dataflow->line_num))
		{
         // Dependency: dashed line.
			print_edge(f, EDGE_DASHED, node->dataflow, dataflow);
		}
   }
}

static void print_node(FILE* f, Dataflow* dataflow)
{
   // Print node reference and open label string.
   fprintf(f, "\tn%x [label=\"", (size_t)dataflow);

   // Print contents of label string.
   switch (dataflow->flavour)
	{
		case DATAFLOW_CONST_BOOL:
         fprintf(f, dataflow->u.const_bool.value ? "true" : "false");
         break;

		case DATAFLOW_CONST_INT:
         fprintf(f, "%d", dataflow->u.const_int.value);
         break;

		case DATAFLOW_CONST_FLOAT:
			fprintf(f, "%f", *(float*)&dataflow->u.const_float.value);
			break;

      case DATAFLOW_CONST_SAMPLER:
         fprintf(f, "sampler[%d] from <%s>", dataflow->u.const_sampler.location, dataflow->u.const_sampler.name);
         break;

		case DATAFLOW_UNIFORM:
         fprintf(f, "uniform[%d] from <%s>", dataflow->u.linkable_value.row, dataflow->u.linkable_value.name);
         break;
		case DATAFLOW_ATTRIBUTE:
         fprintf(f, "attribute[%d] from <%s>", dataflow->u.linkable_value.row, dataflow->u.linkable_value.name);
         break;
		case DATAFLOW_VARYING:
         fprintf(f, "varying[%d] from <%s>", dataflow->u.linkable_value.row, dataflow->u.linkable_value.name);
         break;

      case DATAFLOW_UNIFORM_OFFSET:
         fprintf(f, "uniform offset");
         break;

		case DATAFLOW_ARITH_NEGATE:
         fprintf(f, "-");
         break;
		case DATAFLOW_LOGICAL_NOT:
         fprintf(f, "!");
         break;
      case DATAFLOW_INTRINSIC_FLOATTOINT_TRUNC:
         fprintf(f, "trunc");
         break;
      case DATAFLOW_INTRINSIC_FLOATTOINT_NEAREST:
         fprintf(f, "nearest");
         break;
      case DATAFLOW_INTRINSIC_FLOATTOBOOL:
         fprintf(f, "ftob");
         break;
      case DATAFLOW_INTRINSIC_INTTOFLOAT:
         fprintf(f, "itof");
         break;
      case DATAFLOW_INTRINSIC_INTTOBOOL:
         fprintf(f, "itob");
         break;
      case DATAFLOW_INTRINSIC_BOOLTOINT:
         fprintf(f, "btoi");
         break;
      case DATAFLOW_INTRINSIC_BOOLTOFLOAT:
         fprintf(f, "btof");
         break;
		case DATAFLOW_INTRINSIC_RSQRT:
         fprintf(f, "rsqrt");
         break;
      case DATAFLOW_INTRINSIC_CEIL:
         fprintf(f, "ceil");
         break;
      case DATAFLOW_INTRINSIC_FLOOR:
         fprintf(f, "floor");
         break;
      case DATAFLOW_INTRINSIC_SIGN:
         fprintf(f, "sign");
         break;
		case DATAFLOW_INTRINSIC_RCP:
         fprintf(f, "rcp");
         break;
		case DATAFLOW_INTRINSIC_LOG2:
         fprintf(f, "log2");
         break;
		case DATAFLOW_INTRINSIC_EXP2:
         fprintf(f, "exp2");
         break;

      case DATAFLOW_MOV:
         fprintf(f, "mov");
         break;

      case DATAFLOW_COERCE_TOFLOAT:
         fprintf(f, "tof");
         break;
      case DATAFLOW_COERCE_TOINT:
         fprintf(f, "toi");
         break;

		case DATAFLOW_MUL:
         fprintf(f, "*");
         break;
		case DATAFLOW_ADD:
         fprintf(f, "+");
         break;
		case DATAFLOW_SUB:
		case DATAFLOW_RSUB:
         fprintf(f, "-");
         break;
		case DATAFLOW_LESS_THAN:
         fprintf(f, "<");
         break;
		case DATAFLOW_LESS_THAN_EQUAL:
         fprintf(f, "<=");
         break;
		case DATAFLOW_GREATER_THAN:
         fprintf(f, ">");
         break;
		case DATAFLOW_GREATER_THAN_EQUAL:
         fprintf(f, ">=");
         break;
		case DATAFLOW_EQUAL:
         fprintf(f, "==");
         break;
		case DATAFLOW_NOT_EQUAL:
         fprintf(f, "!=");
         break;
		case DATAFLOW_LOGICAL_AND:
         fprintf(f, "&&");
         break;
		case DATAFLOW_LOGICAL_XOR:
         fprintf(f, "^^");
         break;
		case DATAFLOW_LOGICAL_OR:
         fprintf(f, "||");
         break;
		case DATAFLOW_INTRINSIC_MIN:
         fprintf(f, "min");
         break;
		case DATAFLOW_INTRINSIC_MAX:
         fprintf(f, "max");
         break;

		case DATAFLOW_CONDITIONAL:
         fprintf(f, "cond");
         break;

      case DATAFLOW_THREADSWITCH:
         fprintf(f, "thrsw");
         break;

		case DATAFLOW_TEX_SET_COORD_S:
         fprintf(f, "set coord s");
         break;
		case DATAFLOW_TEX_SET_COORD_T:
         fprintf(f, "set coord t");
         break;
		case DATAFLOW_TEX_SET_COORD_R:
         fprintf(f, "set coord r");
         break;
		case DATAFLOW_TEX_SET_BIAS:
         fprintf(f, "set bias");
         break;
		case DATAFLOW_TEX_SET_LOD:
         fprintf(f, "set lod");
         break;

		case DATAFLOW_TEX_GET_CMP_R:
         fprintf(f, "get cmp r");
         break;
		case DATAFLOW_TEX_GET_CMP_G:
         fprintf(f, "get cmp g");
         break;
		case DATAFLOW_TEX_GET_CMP_B:
         fprintf(f, "get cmp b");
         break;
		case DATAFLOW_TEX_GET_CMP_A:
         fprintf(f, "get cmp a");
         break;

		case DATAFLOW_FRAG_GET_X:
         fprintf(f, "get frag x");
         break;
		case DATAFLOW_FRAG_GET_Y:
         fprintf(f, "get frag y");
         break;
		case DATAFLOW_FRAG_GET_Z:
         fprintf(f, "get frag z");
         break;
		case DATAFLOW_FRAG_GET_W:
         fprintf(f, "get frag w");
         break;
		case DATAFLOW_FRAG_GET_PC_X:
         fprintf(f, "get frag pc x");
         break;
		case DATAFLOW_FRAG_GET_PC_Y:
         fprintf(f, "get frag pc y");
         break;
		case DATAFLOW_FRAG_GET_FF:
         fprintf(f, "get frag ff");
         break;

		case DATAFLOW_FRAG_SET_R:
         fprintf(f, "set frag r");
         break;
		case DATAFLOW_FRAG_SET_G:
         fprintf(f, "set frag g");
         break;
		case DATAFLOW_FRAG_SET_B:
         fprintf(f, "set frag b");
         break;
		case DATAFLOW_FRAG_SET_A:
         fprintf(f, "set frag a");
         break;

#ifdef __VIDEOCORE4__
   case DATAFLOW_BITWISE_NOT:
      fprintf(f, "~");
      break;
   case DATAFLOW_BITWISE_AND:
      fprintf(f, "&");
      break;
   case DATAFLOW_BITWISE_OR:
      fprintf(f, "|");
      break;
   case DATAFLOW_BITWISE_XOR:
      fprintf(f, "^");
      break;
   case DATAFLOW_V8MULD:
      fprintf(f, "v8 *");
      break;
   case DATAFLOW_V8MIN:
      fprintf(f, "v8 min");
      break;
   case DATAFLOW_V8MAX:
      fprintf(f, "v8 max");
      break;
   case DATAFLOW_V8ADDS:
      fprintf(f, "v8 +");
      break;
   case DATAFLOW_V8SUBS:
      fprintf(f, "v8 -");
      break;
   case DATAFLOW_INTEGER_ADD:
      fprintf(f, "int +");
      break;
   case DATAFLOW_VARYING_C:
      fprintf(f, "vary c");
      break;
   case DATAFLOW_FRAG_GET_COL:
      fprintf(f, "get frag col");
      break;
   case DATAFLOW_FRAG_SUBMIT_STENCIL:
      fprintf(f, "set frag stencil");
      break;
   case DATAFLOW_FRAG_SUBMIT_Z:
      fprintf(f, "set frag z");
      break;
   case DATAFLOW_FRAG_SUBMIT_MS:
      fprintf(f, "set frag ms");
      break;
   case DATAFLOW_FRAG_SUBMIT_ALL:
      fprintf(f, "set frag all");
      break;
   case DATAFLOW_FRAG_SUBMIT_R0:
      fprintf(f, "set r0");
      break;
   case DATAFLOW_FRAG_SUBMIT_R1:
      fprintf(f, "set r1");
      break;
   case DATAFLOW_FRAG_SUBMIT_R2:
      fprintf(f, "set r2");
      break;
   case DATAFLOW_FRAG_SUBMIT_R3:
      fprintf(f, "set r3");
      break;
   case DATAFLOW_TMU_SWAP:
      fprintf(f, "set tmu swap");
      break;
#ifndef __BCM2708A0__
   case DATAFLOW_TEX_SET_DIRECT:
      fprintf(f, "set direct lookup");
      break;
#endif
   case DATAFLOW_VERTEX_SET:
      fprintf(f, "set vertex data");
      break;
   case DATAFLOW_VPM_READ_SETUP:
      fprintf(f, "set vpm read setup");
      break;
   case DATAFLOW_VPM_WRITE_SETUP:
      fprintf(f, "set vpm write setup");
      break;
   case DATAFLOW_PACK_COL_R:
      fprintf(f, "pack col r");
      break;
   case DATAFLOW_PACK_COL_G:
      fprintf(f, "pack col g");
      break;
   case DATAFLOW_PACK_COL_B:
      fprintf(f, "pack col b");
      break;
   case DATAFLOW_PACK_COL_A:
      fprintf(f, "pack col a");
      break;
   case DATAFLOW_PACK_16A:
      fprintf(f, "pack 16a");
      break;
   case DATAFLOW_PACK_16B:
      fprintf(f, "pack 16b");
      break;
   case DATAFLOW_PACK_FB_R:
      fprintf(f, "pack col (r)");
      break;
   case DATAFLOW_PACK_FB_B:
      fprintf(f, "pack col (b)");
      break;
   case DATAFLOW_UNPACK_COL_R:
      fprintf(f, "unpack col r");
      break;
   case DATAFLOW_UNPACK_COL_G:
      fprintf(f, "unpack col g");
      break;
   case DATAFLOW_UNPACK_COL_B:
      fprintf(f, "unpack col b");
      break;
   case DATAFLOW_UNPACK_COL_A:
      fprintf(f, "unpack col a");
      break;
   case DATAFLOW_UNPACK_16A:
      fprintf(f, "unpack 16a");
      break;
   case DATAFLOW_UNPACK_16A_F:
      fprintf(f, "unpack 16a float");
      break;
   case DATAFLOW_UNPACK_16B:
      fprintf(f, "unpack 16b");
      break;
   case DATAFLOW_UNPACK_16B_F:
      fprintf(f, "unpack 16b float");
      break;
   case DATAFLOW_UNPACK_8A:
      fprintf(f, "unpack 8a");
      break;
   case DATAFLOW_UNPACK_8B:
      fprintf(f, "unpack 8b");
      break;
   case DATAFLOW_UNPACK_8C:
      fprintf(f, "unpack 8c");
      break;
   case DATAFLOW_UNPACK_8D:
      fprintf(f, "unpack 8d");
      break;
   case DATAFLOW_UNPACK_8R:
      fprintf(f, "unpack 8r");
      break;
   case DATAFLOW_UNPACK_FB_R:
      fprintf(f, "unpack col (r)");
      break;
   case DATAFLOW_UNPACK_FB_B:
      fprintf(f, "unpack col (g)");
      break;
   case DATAFLOW_SHIFT_RIGHT:
      fprintf(f, ">>");
      break;
   case DATAFLOW_LOGICAL_SHR:
      fprintf(f, "logical >>");
      break;
#ifdef __BCM2708A0__
   case DATAFLOW_INDEXED_UNIFORM_SAMPLER:
      fprintf(f, "sampler from indexed uniform");
      break;
#else
   case DATAFLOW_UNIFORM_ADDRESS:
      fprintf(f, "uniform address");
      break;
#endif
   case DATAFLOW_SCOREBOARD_WAIT:
      fprintf(f, "sbwait");
      break;
#endif

		default:
			UNREACHABLE();
			return;
	}

   // Append type.
   {
      const char* type = NULL;

      switch (dataflow->type_index)
      {
         case PRIM_BOOL:
         case PRIM_INT:
         case PRIM_FLOAT:
         case PRIM_VOID:
         case PRIM_SAMPLER2D:
         case PRIM_SAMPLERCUBE:
            type = primitiveTypes[dataflow->type_index].name;
            break;

         default:
            UNREACHABLE();
            return;
      }

      fprintf(f, " : %s", type);
   }

   if (dataflow->slot == -1)
      fprintf(f, " -> ?");
   else
      if (dataflow->slot & DATAFLOW_SLOT_VRF)
         fprintf(f, " -> v%d", dataflow->slot & DATAFLOW_SLOT_MASK);
      else
         fprintf(f, " -> s%d", dataflow->slot);

   fprintf(f, " (%d)\"", dataflow->delay);

   switch (dataflow->phase)
   {
   case BACKEND_PASS_AWAITING_SCHEDULE:
      fprintf(f, " style=\"filled\" fillcolor=\"#ffff80\"");
      break;
   case BACKEND_PASS_SCHEDULED:
      fprintf(f, " style=\"filled\" fillcolor=\"#ff8080\"");
      break;
   case BACKEND_PASS_DIVING:
      fprintf(f, " style=\"filled\" fillcolor=\"#8080ff\"");
      break;
   }

   // Close label string.
   fprintf(f, "];\n");
}

// map must map a line number to a DataflowChain, containing all Dataflow nodes for that line.
// Outputs graphviz dot representation of these nodes,
// clustering by line number.
static void print_dataflow_from_map(FILE* f, Map* map)
{
	DataflowChain* chain;
	DataflowChainNode* node;

   // For all line numbers...
	while ((chain = (DataflowChain *)glsl_map_pop(map)) != NULL)
	{
      int line_num;

      vcos_assert(chain->first);
      line_num = chain->first->dataflow->line_num;

      // Open cluster if we have a valid line number to group by.
      if (LINE_NUMBER_UNDEFINED != line_num)
      {
//         fprintf(f, "\tsubgraph cluster_" GRAPHVIZ_CLUSTER_PREFIX "_%d\n", line_num);
         fprintf(f, "\t{\n");
         fprintf(f, "\tlabel=\"line %d\";\n", line_num);
		   fprintf(f, "\tstyle=filled;\n");
		   fprintf(f, "\tfillcolor=\"0 0 .9\";\n");
      }

      // For all nodes...
		for (node = chain->first; node; node = node->next)
		{
         // Declare node.
         print_node(f, node->dataflow);

         // Add all the edges that don't cross a cluster boundary.
         print_edges(f, node->dataflow, false);
		}

      // Close cluster.
      if (LINE_NUMBER_UNDEFINED != line_num)
      {
         fprintf(f, "\t}\n");
      }

      // For all nodes...
		for (node = chain->first; node; node = node->next)
		{
         // Add remaining edges.
         print_edges(f, node->dataflow, true);
		}
	}
}

void glsl_print_dataflow_from_root(FILE* f, Dataflow* root, int pass)
{
   Map* map;

   // Initialize map with key comparator.
   map = glsl_map_new();

   // Gather nodes into map.
   glsl_dataflow_accept_towards_leaves(root, map, NULL, dpostv_gather_by_line_num, pass);

	// Print opening.
	fprintf(f, "digraph " GRAPHVIZ_GRAPH_NAME "\n");
   fprintf(f, "{\n");

   // Print map.
   print_dataflow_from_map(f, map);

	// Print closing.
	fprintf(f, "}\n");
}

void glsl_print_dataflow_from_roots(FILE* f, DataflowChain* roots, DataflowChain *order, int pass)
{
   Map* map;
   DataflowChainNode *node;

   // Initialize map with key comparator.
   map = glsl_map_new();

   // Gather nodes into map.
   for (node = roots->first; node; node = node->next)
   {
      Dataflow* root = node->dataflow;
      glsl_dataflow_accept_towards_leaves(root, map, NULL, dpostv_gather_by_line_num, pass);
   }

	// Print opening.
	fprintf(f, "digraph " GRAPHVIZ_GRAPH_NAME "\n");
   fprintf(f, "{\n");

   // Print map.
   print_dataflow_from_map(f, map);

   // Print ordering edges (typically from scheduler)
   if (order)
      for (node = order->first; node; node = node->next)
         if (node->next)
            print_edge(f, EDGE_SEQUENCE, node->dataflow, node->next->dataflow);

	// Print closing.
	fprintf(f, "}\n");
}
#else
/*
   keep Metaware happy by providing an exported symbol
*/

void glsl_print_dataflow_from_roots(FILE* f, DataflowChain* roots, DataflowChain *order, int pass)
{
   UNUSED(f);
   UNUSED(roots);
   UNUSED(order);
   UNUSED(pass);
}
#endif // _DEBUG