text:
<?php
/**
 * Twitter API Wordpress library.
 * @author Tim Whitlock <@timwhitlock>
 */

global $GLTW_API;

class GLTW_API {
	public static $clients = array();

	function __construct() {
	}

	/**
	 * Call a Twitter API GET method.
	 *
	 * @param string endpoint/method, e.g. "users/show"
	 * @param array Request arguments, e.g. array( 'screen_name' => 'timwhitlock' )
	 * @return array raw, deserialised data from Twitter
	 * @throws TwitterApiException
	 */
	public static function api_get( $path, array $args = array() ){
gltw_log();
	    $Client = GLTW_API::api_client();
	    return $Client->call( $path, $args, 'GET' );
	}

	/**
	 * Call a Twitter API POST method.
	 *
	 * @param string endpoint/method, e.g. "users/show"
	 * @param array Request arguments, e.g. array( 'screen_name' => 'timwhitlock' )
	 * @return array raw, deserialised data from Twitter
	 * @throws TwitterApiException
	 */
	public static function api_post( $path, array $args = array() ){
gltw_log();
	    $Client = GLTW_API::api_client();
	    return $Client->call( $path, $args, 'POST' );
	}

	/**
	 * Enable caching of Twitter API responses using APC
	 * @param int Cache lifetime in seconds
	 * @return TwitterApiClient
	 */
	public static function api_enable_cache( $ttl ){
gltw_log();
	    $Client = GLTW_API::api_client();
	    return $Client->enable_cache( $ttl );
	}

	/**
	 * Disable caching of Twitter API responses
	 * @return TwitterApiClient
	 */
	public static function api_disable_cache( $ttl ){
gltw_log();
	    $Client = GLTW_API::api_client();
	    return $Client->disable_cache();
	}

	/**
	 * Get plugin local base directory in case __DIR__ isn't available (php<5.3)
	 */
	public static function api_basedir(){
gltw_log();
	    static $dir;
	    isset($dir) or $dir = dirname(__FILE__).'/..';
	    return $dir;
	}

	/**
	 * Get fully configured and authenticated Twitter API client.
	 * @return TwitterApiClient
	 */
	public static function api_client( $id = null ){
gltw_log();
	    if( ! isset($clients[$id]) ){
	        $clients[$id] = TwitterApiClient::create_instance( is_null($id) );
	    }
	    return $clients[$id];
	}

	/**
	 * Contact Twitter for a request token, which will be exchanged for an access token later.
	 * @return TwitterOAuthToken Request token
	 */
	public static function api_oauth_request_token( $consumer_key, $consumer_secret, $oauth_callback = 'oob' ){
gltw_log();
gltw_pr( 'method params', $consumer_key, $consumer_secret, $oauth_callback );
	    $Client = GLTW_API::api_client('oauth');
gltw_pr( $Client );
	    $Client->set_oauth( $consumer_key, $consumer_secret );
gltw_pr( $Client );
	    $params = $Client->oauth_exchange( OAUTH_REQUEST_TOKEN_URL, compact('oauth_callback') );
gltw_pr( $params );
	    return new TwitterOAuthToken( $params['oauth_token'], $params['oauth_token_secret'] );
	}

	/**
	 * Exchange request token for an access token after authentication/authorization by user
	 * @return TwitterOAuthToken Access token
	 */
	public static function api_oauth_access_token( $consumer_key, $consumer_secret, $request_key, $request_secret, $oauth_verifier ){
gltw_log();
	    $Client = GLTW_API::api_client('oauth');
	    $Client->set_oauth( $consumer_key, $consumer_secret, $request_key, $request_secret );
	    $params = $Client->oauth_exchange( OAUTH_ACCESS_TOKEN_URL, compact('oauth_verifier') );
	    return new TwitterOAuthToken( $params['oauth_token'], $params['oauth_token_secret'] );
	}

}

// Instantiate Class
$GLTW_API = new GLTW_API();

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#include "envoy/server/transport_socket_config.h"

namespace Envoy {
namespace Extensions {
namespace TransportSockets {
namespace Http11Connect {

/**
 * Config registration for the upstream HTTP/1.1 proxy transport socket factory.
 * @see TransportSocketConfigFactory.
 */
class UpstreamHttp11ConnectSocketConfigFactory
    : public Server::Configuration::UpstreamTransportSocketConfigFactory {
public:
  std::string name() const override { return "envoy.transport_sockets.http_11_proxy"; }
  ProtobufTypes::MessagePtr createEmptyConfigProto() override;
  Network::UpstreamTransportSocketFactoryPtr createTransportSocketFactory(
      const Protobuf::Message& config,
      Server::Configuration::TransportSocketFactoryContext& context) override;
};

DECLARE_FACTORY(UpstreamHttp11ConnectSocketConfigFactory);

} // namespace Http11Connect
} // namespace TransportSockets
} // namespace Extensions
} // namespace Envoy


text:
#ifndef _TM_MACROS_H_
# define _TM_MACROS_H_

# define TM_START(id,ro)                    __transaction_atomic {
# define TM_LOAD(x)                         *x
# define TM_STORE(x,y)                      *x=y
# define TM_COMMIT                          }
# define TM_MALLOC(size)                    malloc(size)
// TODO is it possible to do TM_FREE(addr ...)  free(addr) ? //__VA_ARGS__
# define TM_FREE(addr)                      free(addr)
# define TM_FREE2(addr, size)               free(addr)

# define TM_INIT
# define TM_EXIT
# define TM_INIT_THREAD
# define TM_EXIT_THREAD

/* Define Annotations */
# define TM_PURE                            __attribute__((transaction_pure))
# define TM_SAFE                            __attribute__((transaction_safe))

#endif /* _TM_MACROS_H_ */


text: select fn_db_change_column_type('vm_device', 'device', 'VARCHAR', 'VARCHAR(255)');


text:
HDFS Browser

            /

            Type
            Name
            Size
            Owner
            Group
            Permission

File Info

File Contents

Text

Binary

Schema

First Block

Previous Block

Next Block

Last Block

              Viewing Bytes:
              <input type="text" name="begin" value="1" size="8" class="form-control input-sm">
               -
              <input type="text" name="end" value="215" size="8" class="form-control input-sm"> of
              292 (4096 B block size)

Text Content

First Block

Previous Block

Next Block

Last Block

                Viewing Bytes:
                <input type="text" name="begin" value="1" size="8" class="form-control input-sm">
                 -
                <input type="text" name="end" value="215" size="8" class="form-control input-sm"> of
                292 (4096B block size)

Binary Content

Avro schema goes here


text:
module MultilineLiteralBraceHelper
  # Construct the source code for the braces. For instance, for an array
  # the `open` brace would be `[` and the `close` brace would be `]`, so
  # you could construct the following:
  #
  #     braces(true, 'a', 'b', 'c', false)
  #
  #     [ # line break indicated by `true` as the first argument.
  #     a,
  #     b,
  #     c] # no line break indicated by `false` as the last argument.
  #
  # This method also supports multi-line arguments. For example:
  #
  #     braces(true, 'a', ['{', 'foo: bar', '}'], true)
  #
  #     [ # line break indicated by `true` as the first argument.
  #     a,
  #     {
  #     foo: bar
  #     } # line break indicated by `true` as the last argument.
  #     ]
  def braces(open_line_break, *args, close_line_break)
    args = default_args if args.empty?

    open + (open_line_break ? "\n" : '') +
      args.map { |a| a.respond_to?(:join) ? a.join("\n") : a }.join(",\n") +
      (close_line_break ? "\n" : '') + close
  end

  def default_args
    [a, b + b_comment]
  end

  # Construct a piece of source code for brace layout testing. This farms
  # out most of the work to `#braces` but it also includes a prefix and suffix.
  def construct(*args)
    "#{prefix}#{braces(*args)}\n#{suffix}"
  end
end


text:
categories:
- tumblr
- archive
- quote
date: 2007-08-30T01:31:38Z
title: Quote 20070830
url: /2007/08/30/quote-20070830/
---

Pere Ubu is mainstream rock. Justin Timberlake is weird experimental music. Robbie Williams is avant-garde. Britney Spears is constantly coming up with something new and innovative. Pere Ubu does the same old thing. 'New' is a trap and a scam to dupe student-types and other naive people.
David Thomas, Pere Ubu


text:
package com.jpattern.service.mail;

import java.util.Date;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author Francesco Cina
 *
 * 29/giu/2011
 */
public abstract class AMailSender implements IMailSender {

	private MailRecipients _recipients;

	@Override
	public void recipients(MailRecipients aRecipients) {
	    _recipients = aRecipients;
	}

	@Override
	public boolean send(TransportMailMessage aMessage) {
	    try {

	    	Session session = getSession();
	        MimeMessage mimeMessage = new MimeMessage(session);
	        mimeMessage.setSubject(aMessage.subject().content());
	        mimeMessage.setSentDate(new Date());

	        MailMessageAddress mailMessageAddress = new MailMessageAddress(mimeMessage);
	        _recipients.writeOnMessage(mailMessageAddress);

	        if (!mailMessageAddress.valid()) {
	            return false;
	        }
	        mimeMessage.setContent(aMessage.asMultipart());

	        Transport.send(mimeMessage);

	        return true;
	    }
	    catch (Exception e) {
	    	e.printStackTrace();
	    	return false;
	    }
	}

	protected abstract Session getSession();
}


text:
import React from 'react';
import { Button, Input, Form } from 'antd';
import { FormattedMessage } from 'react-intl';
import styles from './Start.less';

const FormItem = Form.Item;

function Start({ dispatch, form, loading, intl }) {
  const { getFieldDecorator, validateFields } = form;
  const onSubmit = () => {
    validateFields(['url'], { force: true }, (err, values) => {
      if (!err) {
        dispatch({
          type: 'contribute/validateRepo',
          payload: values.url,
          intl,
        });
      }
    });
  };
  return (
    <Form className={styles.form}>
      <h3 className={styles.title}>
        <FormattedMessage id="submit.title" />
      </h3>
      <FormItem>
        {getFieldDecorator('url', {
          rules: [{
            type: 'string',
            required: true,
            pattern: /^https?:\/\/(www\.)?github\.com\/([\w-]+)\/([\w-]+)\/?/,
            message: intl.formatMessage({ id: 'submit.repo.error' }),
          }],
        })(
          <Input
            className={styles.input}
            autoComplete="off"
            placeholder={intl.formatMessage({ id: 'submit.repo.placeholder' })}
          />,
        )}
      </FormItem>
      <FormItem style={{ marginTop: 60 }}>
        <Button
          type="primary"
          size="large"
          loading={loading.models.contribute}
          onClick={onSubmit}
        >
          <FormattedMessage id="submit.next" />
        </Button>
      </FormItem>
    </Form>
  );
}

export default Form.create()(Start);


text:
license: 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.
---

# notification.confirm

顯示一個可自訂的確認對話方塊。

    navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])

*   **消息**: 消息對話方塊。*(字串)*

*   **confirmCallback**: 要用索引 (1、 2 或 3) 按下的按鈕,或者在沒有按下按鈕 (0) 駁回了對話方塊中時調用的回檔。*(函數)*

*   **標題**: 標題對話方塊。*(字串)*(可選,預設值為`Confirm`)

*   **buttonLabels**: 指定按鈕標籤的字串陣列。*(陣列)*(可選,預設值為 [ `OK,Cancel` ])

## 說明

`notification.confirm`方法顯示一個本機的對話方塊,更可自訂的瀏覽器比 `confirm` 函數。

## confirmCallback

`confirmCallback`當使用者按下確認對話方塊中的按鈕之一的時候執行。

回檔將參數 `buttonIndex` *(編號)*,它是按下的按鈕的索引。 請注意索引使用基於 1 的索引,所以值是 `1` , `2` , `3` ,等等。

## 支援的平臺

*   Android 系統
*   黑莓手機 WebWorks (OS 5.0 和更高)
*   iOS
*   Tizen
*   Windows Phone 7 和 8
*   Windows 8

## 快速的示例

    // process the confirmation dialog result
    function onConfirm(buttonIndex) {
        alert('You selected button ' + buttonIndex);
    }

    // Show a custom confirmation dialog
    //
    function showConfirm() {
        navigator.notification.confirm(
            'You are the winner!', // message
             onConfirm,            // callback to invoke with index of button pressed
            'Game Over',           // title
            ['Restart','Exit']         // buttonLabels
        );
    }

## 完整的示例

    <!DOCTYPE html>

        <title>Notification Example</title>

Show Confirm

## Windows Phone 7 和 8 怪癖

*   有沒有內置的瀏覽器功能的 `window.confirm` ,但你可以將它綁定通過分配:

        window.confirm = navigator.notification.confirm;

*   調用到 `alert` 和 `confirm` 的非阻塞,所以結果就是只可用以非同步方式。


text:
define(["Leap"],
  function(Leap) {

    if(Leap !== undefined) {
      console.log("Leap loaded successful!");
    } else {
      console.log("FAIL, Leap isn't loaded! (after optimization, ERROR?!?)");
    }
  }
);


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.frc1675.subsystems;

import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.Relay;
import org.frc1675.RobotMap;
import org.frc1675.commands.MakeCompressorWork;

/**
 * Does all things relating to compressor
 *
 * @author Tony
 */
public class CompressorSystem extends Subsystem {

    private Compressor compressor;

    public CompressorSystem() {
        compressor = new Compressor(RobotMap.PRESSURE_SWITCH, RobotMap.COMPRESSOR_SPIKE);
    }

    public void initDefaultCommand() {
        setDefaultCommand(new MakeCompressorWork());
    }

    public void enable() {
        compressor.start();
    }

    public void disable() {
        compressor.setRelayValue(Relay.Value.kOff);
        compressor.stop();
    }
}


text:
<?php

global $_MODULE;
$_MODULE = array();

$_MODULE['<{blockcategories}prestashop>blockcategories_8f0ed7c57fca428f7e3f8e64d2f00918'] = 'Categories block';
$_MODULE['<{blockcategories}prestashop>blockcategories_15a6f5841d9e4d7e62bec3319b4b7036'] = 'Adds a block featuring product categories.';
$_MODULE['<{blockcategories}prestashop>blockcategories_23e0d4ecc25de9b2777fdaca3e2f3193'] = 'Maximum depth: Invalid number.';
$_MODULE['<{blockcategories}prestashop>blockcategories_0cf328636f0d607ac24a5c435866b94b'] = 'Dynamic HTML: Invalid choice.';
$_MODULE['<{blockcategories}prestashop>blockcategories_f4f70727dc34561dfde1a3c529b6205c'] = 'Settings';
$_MODULE['<{blockcategories}prestashop>blockcategories_1379a6b19242372c1f23cc9adedfcdd6'] = 'Category root';
$_MODULE['<{blockcategories}prestashop>blockcategories_c6d333d07d30f7b4c31a94bbd510bf88'] = 'Select which category is displayed in the block. The current category is the one the visitor is currently browsing.';
$_MODULE['<{blockcategories}prestashop>blockcategories_89b278a71f2be5f620307502326587a0'] = 'Home category';
$_MODULE['<{blockcategories}prestashop>blockcategories_62381fc27e62649a16182a616de3f7ea'] = 'Current category';
$_MODULE['<{blockcategories}prestashop>blockcategories_52b68aaa602d202c340d9e4e9157f276'] = 'Parent category';
$_MODULE['<{blockcategories}prestashop>blockcategories_f225631c1a6f71e99cc779f6bbf06dd4'] = 'Current category, unless it has no subcategories, in which case the parent category of the current category is used';
$_MODULE['<{blockcategories}prestashop>blockcategories_19561e33450d1d3dfe6af08df5710dd0'] = 'Maximum depth';
$_MODULE['<{blockcategories}prestashop>blockcategories_584d4e251b6f778eda9cfc2fc756b0b0'] = 'Set the maximum depth of category sublevels displayed in this block (0 = infinite).';
$_MODULE['<{blockcategories}prestashop>blockcategories_971fd8cc345d8bd9f92e9f7d88fdf20c'] = 'Dynamic';
$_MODULE['<{blockcategories}prestashop>blockcategories_c10efcaa2a8ff4eedaa3538fff78eb53'] = 'Activate dynamic (animated) mode for category sublevels.';
$_MODULE['<{blockcategories}prestashop>blockcategories_00d23a76e43b46dae9ec7aa9dcbebb32'] = 'Enabled';
$_MODULE['<{blockcategories}prestashop>blockcategories_b9f5c797ebbf55adccdd8539a65a0241'] = 'Disabled';
$_MODULE['<{blockcategories}prestashop>blockcategories_6b46ae48421828d9973deec5fa9aa0c3'] = 'Sort';
$_MODULE['<{blockcategories}prestashop>blockcategories_54e4f98fb34254a6678f0795476811ed'] = 'By name';
$_MODULE['<{blockcategories}prestashop>blockcategories_883f0bd41a4fcee55680446ce7bec0d9'] = 'By position';
$_MODULE['<{blockcategories}prestashop>blockcategories_06f1ac65b0a6a548339a38b348e64d79'] = 'Sort order';
$_MODULE['<{blockcategories}prestashop>blockcategories_e3cf5ac19407b1a62c6fccaff675a53b'] = 'Descending';
$_MODULE['<{blockcategories}prestashop>blockcategories_cf3fb1ff52ea1eed3347ac5401ee7f0c'] = 'Ascending';
$_MODULE['<{blockcategories}prestashop>blockcategories_5f73e737cedf8f4ccf880473a7823005'] = 'How many footer columns would you like?';
$_MODULE['<{blockcategories}prestashop>blockcategories_c9cc8cce247e49bae79f15173ce97354'] = 'Save';
$_MODULE['<{blockcategories}prestashop>blockcategories_footer_af1b98adf7f686b84cd0b443e022b7a0'] = 'Categories';
$_MODULE['<{blockcategories}prestashop>blockcategories_af1b98adf7f686b84cd0b443e022b7a0'] = 'Categories';

return $_MODULE;


text:
from django.conf.urls.defaults import *

import apiserver as api
import organization

class TOC(api.TOC):
    class Meta:
        route = ''
        resources = [organization.resources.Organizations]

v1 = api.API('v1')
v1.register(TOC)
v1.register(organization.resources)

urlpatterns = patterns('',
    (r'^', include(v1.urlconf)),
)


text:
using System.Collections.Generic;
using System.Linq;
using Xunit;

namespace System.Collections.Tests
{
    /// <summary>
    /// Contains tests that ensure the correctness of the List class.
    /// </summary>
    public abstract partial class List_Generic_Tests<T> : IList_Generic_Tests<T>
    {
        [Fact]
        public void Constructor_Default()
        {
            List<T> list = new List<T>();
            Assert.Equal(0, list.Capacity); //"Expected capacity of list to be the same as given."
            Assert.Equal(0, list.Count); //"Do not expect anything to be in the list."
            Assert.False(((IList<T>)list).IsReadOnly); //"List should not be readonly"
        }

        [Theory]
        [InlineData(0)]
        [InlineData(10)]
        [InlineData(15)]
        [InlineData(16)]
        [InlineData(17)]
        [InlineData(100)]
        public void Constructor_Capacity(int capacity)
        {
            List<T> list = new List<T>(capacity);
            Assert.Equal(capacity, list.Capacity); //"Expected capacity of list to be the same as given."
            Assert.Equal(0, list.Count); //"Do not expect anything to be in the list."
            Assert.False(((IList<T>)list).IsReadOnly); //"List should not be readonly"
        }

        [Theory]
        [InlineData(-1)]
        [InlineData(int.MinValue)]
        public void Constructor_NegativeCapacity_ThrowsArgumentOutOfRangeException(int capacity)
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => new List<T>(capacity));
        }

        [Theory]
        [MemberData(nameof(EnumerableTestData))]
        public void Constructor_IEnumerable(EnumerableType enumerableType, int listLength, int enumerableLength, int numberOfMatchingElements, int numberOfDuplicateElements)
        {
            _ = listLength;
            _ = numberOfMatchingElements;
            IEnumerable<T> enumerable = CreateEnumerable(enumerableType, null, enumerableLength, 0, numberOfDuplicateElements);
            List<T> list = new List<T>(enumerable);
            List<T> expected = enumerable.ToList();

            Assert.Equal(enumerableLength, list.Count); //"Number of items in list do not match the number of items given."

            for (int i = 0; i < enumerableLength; i++)
                Assert.Equal(expected[i], list[i]); //"Expected object in item array to be the same as in the list"

            Assert.False(((IList<T>)list).IsReadOnly); //"List should not be readonly"
        }

        [Fact]
        public void Constructo_NullIEnumerable_ThrowsArgumentNullException()
        {
            Assert.Throws<ArgumentNullException>(() => { List<T> _list = new List<T>(null); }); //"Expected ArgumentnUllException for null items"
        }
    }
}


text:
from werkzeug.local import Local, LocalManager

context = Local()
local_manager = LocalManager([context])

def release_context():
    local_manager.cleanup()


text:
<?php

namespace MiniSuite\That;

use MiniSuite\AbstractExpectation;

/*
    Verify if the value is an object
*/
class IsObjectExpectation extends AbstractExpectation {

    /*
        Check if the condition is matched

        Parameters
            mixed $value
    */
    public function check($value) {
        if(!is_object($value)) {
            $value = $this->format($value);
            throw new \Exception("should be an object but instead saw '$value'");
        }
    }

}


text:
package com.github.stonelion.promise;

public class Precondition {
    public static <T> T checkNotNull(T reference) {
        if (reference == null) {
            throw new NullPointerException();
        }
        return reference;
    }
}


text:
@interface ELMIDINoteMessage : NSObject {
  Byte  _channel;
  Byte  _note;
  Byte  _velocity;
  BOOL  _noteOn;
}

- (id)initWithChannel:(Byte)channel note:(Byte)note velocity:(Byte)velocity noteOn:(BOOL)noteOn;

@property Byte channel;
@property Byte note;
@property Byte velocity;
@property  (nonatomic) BOOL noteOn;

- (BOOL)matchesChannelMask:(Byte)channelMask;

@end


text:
class CreateTr8nApplications < ActiveRecord::Migration
  def self.up
    create_table :tr8n_applications do |t|
      t.string :key
      t.string :name
      t.string :description
      t.timestamps
    end

    add_index :tr8n_applications, [:key]
  end

  def self.down
    drop_table :tr8n_applications
  end
end


text:
require "./reverse_integer"
require "test/unit"

class TestReverse2BasedInteger < Test::Unit::TestCase
  def test_main
    assert_equal(11, Reverse2BasedInteger.reverse(13))
    assert_equal(61, Reverse2BasedInteger.reverse(47))
    assert_equal(1365623, Reverse2BasedInteger.reverse(1000000000))
  end
end


text:
package ui

import(
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"golang.org/x/net/context"
	"google.golang.org/appengine/user"

	"github.com/skypies/adsb"
	"github.com/skypies/geo"
	"github.com/skypies/geo/sfo"
	sprovider "github.com/skypies/util/gcp/singleton"
	"github.com/skypies/util/widget"

	fdb "github.com/skypies/flightdb"
	"github.com/skypies/flightdb/fgae"
	"github.com/skypies/flightdb/fr24"
	"github.com/skypies/flightdb/ref"
)

// {{{ DebugHandler

func DebugHandler(db fgae.FlightDB, w http.ResponseWriter, r *http.Request) {
	ctx := db.Ctx()
	opt,_ := GetUIOptions(ctx)
	str := ""

	idspecs,err := opt.IdSpecs()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	topstr := ""

	for _,idspec := range idspecs {
		q := db.NewQuery().ByIdSpec(idspec)
		topstr += fmt.Sprintf("*** %s\n", idspec)

		results,err := db.LookupAll(q)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		for i,result := range results {
			topstr += fmt.Sprintf("  * %s\n", result)
			str += fmt.Sprintf(" [%02d] %s\n", i, result)

			//db.PersistFlight(result)
		}
		str += "\n\n\n\n"

		for i,f := range results {
			str += fmt.Sprintf("----------{result %02d }-----------\n\n", i)

			if f == nil {
				http.Error(w, fmt.Sprintf("idspec %s[%#v] not found", idspec, idspec), http.StatusInternalServerError)
				return
			}

			str += fmt.Sprintf("    %s\n", f.IdSpec())
			str += fmt.Sprintf("    %s\n", f.FullString())
			str += fmt.Sprintf("    airframe: %s\n", f.Airframe.String())
			str += fmt.Sprintf("    %s\n\n", f)
			str += fmt.Sprintf("    index tags: %v\n", f.IndexTagList())
			str += fmt.Sprintf("    /batch/flights/flight?flightkey=%s&job=retag\n", f.GetDatastoreKey())

			t := f.AnyTrack()
			str += fmt.Sprintf("\n---- Anytrack: %s\n", t)

			for k,v := range f.Tracks {
				str += fmt.Sprintf("  -- [%-7.7s] %s\n", k, v)
				if r.FormValue("v") != "" {
					for n,tp := range *v {
						str += fmt.Sprintf("    - [%3d] %s\n", n, tp)
					}
				}
			}
			str += "\n"
			str += fmt.Sprintf("--- DebugLog:-\n%s\n", f.DebugLog)
		}
	}

	w.Header().Set("Content-Type", "text/plain")
	w.Write([]byte(fmt.Sprintf("OK\n\n%s\n%s", topstr, str)))
}

// }}}

// {{{ debugUserHandler

func debugUserHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	user := user.Current(ctx)
	json,_ := json.MarshalIndent(user, "", "  ")

	w.Header().Set("Content-Type", "text/plain")
	w.Write([]byte("OK\n--\n"+string(json)))
}

// }}}
// {{{ DebugHandler9

func DebugHandler9(db fgae.FlightDB, w http.ResponseWriter, r *http.Request) {
	ctx := db.Ctx()
	opt,_ := GetUIOptions(ctx)
	str := ""

	/*
	conts,_ := ioutil.ReadDir(".")
	for _,f := range conts {
		str += fmt.Sprintf("Yoho: %s\n", f.Name())
	}
	w.Header().Set("Content-Type", "text/plain")
	w.Write([]byte(fmt.Sprintf("OK\n\n%s", str)))
	return
*/

	//str += fmt.Sprintf("** Idspecs:-\n%#v\n\n", opt.IdSpecs())

	idspecs,err := opt.IdSpecs()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	nPts := 0
	for _,idspec := range idspecs {
		q := db.NewQuery().ByIdSpec(idspec)
		str += fmt.Sprintf("*** %s [%v]\n%s\nResults:-\n", idspec, idspec, q)

		results,err := db.LookupAll(q)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		for i,result := range results {
			//s,e := result.Times()
			//str += fmt.Sprintf("  * [%02d] %s,%s  %s\n", i, s,e, result.IdentityString())
			str += fmt.Sprintf(" [%02d] %s\n", i, result)
			nPts += len(result.AnyTrack())
		}
		str += fmt.Sprintf("*** Total pts: %d\n", nPts)
		str += "\n\n\n\n"

		for i,f := range results {
			str += fmt.Sprintf("----------{result %02d }-----------\n\n", i)

			if f == nil {
				http.Error(w, fmt.Sprintf("idspec %s[%#v] not found", idspec, idspec), http.StatusInternalServerError)
				return
			}

			str += fmt.Sprintf("    %s\n", f.IdSpec())
			str += fmt.Sprintf("    %s\n", f.FullString())
			str += fmt.Sprintf("    airframe: %s\n", f.Airframe.String())
			str += fmt.Sprintf("    %s\n\n", f)
			str += fmt.Sprintf("    index tags: %v\n", f.IndexTagList())
			str += fmt.Sprintf("    /batch/flights/flight?flightkey=%s&job=retag\n", f.GetDatastoreKey())

			t := f.AnyTrack()
			str += fmt.Sprintf("\n---- Anytrack: %s\n", t)

			/*
			gr := geo.LatlongBoxRestrictor{LatlongBox: sfo.KFixes["ZORSA"].Box(1,1) }
			satisfies,intersection,deb := f.SatisfiesGeoRestriction(gr, []string{"ADSB","MLAT"})
			str += fmt.Sprintf("\n\n---- ZORSA@1KM intersection result:-\n * %v\n * %s\n----\n%s",
				satisfies, intersection, deb)*/

			/* pos := sfo.KFixes["BRIXX"]
		gr := geo.LatlongBoxRestrictor{LatlongBox: pos.Box(1,1) }
		isects,debug := t.AllIntersectsGeoRestriction(gr)
		str += fmt.Sprintf("---- Intersections\n")
		for _,isect := range isects { str += fmt.Sprintf("  -- %s\n", isect) }
		str += fmt.Sprintf("\n%s", debug) */

			for k,v := range f.Tracks {
				str += fmt.Sprintf("  -- [%-7.7s] %s\n", k, v)
				if r.FormValue("v") != "" {
					for n,tp := range *v {
						str += fmt.Sprintf("    - [%3d] %s\n", n, tp)
					}
				}
			}
			str += "\n"
			str += fmt.Sprintf("--- DebugLog:-\n%s\n", f.DebugLog)
		}
	}

	w.Header().Set("Content-Type", "text/plain")
	w.Write([]byte(fmt.Sprintf("OK\n\n%s", str)))
}

// }}}
// {{{ DebugSchedHandler

func DebugSchedHandler(db fgae.FlightDB, w http.ResponseWriter, r *http.Request) {
	ctx := db.Ctx()
	sp := sprovider.NewProvider(db.Backend)

	str := "--{ DebugSchedHandler }--\n"
	k := r.FormValue("k")

	if airframes,err := ref.LoadAirframeCache(ctx, sp); err != nil {
		str += fmt.Sprintf("LoadAirframeCache: err=%v\n", err)
	} else if schedules,err := ref.LoadScheduleCache(ctx, sp); err != nil {
		str += fmt.Sprintf("LoadScheduleCache: err=%v\n", err)
	} else {
		af := airframes.Get(k)
		sched := schedules.Get(k)

		str += fmt.Sprintf("Live refdata lookup for '%s':-\n----\n%#v\n----\n%#v\n----\n%s", k, sched, af, schedules)
	}

	w.Header().Set("Content-Type", "text/plain")
	w.Write([]byte(fmt.Sprintf("OK\n\n%s", str)))
}

// }}}

// {{{ AddFragEvent{}

type AddFragEvent struct {
	TrackFragment fdb.TrackFragment
	Time time.Time
	I int `json:"-"`
	N int `json:"-"`  // Added N trackpoints starting at index I
	J int `json:"-"` // result number
}

func (ev AddFragEvent)String() string {
	// Delay from when message was received, to when frag was written to datastore
	delay := ev.Time.Sub(ev.TrackFragment.Track[0].TimestampUTC).Seconds()
	return fmt.Sprintf("{{%2d}} % 4d + %2d : %s (total delay %6.0fs) %s",
		ev.J, ev.I, ev.N,
		ev.TrackFragment.Track[0].TimestampUTC.Format("15:04:05"),
		delay, ev.TrackFragment)
}

type ByTimeOfDBWrite []AddFragEvent

func (a ByTimeOfDBWrite) Len() int           { return len(a) }
func (a ByTimeOfDBWrite) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByTimeOfDBWrite) Less(i, j int) bool { return a[i].Time.Before(a[j].Time) }

// }}}
// {{{ AddNewEvent

func AddNewEvent(events *[]AddFragEvent, instance int, t fdb.Track, id,callsign string, start,length int, tm time.Time) {
	ev := AddFragEvent{
		TrackFragment: track2frag(t, id, callsign, start, length),
		Time:tm,
		J:instance,
		I:start,
		N:length,
	}

	*events = append(*events, ev)
}

func track2frag(t fdb.Track, id,callsign string, start,length int) fdb.TrackFragment {
	if len(t) == 0 || start+length > len(t) {
		return fdb.TrackFragment{}
	}

	frag := fdb.TrackFragment{
		IcaoId: adsb.IcaoId(id),
		Callsign: callsign,
		Track: t[start:(start+length)],
		DataSystem: fdb.DSADSB,
	}

	if t[0].DataSource != "ADSB" {
		frag.DataSystem = fdb.DSMLAT
	}

	return frag
}

// }}}
/*
// {{{ debugFragsHandler

// This handler reconstructs the series of TrackFragments that generated the set of
// flights matching the idpsec (use a range idspec to get multiple instances of the same IcaoID).
// It parses the debug log to figure out which trackpoints got added when, so it's brittle.
func debugFragsHandler(db fgae.FlightDB, w http.ResponseWriter, r *http.Request) {
	ctx := db.Ctx()
	opt,_ := GetUIOptions(ctx)
	str := ""

	idspecs,err := opt.IdSpecs()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	events := []AddFragEvent{}
	nPts := 0

	for _,idspec := range idspecs {
		str += fmt.Sprintf("*** %s [%v]\n", idspec, idspec)

		results,err := db.LookupAll(db.NewQuery().ByIdSpec(idspec))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		for i,result := range results {
			str += fmt.Sprintf("  * [%02d] %s\n", i, result)
			nPts += len(result.AnyTrack())
		}
		str += fmt.Sprintf("*** Total pts: %d\n\n\n", nPts)

		for instance,f := range results {
			var tStart time.Time
			var track fdb.Track
			firstHandled := false

			// What to write the fragments as
			newIcao := r.FormValue("as")
			if newIcao == "" { newIcao = f.IcaoId }

			for _,line := range strings.Split(f.DebugLog, "\n") {
				exp := "-- AddFrag.*\\]([AM]) (\\d{4}-.* UTC): "+
					"(was not plausible|new IcaoID|extending \\(adding (\\d+) to (\\d+))"
				reg := regexp.MustCompile(exp).FindStringSubmatch(line)
				if reg != nil {
					t,_ := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", reg[2])
					length,_ := strconv.Atoi(reg[4])
					index,_ := strconv.Atoi(reg[5])

					if length == 0 { // AKA undef; must be the initial fragment; we don't know how long it is
						tStart = t
						switch (fdb.DataSystem(reg[1])) {
						case fdb.DSADSB: track = *(f.Tracks["ADSB"])
						default: track = *(f.Tracks["MLAT"])
						}

					} else {
						if !firstHandled {
							// Now we know how long the first frag was, add it in
							if 0+index > len(track) {
								http.Error(w, fmt.Sprintf("0+%d > %d !", index, len(track)),
									http.StatusInternalServerError)
								return
							}
							AddNewEvent(&events, instance, track, newIcao, f.Callsign, 0, index, tStart)
							firstHandled = true
						}
						if index+length > len(track) {
							http.Error(w, fmt.Sprintf("%d+%d > %d !", index, length, len(track)),
								http.StatusInternalServerError)
							return
						}
						AddNewEvent(&events, instance, track, newIcao, f.Callsign, index, length, t)
					}
				}
			}

			if !firstHandled {
				// We only ever had one frag - so its length is that of the whole track
				AddNewEvent(&events, instance, track, newIcao, f.Callsign, 0, len(track), tStart)
			}
		}
	}

	//fgae.Debug = true

	sort.Sort(ByTimeOfDBWrite(events)) // Restore the original insertion order

	if false && len(events) == 865 {
		// The original list of 864 frags is too long to use with test datastore. Prune out these
		// uninteresting serial ones: [776,864] [300,758] [143,260]
		events = events[:777]
		events = append(events[:300], events[759:]...)
		events = append(events[:143], events[261:]...)
	}

	for i,ev := range events {
		relativeT := ev.Time.Sub(events[0].Time).Seconds() // Time from when first frag was written

		if r.FormValue("as") != "" {
			// We've been asked to reinsert these frags, in their orig order, with a new IcaoID
			time.Sleep(1000 * time.Millisecond) // the test datastore gets confused if we go any quicker
			err := db.AddTrackFragment(&ev.TrackFragment)
			str += fmt.Sprintf("%08.3fs %s added [[%v]]\n", relativeT, ev, err)
		} else if r.FormValue("json") == "" {
			str += fmt.Sprintf("[% 5d] %08.3fs %s\n", i, relativeT, ev)
		}
	}

	if r.FormValue("json") != "" {
		frags := []fdb.TrackFragment{}
		for _,ev := range events {
			frags = append(frags, ev.TrackFragment)
		}
		json,_ := json.MarshalIndent(frags, "", "  ")
		str = "OK\n--\n"+string(json)
	}

	w.Header().Set("Content-Type", "text/plain")
	w.Write([]byte(fmt.Sprintf("OK\n\n%s", str)))
}

// }}}
*/
// {{{ AirspaceDelayHandler

// Pulls a skypi airspace, resyncs flight positions to some point in past (or future),
// and displays them both with a line between them.
//	&sync=-20s

func AirspaceDelayHandler(db fgae.FlightDB, w http.ResponseWriter, r *http.Request) {
	client := db.HTTPClient()
	pos := geo.Latlong{37.060312,-121.990814}

	syncedAge := widget.FormValueDuration(r, "sync")
	if syncedAge == 0 { syncedAge = 2 * time.Minute }

	as,err := fr24.FetchAirspace(client, pos.Box(100,100))
	if err != nil {
		http.Error(w, fmt.Sprintf("FetchAirspace: %v", err), http.StatusInternalServerError)
		return
	}
	ms := NewMapShapes()
	for _,ad := range as.Aircraft {
		tp := fdb.TrackpointFromADSB(ad.Msg)
		age := time.Since(tp.TimestampUTC)
		rewindDuration := age - syncedAge
		newTp := tp.RepositionByTime(rewindDuration)

		ms.AddIcon(MapIcon{TP:&tp,    Color:"#404040", Text:ad.Msg.Callsign,     ZIndex:1000})
		ms.AddIcon(MapIcon{TP:&newTp, Color:"#c04040", Text:ad.Msg.Callsign+"'", ZIndex:2000})
		ms.AddLine(MapLine{Start:tp.Latlong, End:newTp.Latlong, Color:"#000000"})
	}

	var params = map[string]interface{}{
		"Legend": "Debug Thing",
		"Center": sfo.KFixes["YADUT"],
		"Zoom": 9,
	}

	MapHandlerWithShapesParams(db.Ctx(), w, r, ms, params);
}

// }}}

// {{{ -------------------------={ E N D }=----------------------------------

// Local variables:
// folded-file: t
// end:

// }}}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Ciboria juncigena Ellis & Everh.

### Remarks
null


text:
import re

commit_types = ['feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'chore', 'config']

branchre = re.compile('release-(\d+\.\d+\.x)')
commitre = re.compile('({})(.*): (.*)'.format('|'.join(commit_types)))

def ParseReleaseBranch(branch):
    branch = ReleaseBranchFor(branch)
    if branch is None:
        return None

    branch = branch.split('.')[:-1]
    branch = [ int(v) for v in branch ]
    return branch

def ReleaseBranchFor(branch):
    if not branch:
        return None
    m = branchre.match(branch)
    if m:
        return m.group(1)
    else:
        return None

def ParseCommitMessage(message):
    if not message:
        return None
    m = commitre.match(message)
    if m:
        return {
                'type': m.group(1),
                'scope': m.group(2),
                'subject': m.group(3)
        }
    else:
        return None


text:
using namespace lldb;
using namespace lldb_private;

BreakpointID::BreakpointID(break_id_t bp_id, break_id_t loc_id)
    : m_break_id(bp_id), m_location_id(loc_id) {}

BreakpointID::~BreakpointID() = default;

static llvm::StringRef g_range_specifiers[] = {"-", "to", "To", "TO"};

// Tells whether or not STR is valid to use between two strings representing
// breakpoint IDs, to indicate a range of breakpoint IDs.  This is broken out
// into a separate function so that we can easily change or add to the format
// for specifying ID ranges at a later date.

bool BreakpointID::IsRangeIdentifier(llvm::StringRef str) {
  for (auto spec : g_range_specifiers) {
    if (spec == str)
      return true;
  }

  return false;
}

bool BreakpointID::IsValidIDExpression(llvm::StringRef str) {
  return BreakpointID::ParseCanonicalReference(str).hasValue();
}

llvm::ArrayRef<llvm::StringRef> BreakpointID::GetRangeSpecifiers() {
  return llvm::makeArrayRef(g_range_specifiers);
}

void BreakpointID::GetDescription(Stream *s, lldb::DescriptionLevel level) {
  if (level == eDescriptionLevelVerbose)
    s->Printf("%p BreakpointID:", static_cast<void *>(this));

  if (m_break_id == LLDB_INVALID_BREAK_ID)
    s->PutCString("<invalid>");
  else if (m_location_id == LLDB_INVALID_BREAK_ID)
    s->Printf("%i", m_break_id);
  else
    s->Printf("%i.%i", m_break_id, m_location_id);
}

void BreakpointID::GetCanonicalReference(Stream *s, break_id_t bp_id,
                                         break_id_t loc_id) {
  if (bp_id == LLDB_INVALID_BREAK_ID)
    s->PutCString("<invalid>");
  else if (loc_id == LLDB_INVALID_BREAK_ID)
    s->Printf("%i", bp_id);
  else
    s->Printf("%i.%i", bp_id, loc_id);
}

llvm::Optional<BreakpointID>
BreakpointID::ParseCanonicalReference(llvm::StringRef input) {
  break_id_t bp_id;
  break_id_t loc_id = LLDB_INVALID_BREAK_ID;

  if (input.empty())
    return llvm::None;

  // If it doesn't start with an integer, it's not valid.
  if (input.consumeInteger(0, bp_id))
    return llvm::None;

  // period is optional, but if it exists, it must be followed by a number.
  if (input.consume_front(".")) {
    if (input.consumeInteger(0, loc_id))
      return llvm::None;
  }

  // And at the end, the entire string must have been consumed.
  if (!input.empty())
    return llvm::None;

  return BreakpointID(bp_id, loc_id);
}

bool BreakpointID::StringIsBreakpointName(llvm::StringRef str, Status &error) {
  error.Clear();
  if (str.empty())
  {
    error.SetErrorStringWithFormat("Empty breakpoint names are not allowed");
    return false;
  }

  // First character must be a letter or _
  if (!isalpha(str[0]) && str[0] != '_')
  {
    error.SetErrorStringWithFormat("Breakpoint names must start with a "
                                   "character or underscore: %s",
                                   str.str().c_str());
    return false;
  }

  // Cannot contain ., -, or space.
  if (str.find_first_of(".- ") != llvm::StringRef::npos) {
    error.SetErrorStringWithFormat("Breakpoint names cannot contain "
                                   "'.' or '-': \"%s\"",
                                   str.str().c_str());
    return false;
  }

  return true;
}


text:
import loadingCourses from './loading_courses';

describe('loading_courses reducer', () => {
  describe('initial state', () => {
    it('returns empty state', () => {
      const initialState = {};
      const state = loadingCourses(initialState, {});
      expect(state).toEqual({});
    });
  });

  describe('list external tools courses', () => {
    it('returns localDataId to be true', () => {
      const localDataId = 2;
      const state = { loading_courses: [{ 1: { id: 1, config: 123 } }], 2: false };
      const result = loadingCourses(state, { type: 'LIST_EXTERNAL_TOOLS_COURSES', localData: localDataId });
      expect(result.loading_courses.length).toBe(1);
      expect(result[localDataId]).toBe(true);
    });
  });

  describe('delete external tools courses', () => {
    it('returns the same state', () => {
      const localDataId = 2;
      const state = { loading_courses: [{ 1: { id: 1, config: 123 } }], 2: false };
      const result = loadingCourses(state, { type: 'LIST_EXTERNAL_TOOLS_COURSES_DONE', original: { localData: localDataId } });
      expect(result.loading_courses.length).toBe(1);
      expect(result[localDataId]).not.toBeDefined();
    });
  });
});


text:
DM_TEMPLATE
class DistanceRow : public Object{
public:

  //CONSTRUCTORS
  DistanceRow(size_t columns=0);
  DistanceRow(const DistanceRow &dm);
  DistanceRow(std::istream &in);

  //DIMENSIONS
  size_t getColumns() const{ return columns;}
  void resize(size_t newsize) { if ( columns != newsize) {columns = newsize; assureSize();} }

  //set all the matrix elements and identifiers to the supplied values.
  void setDefaultValues(DistanceType &defval, Identifier &defid);

  //---------------------------------
  //GET AND SET DISTANCE
  DistanceType getDistance(int j) const{
      return D[j];
  };

  void setDistance(int j, DistanceType d) {
      D[j] = d;
  };

  //---------------------
  void setIdentifier(Identifier id){
    identifier = id;
  }
  Identifier& getIdentifier(){
    return identifier;
  }
 const Identifier& getIdentifier() const{
    return identifier;
 }

  //------------------- PRIVATE ------------------------
private:
  DistInit distInit;
  DistPrintOn distPrintOn;
  IdentInit idInit;
  IdentPrintOn idPrintOn;

  size_t columns;
  Identifier identifier;
  std::vector<DistanceType> D;

  //makes sure that the vectors are of the right size.
  void assureSize();

};

//--------------------------
// Include the implementation
#include "DistanceRow_impl.hpp"

//-------------------------
// A regular distance matrix with strings as identifier and doubles as distance type.
typedef DistanceRow<std::string, double, Data_init<std::string>, Data_printOn<std::string>, Data_init<double>, Data_printOn<double> > StrDblRow;
typedef DistanceRow<std::string, float, Data_init<std::string>, Data_printOn<std::string>, Data_init<float>, Data_printOn<float> > StrFloRow;
//Distance for over saturated data ( !isfinite(d) || d<0 ) is set to <int>*maxRealDistance.\n"
//returns true if some element was changed.
bool
applyFixFactorRow(StrFloRow &dm, float fixFactor);

#endif // DISTANCEROW_HPP


text:
Package.describe({
  name: 'storyteller:profiles-react-materialize',
  version: '0.3.4',
  summary: 'Profiles for your users',
  git: 'https://github.com/StorytellerCZ/meteor-profiles-react-materialize.git',
  documentation: 'README.md',
  deprecated: true
});

Package.onUse(function(api) {
  api.versionsFrom(['1.3', '2.3']);
  api.use(['meteor', 'ecmascript', 'check', 'accounts-password']);

  //other packages in use
  api.use([
    'storyteller:profiles-server@1.0.0',
    'socialize:user-profile@1.0.5',
    'socialize:friendships@1.1.2',
    'socialize:feed@1.0.5',
    'momentjs:moment@2.29.1',
    'djedi:sanitize-html-client@1.11.3'
  ]);

  api.addFiles([
    'components/UserProfile.jsx',
    'layouts/profile.css',
    'components/ChangeAvatar.jsx',
    'components/ChangeBio.jsx',
    'components/ChangeName.jsx',
    'components/ProfileSettings.jsx',
    'components/FriendsRequests.jsx',
    'components/Feed.jsx',
    'components/NewFeedPost.jsx'
  ], "client");

  api.imply(['momentjs:moment']);

  api.export([
    "UserProfile",
    "UserChangeAvatar",
    "UserChangeBio",
    "UserChangeName",
    "UserProfileSettings",
    "UserFriendsRequests",
    "UserFeed",
    "NewFeedPost"
  ], "client");
});

Package.onTest(function(api) {
  api.use('ecmascript');
  api.use('tinytest');
  api.use('storyteller:profiles-react-materialize');
  //api.addFiles('profiles-react-materialize-tests.js');
});


text:
import { fork, ChildProcess } from "child_process";
import { Mappings, Mapping, RawSourceMap, SmartPosition, Position } from "../approved-imports/source-map";
import { CancellationToken } from "../approved-imports/cancallation";
import { createMessageConnection, MessageConnection } from "../approved-imports/jsonrpc";
import { DataStoreViewReadonly, DataStoreView, DataHandleRead } from "../data-store/data-store";
import { Message, IAutoRestPluginInitiator_Types, IAutoRestPluginTarget_Types, IAutoRestPluginInitiator } from "./plugin-api";

interface IAutoRestPluginTargetEndpoint {
  GetPluginNames(cancellationToken: CancellationToken): Promise<string[]>;
  Process(pluginName: string, sessionId: string, cancellationToken: CancellationToken): Promise<boolean>;
}

interface IAutoRestPluginInitiatorEndpoint {
  FinishNotifications(): Promise<void>; // not exposed; necessary to ensure notifications are processed before

  ReadFile(filename: string): Promise<string>;
  GetValue(key: string): Promise<any>;
  ListInputs(): Promise<string[]>;

  WriteFile(filename: string, content: string, sourceMap?: Mappings | RawSourceMap): Promise<void>;
  Message(message: Message<any>, path?: SmartPosition, sourceFile?: string): Promise<void>;
}

export class AutoRestPlugin {
  private static lastSessionId: number = 0;
  private static CreateSessionId(): string { return `session_${++AutoRestPlugin.lastSessionId}`; }

  public static async FromModule(modulePath: string): Promise<AutoRestPlugin> {
    const childProc = fork(modulePath, [], <any>{ silent: true });
    return AutoRestPlugin.FromChildProcess(childProc);
  }

  public static async FromChildProcess(childProc: ChildProcess): Promise<AutoRestPlugin> {
    // childProc.on("error", err => { throw err; });
    const channel = createMessageConnection(
      childProc.stdout,
      childProc.stdin,
      console
    );
    childProc.stderr.pipe(process.stderr);
    const plugin = new AutoRestPlugin(channel);
    channel.listen();
    return plugin;
  }

  public constructor(channel: MessageConnection) {
    // initiator
    const dispatcher = (fnName: string) => (sessionId: string, ...rest: any[]) => {
      const endpoint = this.apiInitiatorEndpoints[sessionId];
      if (endpoint) {
        return (endpoint as any)[fnName](...rest);
      }
    };
    this.apiInitiator = {
      ReadFile: dispatcher("ReadFile"),
      GetValue: dispatcher("GetValue"),
      ListInputs: dispatcher("ListInputs"),

      WriteFile: dispatcher("WriteFile"),
      Message: dispatcher("Message"),
    };
    channel.onRequest(IAutoRestPluginInitiator_Types.ReadFile, this.apiInitiator.ReadFile);
    channel.onRequest(IAutoRestPluginInitiator_Types.GetValue, this.apiInitiator.GetValue);
    channel.onRequest(IAutoRestPluginInitiator_Types.ListInputs, this.apiInitiator.ListInputs);
    channel.onNotification(IAutoRestPluginInitiator_Types.WriteFile, this.apiInitiator.WriteFile);
    channel.onNotification(IAutoRestPluginInitiator_Types.Message, this.apiInitiator.Message);

    // target
    this.apiTarget = {
      async GetPluginNames(cancellationToken: CancellationToken): Promise<string[]> {
        return await channel.sendRequest(IAutoRestPluginTarget_Types.GetPluginNames, cancellationToken);
      },
      async Process(pluginName: string, sessionId: string, cancellationToken: CancellationToken): Promise<boolean> {
        return await channel.sendRequest(IAutoRestPluginTarget_Types.Process, pluginName, sessionId, cancellationToken);
      }
    };
  }

  private apiTarget: IAutoRestPluginTargetEndpoint;
  private apiInitiator: IAutoRestPluginInitiator;
  private apiInitiatorEndpoints: { [sessionId: string]: IAutoRestPluginInitiatorEndpoint } = {};

  public GetPluginNames(cancellationToken: CancellationToken): Promise<string[]> {
    return this.apiTarget.GetPluginNames(cancellationToken);
  }

  public async Process(pluginName: string, configuration: (key: string) => any, inputScope: DataStoreViewReadonly, outputScope: DataStoreView, messageScope: DataStoreView, cancellationToken: CancellationToken): Promise<boolean> {
    const sid = AutoRestPlugin.CreateSessionId();

    // register endpoint
    this.apiInitiatorEndpoints[sid] = AutoRestPlugin.CreateEndpointFor(configuration, inputScope, outputScope, messageScope, cancellationToken);

    // dispatch
    const result = await this.apiTarget.Process(pluginName, sid, cancellationToken);

    // wait for outstanding notifications
    await this.apiInitiatorEndpoints[sid].FinishNotifications();

    // unregister endpoint
    delete this.apiInitiatorEndpoints[sid];

    return result;
  }

  private static CreateEndpointFor(configuration: (key: string) => any, inputScope: DataStoreViewReadonly, outputScope: DataStoreView, messageScope: DataStoreView, cancellationToken: CancellationToken): IAutoRestPluginInitiatorEndpoint {
    let messageId: number = 0;

    const inputFileHandles = async () => {
      const inputFileNames = Array.from(await inputScope.Enum());
      const inputFiles = await Promise.all(inputFileNames.map(fn => inputScope.ReadStrict(fn)));
      return inputFiles;
    }

    let finishNotifications: Promise<void> = Promise.resolve();
    const apiInitiator: IAutoRestPluginInitiatorEndpoint = {
      FinishNotifications(): Promise<void> { return finishNotifications; },
      async ReadFile(filename: string): Promise<string> {
        const file = await inputScope.ReadStrict(filename);
        return await file.ReadData();
      },
      async GetValue(key: string): Promise<any> {
        return configuration(key);
      },
      async ListInputs(): Promise<string[]> {
        const result = await inputScope.Enum();
        return Array.from(result);
      },

      async WriteFile(filename: string, content: string, sourceMap?: Mappings | RawSourceMap): Promise<void> {
        if (!sourceMap) {
          sourceMap = [];
        }
        const finishPrev = finishNotifications;
        let notify: () => void = () => { };
        finishNotifications = new Promise<void>(res => notify = res);

        const file = await outputScope.Write(filename);
        if (typeof (sourceMap as any).mappings === "string") {
          await file.WriteDataWithSourceMap(content, async () => sourceMap);
        } else {
          await file.WriteData(content, sourceMap as Mappings, await inputFileHandles());
        }

        await finishPrev;
        notify();
      },
      async Message(message: Message<any>, path?: SmartPosition, sourceFile?: string): Promise<void> {
        if (message.channel === "FATAL") {
          throw new Error(message.message);
        }

        const finishPrev = finishNotifications;
        let notify: () => void = () => { };
        finishNotifications = new Promise<void>(res => notify = res);

        const dataHandle = await messageScope.Write(`message_${messageId++}.yaml`);
        const mappings: Mapping[] = [];
        const files = await inputFileHandles();
        if (path) {
          if (!sourceFile) {
            if (files.length !== 1) {
              await finishPrev;
              notify();
              throw new Error("Message did not specify blame origin but there are multiple input files");
            }
            sourceFile = files[0].key;
          }
          var a: Position = { line: 1, column: 0 };
          var b: SmartPosition = a;

          mappings.push({
            name: `location of ${message.channel} '${message.message}'`,
            source: sourceFile,
            generated: <Position>{ line: 1, column: 0 },
            original: path
          });
        }
        dataHandle.WriteObject(message, mappings, files);

        await finishPrev;
        notify();
      }
    };
    return apiInitiator;
  }
}


text:
package io.zrz.zulu.server.netty;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.ImmutableList;

import hu.akarnokd.rxjava2.interop.FlowInterop;
import io.reactivex.Flowable;
import io.zrz.graphql.plugins.jackson.JacksonResultReceiver;
import io.zrz.graphql.plugins.jackson.ZuluJacksonParameterProvider;
import io.zrz.graphql.zulu.engine.ZuluEngine;
import io.zrz.graphql.zulu.engine.ZuluPortal;
import io.zrz.graphql.zulu.engine.ZuluWarning;
import io.zrz.graphql.zulu.server.ImmutableBindParams;
import zulu.runtime.subscriptions.ZuluDataResult;
import zulu.runtime.subscriptions.ZuluResult;

/**
 * provides common functionality shared between the HTTP endpoint and websocket.
 *
 * @author theo
 *
 */

public class DefaultZuluHttpEngine implements ZuluHttpEngine {

  private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(DefaultZuluHttpEngine.class);
  private final ZuluEngine zulu;
  private final ZuluHttpResponder responder;

  public DefaultZuluHttpEngine(final ZuluEngine zulu, final ZuluHttpResponder responder) {
    this.zulu = zulu;
    this.responder = responder;
  }

  @Override
  public Flowable<ZuluJacksonResult> execute(final HttpOperationRequest req) {

    final ImmutableBindParams query = ImmutableBindParams.builder()
        .query(req.query())
        .operationName(req.operationName())
        .variables(new ZuluJacksonParameterProvider(this.responder.mapper(), req.variables()))
        .build();

    final ZuluPortal portal = this.zulu.bind(query, this.responder);

    return FlowInterop
        .fromFlowPublisher(portal)
        .doOnCancel(() -> {
          log.debug("query cancelled");
          portal.cancel();
        })
        .map(this::mapResult);

  }

  ZuluJacksonResult mapResult(final ZuluResult res) {

    final ZuluDataResult data = (ZuluDataResult) res;
    final ObjectNode json;
    final List<ZuluWarning> notes = new LinkedList<>();

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (JsonGenerator jg = DefaultZuluHttpEngine.this.responder.mapper().getFactory().createGenerator(baos)) {
      final JacksonResultReceiver receiver = new JacksonResultReceiver(jg);
      data.data(receiver, note -> notes.add(note));
      jg.flush();
      jg.close();
      final byte[] bytes = baos.toByteArray();
      if (!notes.isEmpty()) {
        log.warn("notes: {}", notes);
      }
      if (bytes.length == 0) {
        log.warn("null result");
        json = JsonNodeFactory.instance.objectNode();
      }
      else {
        json = DefaultZuluHttpEngine.this.responder.mapper().readValue(bytes, ObjectNode.class);
      }
    }
    catch (final IOException e) {
      throw new RuntimeException(e);
    }

    return new ZuluJacksonResult() {

      @Override
      public ObjectNode extensions() {
        return null;
      }

      @Override
      public List<ZuluWarning> errors() {
        return ImmutableList.<ZuluWarning>builder().addAll(data.errors()).addAll(notes).build();
      }

      @Override
      public ObjectNode data() {
        return json;
      }

      @Override
      public String toString() {
        return "mappedResult(" + data + "): " + this.errors();
      }

    };

  }

}


text:
let _ =require('lodash')

let defaultOptions = {};

module.exports = class Map {
    constructor(svg, colours, data, options) {
        this.svg = svg;
        this.container = svg.append('g');

        this.colours = colours;

        this.options = _.extend({}, defaultOptions, options);

        this.horizontalScale = d3.scale.linear()
            .domain([16.18, 16.58])
            .range([0, 800]);

        this.verticalScale = d3.scale.linear()
            .domain([48.325, 48.055])
            .range([0, 800]);

        this.lineGenerator = d3.svg.line()
            .x((d) => this.horizontalScale(d.x))
            .y((d) => this.verticalScale(d.y));

        this.updateData(data);
    }

    highlightCandidate(candidate) {
        this.container.selectAll('path')
            .attr({
                fill: (datum) => this.colours[candidate],
                'fill-opacity': (datum)=> datum.sprengel.result[candidate] / _.sum(_.values(datum.sprengel.result))
        });
    }

    resetColours() {
        this.container.selectAll('path')
            .attr({
                fill: (datum) => this.colours[this.maximumKey(datum.sprengel.result)],
                'fill-opacity': 1
            });
    }

    updateData(data) {
        let mapData = this.container.selectAll('path').data(data);

        mapData.enter()
            .append('path')
            .attr({
                d: (datum) => this.lineGenerator(datum.coordinates) + "Z"
            });

        mapData
            .attr({
                'data-bezirk': (datum) => datum.bezirk,
                'data-sprengel': (datum) => datum.sprengel
            });

        mapData.exit()
            .remove();

        this.resetColours();
    }

    maximumKey(target) {
        let currentMax, current;

        for(var key in target) {
            if(currentMax == undefined || target[key] >= currentMax) {
                current = key;
                currentMax = target[key];
            }
        }

        return current;
    }

    on(eventName, handler) {
        this.container.selectAll('path')
            .on(eventName, handler);

        return this;
    }

    off(handler) {
        this.container.selectAll('path')
            .off(eventName, handler);

        return this;
    }
};


text:
package com.github.tdesjardins.ol3.demo.client.example;

import com.github.desjardins.elemental.XMLSerializer;
import com.github.tdesjardins.ol3.demo.client.constants.DemoConstants;
import com.github.tdesjardins.ol3.demo.client.utils.DemoUtils;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.Window;

import elemental2.dom.Node;
import ol.Coordinate;
import ol.Feature;
import ol.Map;
import ol.MapOptions;
import ol.OLFactory;
import ol.View;
import ol.format.GeoJson;
import ol.format.Wfs;
import ol.format.WfsWriteFeatureOptions;
import ol.format.filter.IsLike;
import ol.layer.VectorLayerOptions;
import ol.source.Vector;

/**
 * WFS example with filter.
 *
 * @author Tino Desjardins
 *
 */
public class WfsExample implements Example {

    /* (non-Javadoc)
     * @see de.desjardins.ol3.demo.client.example.Example#show()
     */
    @Override
    public void show(String exampleId) {

        // create a vector layer
        Vector vectorSource = new Vector();
        VectorLayerOptions vectorLayerOptions = new VectorLayerOptions();
        vectorLayerOptions.setSource(vectorSource);
        ol.layer.Vector wfsLayer = new ol.layer.Vector(vectorLayerOptions);

        // create a view
        View view = new View();

        Coordinate centerCoordinate = new Coordinate(-8908887.277395891, 5381918.072437216);
        view.setCenter(centerCoordinate);
        view.setZoom(12);
        view.setMaxZoom(19);

        // create the map
        MapOptions mapOptions = OLFactory.createOptions();
        mapOptions.setTarget(exampleId);
        mapOptions.setView(view);

        Map map = new Map(mapOptions);

        map.addLayer(DemoUtils.createOsmLayer());
        map.addLayer(wfsLayer);

        Wfs wfs = new Wfs();
        WfsWriteFeatureOptions wfsWriteFeatureOptions = new WfsWriteFeatureOptions();

        String[] featureTypes = {"water_areas"};
        wfsWriteFeatureOptions.setSrsName(DemoConstants.EPSG_3857);
        wfsWriteFeatureOptions.setFeaturePrefix("osm");
        wfsWriteFeatureOptions.setFeatureNS("http://openstreemap.org");
        wfsWriteFeatureOptions.setFeatureTypes(featureTypes);

        // set a filter
        wfsWriteFeatureOptions.setFilter(new IsLike("name", "Mississippi*"));
        wfsWriteFeatureOptions.setOutputFormat("application/json");

        // create WFS-XML node
        Node wfsNode = wfs.writeGetFeature(wfsWriteFeatureOptions);

        RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, "https://ahocevar.com/geoserver/wfs");
        requestBuilder.setRequestData(new XMLSerializer().serializeToString(wfsNode));
        requestBuilder.setCallback(new RequestCallback() {

            @Override
            public void onResponseReceived(com.google.gwt.http.client.Request request, Response response) {

                GeoJson geoJson = new GeoJson();
                Feature[] features = geoJson.readFeatures(response.getText());

                vectorSource.addFeatures(features);
                map.getView().fit(vectorSource.getExtent());
            }

            @Override
            public void onError(com.google.gwt.http.client.Request request, Throwable exception) {
                Window.alert(exception.getMessage());
            }

        });

        try {
            requestBuilder.send();
        } catch (RequestException e) {
            Window.alert(e.getMessage());
        }

    }

}


text:
import indra.assemblers.english.assembler as ea
from indra.statements import *

def _substring_by_coords(text, coords):
    return text[coords[0]:coords[1]]

def test_agent_basic():
    ag = ea._assemble_agent_str(Agent('EGFR'))
    assert isinstance(ag, ea.AgentWithCoordinates)
    print(ag.agent_str)
    assert ag.agent_str == 'EGFR'
    assert _substring_by_coords(ag.agent_str, ag.coords) == 'EGFR'

def test_agent_mod():
    mc = ModCondition('phosphorylation')
    a = Agent('EGFR', mods=mc)
    ag = ea._assemble_agent_str(a)
    print(ag.agent_str)
    assert ag.agent_str == 'phosphorylated EGFR'
    assert _substring_by_coords(ag.agent_str, ag.coords) == 'EGFR'

def test_agent_mod2():
    mc = ModCondition('phosphorylation', 'tyrosine')
    a = Agent('EGFR', mods=mc)
    ag = ea._assemble_agent_str(a)
    print(ag.agent_str)
    assert ag.agent_str == 'tyrosine-phosphorylated EGFR'
    assert _substring_by_coords(ag.agent_str, ag.coords) == 'EGFR'

def test_agent_mod3():
    mc = ModCondition('phosphorylation', 'tyrosine', '1111')
    a = Agent('EGFR', mods=mc)
    ag = ea._assemble_agent_str(a)
    print(ag.agent_str)
    assert ag.agent_str == 'EGFR phosphorylated on Y1111'
    assert _substring_by_coords(ag.agent_str, ag.coords) == 'EGFR'

def test_agent_mods():
    mc1 = ModCondition('phosphorylation', 'tyrosine', '1111')
    mc2 = ModCondition('phosphorylation', 'tyrosine', '1234')
    a = Agent('EGFR', mods=[mc1, mc2])
    ag = ea._assemble_agent_str(a)
    print(ag.agent_str)
    assert ag.agent_str == 'EGFR phosphorylated on Y1111 and Y1234'
    assert _substring_by_coords(ag.agent_str, ag.coords) == 'EGFR'

def test_agent_mods2():
    mc1 = ModCondition('phosphorylation', 'tyrosine', '1111')
    mc2 = ModCondition('phosphorylation', 'tyrosine')
    a = Agent('EGFR', mods=[mc1, mc2])
    ag = ea._assemble_agent_str(a)
    print(ag.agent_str)
    assert ag.agent_str == 'EGFR phosphorylated on Y1111 and tyrosine'
    assert _substring_by_coords(ag.agent_str, ag.coords) == 'EGFR'

def test_agent_mods3():
    mc1 = ModCondition('phosphorylation', 'tyrosine', '1111')
    mc2 = ModCondition('phosphorylation')
    a = Agent('EGFR', mods=[mc1, mc2])
    ag = ea._assemble_agent_str(a)
    print(ag.agent_str)
    assert ag.agent_str == 'EGFR phosphorylated on Y1111 and an unknown residue'
    assert ag.agent_str[ag.coords[0]:ag.coords[1]] == 'EGFR'

def test_agent_mods_pos_only():
    mc1 = ModCondition('phosphorylation', None, '1111')
    a = Agent('EGFR', mods=[mc1])
    ag = ea._assemble_agent_str(a)
    print(ag.agent_str)
    assert ag.agent_str == 'EGFR phosphorylated on amino acid 1111'
    assert _substring_by_coords(ag.agent_str, ag.coords) == 'EGFR'

def test_agent_bound():
    bc = BoundCondition(Agent('EGF'), True)
    a = Agent('EGFR', bound_conditions=[bc])
    ag = ea._assemble_agent_str(a)
    print(ag.agent_str)
    assert ag.agent_str == 'EGFR bound to EGF'
    assert _substring_by_coords(ag.agent_str, ag.coords) == 'EGFR'

def test_agent_not_bound():
    bc = BoundCondition(Agent('EGF'), False)
    a = Agent('EGFR', bound_conditions=[bc])
    ag = ea._assemble_agent_str(a)
    print(ag.agent_str)
    assert ag.agent_str == 'EGFR not bound to EGF'
    assert _substring_by_coords(ag.agent_str, ag.coords) == 'EGFR'

def test_agent_bound_two():
    bc = BoundCondition(Agent('EGF'), True)
    bc2 = BoundCondition(Agent('EGFR'), True)
    a = Agent('EGFR', bound_conditions=[bc, bc2])
    ag = ea._assemble_agent_str(a)
    print(ag.agent_str)
    assert ag.agent_str == 'EGFR bound to EGF and EGFR'
    assert _substring_by_coords(ag.agent_str, ag.coords) == 'EGFR'

def test_agent_bound_three():
    bc = BoundCondition(Agent('EGF'), True)
    bc2 = BoundCondition(Agent('EGFR'), True)
    bc3 = BoundCondition(Agent('GRB2'), True)
    a = Agent('EGFR', bound_conditions=[bc, bc2, bc3])
    ag = ea._assemble_agent_str(a)
    print(ag.agent_str)
    assert ag.agent_str == 'EGFR bound to EGF, EGFR, and GRB2'
    assert _substring_by_coords(ag.agent_str, ag.coords) == 'EGFR'

def test_agent_bound_mixed():
    bc = BoundCondition(Agent('EGF'), True)
    bc2 = BoundCondition(Agent('EGFR'), False)
    a = Agent('EGFR', bound_conditions=[bc, bc2])
    ag = ea._assemble_agent_str(a)
    print(ag.agent_str)
    assert ag.agent_str == 'EGFR bound to EGF and not bound to EGFR'
    assert _substring_by_coords(ag.agent_str, ag.coords) == 'EGFR'

def test_phos_noenz():
    a = Agent('MAP2K1')
    st = Phosphorylation(None, a)
    sb = ea._assemble_modification(st)
    print(sb.sentence)
    assert sb.sentence == 'MAP2K1 is phosphorylated.'
    assert _substring_by_coords(sb.sentence, sb.agents[0].coords) == 'MAP2K1'

def test_phos_noenz2():
    a = Agent('MAP2K1')
    st = Phosphorylation(None, a, 'serine')
    sb = ea._assemble_modification(st)
    print(sb.sentence)
    assert sb.sentence == 'MAP2K1 is phosphorylated on serine.'
    assert _substring_by_coords(sb.sentence, sb.agents[0].coords) == 'MAP2K1'

def test_phos_noenz3():
    a = Agent('MAP2K1')
    st = Phosphorylation(None, a, 'serine', '222')
    sb = ea._assemble_modification(st)
    print(sb.sentence)
    assert sb.sentence == 'MAP2K1 is phosphorylated on S222.'
    assert _substring_by_coords(sb.sentence, sb.agents[0].coords) == 'MAP2K1'

def test_phos_enz():
    a = Agent('MAP2K1')
    b = Agent('BRAF')
    st = Phosphorylation(b, a, 'serine', '222')
    sb = ea._assemble_modification(st)
    print(sb.sentence)
    assert sb.sentence == 'BRAF phosphorylates MAP2K1 on S222.'
    assert _substring_by_coords(sb.sentence, sb.agents[0].coords) == 'BRAF'
    assert _substring_by_coords(sb.sentence, sb.agents[1].coords) == 'MAP2K1'

def test_phos_indirect():
    a = Agent('MAP2K1')
    b = Agent('BRAF')
    ev = Evidence(epistemics={'direct': False})
    st = Phosphorylation(b, a, 'serine', '222', evidence=[ev])
    sb = ea._assemble_modification(st)
    print(sb.sentence)
    assert sb.sentence == 'BRAF leads to the phosphorylation of MAP2K1 on S222.'
    assert _substring_by_coords(sb.sentence, sb.agents[0].coords) == 'BRAF'
    assert _substring_by_coords(sb.sentence, sb.agents[1].coords) == 'MAP2K1'

def test_phos_enz2():
    a = Agent('MAP2K1')
    b = Agent('PP2A')
    st = Dephosphorylation(b, a, 'serine', '222')
    sb = ea._assemble_modification(st)
    print(sb.sentence)
    assert sb.sentence == 'PP2A dephosphorylates MAP2K1 on S222.'
    assert _substring_by_coords(sb.sentence, sb.agents[0].coords) == 'PP2A'
    assert _substring_by_coords(sb.sentence, sb.agents[1].coords) == 'MAP2K1'

def test_dephos_no_residue():
    a = Agent('MAP2K1')
    b = Agent('PP2A')
    st = Dephosphorylation(b, a, None, '222')
    sb = ea._assemble_modification(st)
    print(sb.sentence)
    assert sb.sentence == 'PP2A dephosphorylates MAP2K1 at position 222.'
    assert _substring_by_coords(sb.sentence, sb.agents[0].coords) == 'PP2A'
    assert _substring_by_coords(sb.sentence, sb.agents[1].coords) == 'MAP2K1'

def test_ubiq_stmt():
    st = Ubiquitination(Agent('X'), Agent('Y'))
    sb = ea._assemble_modification(st)
    print(sb.sentence)
    assert sb.sentence == 'X ubiquitinates Y.'
    assert _substring_by_coords(sb.sentence, sb.agents[0].coords) == 'X'
    assert _substring_by_coords(sb.sentence, sb.agents[1].coords) == 'Y'

def test_deubiq_stmt():
    st = Deubiquitination(Agent('X'), Agent('Y'))
    sb = ea._assemble_modification(st)
    print(sb.sentence)
    assert sb.sentence == 'X deubiquitinates Y.'
    assert _substring_by_coords(sb.sentence, sb.agents[0].coords) == 'X'
    assert _substring_by_coords(sb.sentence, sb.agents[1].coords) == 'Y'

def test_deubiq_noenz():
    st = Deubiquitination(None, Agent('Y'))
    sb = ea._assemble_modification(st)
    print(sb.sentence)
    assert sb.sentence == 'Y is deubiquitinated.'
    assert _substring_by_coords(sb.sentence, sb.agents[0].coords) == 'Y'

def test_complex_one():
    a = Agent('MAP2K1')
    b = Agent('BRAF')
    st = Complex([a, b])
    sb = ea._assemble_complex(st)
    print(sb.sentence)
    assert sb.sentence == 'MAP2K1 binds BRAF.'
    assert _substring_by_coords(sb.sentence, sb.agents[0].coords) == 'MAP2K1'
    assert _substring_by_coords(sb.sentence, sb.agents[1].coords) == 'BRAF'

def test_complex_more():
    a = Agent('MAP2K1')
    b = Agent('BRAF')
    c = Agent('RAF1')
    st = Complex([a, b, c])
    sb = ea._assemble_complex(st)
    print(sb.sentence)
    assert sb.sentence == 'MAP2K1 binds BRAF and RAF1.'
    assert _substring_by_coords(sb.sentence, sb.agents[0].coords) == 'MAP2K1'
    assert _substring_by_coords(sb.sentence, sb.agents[1].coords) == 'BRAF'
    assert _substring_by_coords(sb.sentence, sb.agents[2].coords) == 'RAF1'

def test_assemble_one():
    a = Agent('MAP2K1')
    b = Agent('PP2A')
    st = Dephosphorylation(b, a, 'serine', 222)
    s = _stmt_to_text(st)
    assert s == 'PP2A dephosphorylates MAP2K1 on S222.'

def test_assemble_more():
    a = Agent('MAP2K1')
    b = Agent('PP2A')
    st1 = Dephosphorylation(b, a, 'serine', 222)
    b = Agent('BRAF')
    c = Agent('RAF1')
    st2 = Complex([a, b, c])
    e = ea.EnglishAssembler()
    e.add_statements([st1, st2])
    s = e.make_model()
    print(s)
    assert s == \
        'PP2A dephosphorylates MAP2K1 on S222. MAP2K1 binds BRAF and RAF1.'
    assert _substring_by_coords(s, e.stmt_agents[0][0].coords) == 'PP2A'
    assert _substring_by_coords(s, e.stmt_agents[0][1].coords) == 'MAP2K1'
    assert _substring_by_coords(s, e.stmt_agents[1][0].coords) == 'MAP2K1'
    assert _substring_by_coords(s, e.stmt_agents[1][1].coords) == 'BRAF'
    assert _substring_by_coords(s, e.stmt_agents[1][2].coords) == 'RAF1'

def test_autophos():
    a = Agent('EGFR')
    st = Autophosphorylation(a, 'Y')
    s = _stmt_to_text(st)
    assert s == 'EGFR phosphorylates itself on tyrosine.'

def test_activation():
    st = Activation(Agent('MEK'), Agent('ERK'))
    s = _stmt_to_text(st)
    assert s == 'MEK activates ERK.'

def test_inhibition():
    st = Inhibition(Agent('MEK'), Agent('ERK'))
    s = _stmt_to_text(st)
    assert s == 'MEK inhibits ERK.'

def test_regulateamount():
    st = IncreaseAmount(Agent('TP53'), Agent('MDM2'))
    s = _stmt_to_text(st)
    assert s == 'TP53 increases the amount of MDM2.'
    st = DecreaseAmount(Agent('TP53'), Agent('MDM2'))
    s = _stmt_to_text(st)
    assert s == 'TP53 decreases the amount of MDM2.'
    st = DecreaseAmount(None, Agent('MDM2'))
    s = _stmt_to_text(st)
    assert s == 'MDM2 is degraded.'
    st = IncreaseAmount(None, Agent('MDM2'))
    s = _stmt_to_text(st)
    assert s == 'MDM2 is produced.'

def test_agent_loc():
    a = Agent('BRAF', location='cytoplasm')
    ag = ea._assemble_agent_str(a)
    print(ag.agent_str)
    assert ag.agent_str == 'BRAF in the cytoplasm'
    assert _substring_by_coords(ag.agent_str, ag.coords) == 'BRAF'

def test_agent_mut():
    a = Agent('BRAF', mutations=[MutCondition('600','V', 'E')])
    ag = ea._assemble_agent_str(a)
    print(ag.agent_str)
    assert ag.agent_str == 'BRAF-V600E'
    assert _substring_by_coords(ag.agent_str, ag.coords) == 'BRAF'

def test_agent_mut_plus():
    a = Agent('BRAF', mutations=[MutCondition('600','V', 'E')],
              location='nucleus')
    ag = ea._assemble_agent_str(a)
    print(ag.agent_str)
    assert ag.agent_str == 'BRAF-V600E in the nucleus'
    assert _substring_by_coords(ag.agent_str, ag.coords) == 'BRAF'

def test_agent_activity():
    a = Agent('BRAF', activity=ActivityCondition('activity', True))
    ag = ea._assemble_agent_str(a)
    print(ag.agent_str)
    assert ag.agent_str == 'active BRAF'
    assert _substring_by_coords(ag.agent_str, ag.coords) == 'BRAF'

def test_agent_activity_stmt():
    braf = Agent('BRAF', activity=ActivityCondition('activity', True))
    mek = Agent('MAP2K1')
    st = Activation(braf, mek)
    e = ea.EnglishAssembler()
    e.add_statements([st])
    s = e.make_model()
    print(s)
    assert s == 'Active BRAF activates MAP2K1.'
    assert _substring_by_coords(s, e.stmt_agents[0][0].coords) == 'BRAF'
    assert _substring_by_coords(s, e.stmt_agents[0][1].coords) == 'MAP2K1'

def test_translocation():
    st1 = Translocation(Agent('FOXO3A'))
    st2 = Translocation(Agent('FOXO3A'), 'cytoplasm')
    st3 = Translocation(Agent('FOXO3A'), None, 'nucleus')
    st4 = Translocation(Agent('FOXO3A'), 'cytoplasm', 'nucleus')
    e = ea.EnglishAssembler()
    e.add_statements([st1])
    s = e.make_model()
    assert s == 'FOXO3A translocates.'
    assert _substring_by_coords(s, e.stmt_agents[0][0].coords) == 'FOXO3A'
    e = ea.EnglishAssembler()
    e.add_statements([st2])
    s = e.make_model()
    assert s == 'FOXO3A translocates from the cytoplasm.'
    assert _substring_by_coords(s, e.stmt_agents[0][0].coords) == 'FOXO3A'
    e = ea.EnglishAssembler()
    e.add_statements([st3])
    s = e.make_model()
    assert s == 'FOXO3A translocates to the nucleus.'
    assert _substring_by_coords(s, e.stmt_agents[0][0].coords) == 'FOXO3A'
    e = ea.EnglishAssembler()
    e.add_statements([st4])
    s = e.make_model()
    assert s == 'FOXO3A translocates from the cytoplasm to the nucleus.'
    assert _substring_by_coords(s, e.stmt_agents[0][0].coords) == 'FOXO3A'

def test_gef():
    st = Gef(Agent('SOS1'), Agent('KRAS'))
    s = _stmt_to_text(st)
    assert s == 'SOS1 is a GEF for KRAS.'

def test_gap():
    st = Gap(Agent('RASA1'), Agent('KRAS'))
    s = _stmt_to_text(st)
    assert s == 'RASA1 is a GAP for KRAS.'

def test_methylation():
    st = Methylation(None, Agent('SLF11'))
    s = _stmt_to_text(st)
    assert s == 'SLF11 is methylated.'

def test_generic_mod_state():
    mc = ModCondition('modification')
    st = Activation(Agent('MEK', mods=[mc]), Agent('ERK'))
    s = _stmt_to_text(st)
    assert s == 'Modified MEK activates ERK.'

def test_generic_mutation():
    mc = MutCondition(None, None, None)
    st = Activation(Agent('MEK', mutations=[mc]), Agent('ERK'))
    s = _stmt_to_text(st)
    assert s == 'Mutated MEK activates ERK.'

def test_activity_conditions():
    def to_english(act_type, is_act):
        ac = ActivityCondition(act_type, is_act)
        st = Activation(Agent('MEK', activity=ac), Agent('ERK'))
        s = _stmt_to_text(st)
        return s

    assert to_english('activity', True) == 'Active MEK activates ERK.'
    assert to_english('activity', False) == 'Inactive MEK activates ERK.'
    assert to_english('gtpbound', True) == \
        'GTP-bound active MEK activates ERK.'
    assert to_english('gtpbound', False) == \
        'GDP-bound inactive MEK activates ERK.'
    assert to_english('catalytic', False) == \
        'Catalytically inactive MEK activates ERK.'
    assert to_english('kinase', True) == \
        'Kinase-active MEK activates ERK.'
    assert to_english('gap', True) == \
        'GAP-active MEK activates ERK.'
    assert to_english('gef', False) == \
        'GEF-inactive MEK activates ERK.'

def test_conversion():
    st = Conversion(Agent('RAS'), [Agent('GTP')], [Agent('GDP')])
    s = _stmt_to_text(st)
    assert s == 'RAS catalyzes the conversion of GTP into GDP.'

    st = Conversion(Agent('RAS'), [Agent('GTP'), Agent('X')],
                    [Agent('GDP'), Agent('Y')])
    s = _stmt_to_text(st)
    assert s == 'RAS catalyzes the conversion of GTP and X into GDP and Y.'

    st = Conversion(None, [Agent('GTP'), Agent('X')], [Agent('GDP'), Agent('Y')])
    s = _stmt_to_text(st)
    assert s == 'GTP and X is converted into GDP and Y.'

def test_influence():
    st = Influence(Event(Concept('food')), Event(Concept('hunger'),
                                                 delta=QualitativeDelta(
                                                     polarity=-1)))
    s = _stmt_to_text(st)
    assert s == 'Food causes a decrease in hunger.', s

    st = Influence(Event(Concept('food'), delta=QualitativeDelta(
                                            polarity=1)),
                   Event(Concept('hunger'), delta=QualitativeDelta(
                                            polarity=-1)))
    s = _stmt_to_text(st)
    assert s == 'An increase in food causes a decrease in hunger.', s

    st = Influence(Event(Concept('food'), delta=QualitativeDelta(
                                            polarity=-1)),
                   Event(Concept('hunger'), delta=QualitativeDelta(
                                            polarity=1)))
    s = _stmt_to_text(st)
    assert s == 'A decrease in food causes an increase in hunger.', s

def test_association():
    st = Association([Event(Concept('food')), Event(Concept('hunger'))])
    s = _stmt_to_text(st)
    assert s == 'Food is associated with hunger.'

def test_active_form():
    st = ActiveForm(Agent('BRAF',
                          mods=[ModCondition('phosphorylation', 'T', '396')]),
                    'kinase', True)
    s = _stmt_to_text(st)
    assert s == 'BRAF phosphorylated on T396 is kinase-active.'

def test_get_base_verb():
    assert ea.statement_base_verb('inhibition') == 'inhibit'
    assert ea.statement_base_verb('dephosphorylation') == 'dephosphorylate'
    assert ea.statement_base_verb('complex') == 'bind'

def _stmt_to_text(st):
    e = ea.EnglishAssembler()
    e.add_statements([st])
    s = e.make_model()
    print(s)
    return s

def test_sentence_builder():
    sb = ea.SentenceBuilder()
    ac = ea.AgentWithCoordinates('BRAF', 'BRAF', {})
    sb.append(ac)
    assert len(sb.agents) == 1
    assert sb.sentence == 'BRAF'

    sb.prepend('phosphorylated ')
    assert sb.sentence == 'phosphorylated BRAF'
    assert sb.agents[0].coords == (15, 19), sb.agents[0].coords

    sb.prepend(ea.AgentWithCoordinates('active KRAS', 'KRAS', {}))
    assert sb.sentence == 'active KRAS phosphorylated BRAF', sb.sentence
    assert sb.agents[0].name == 'KRAS'
    assert sb.agents[1].name == 'BRAF'
    assert sb.agents[1].coords == (27, 31), sb.agents[1].coords

def test_negative_mod_condition():
    upgrb = Agent('GRB2', mods=[ModCondition('phosphorylation',
                                             None, None, False)])
    stmt = Activation(upgrb, Agent('SOS'))
    txt = _stmt_to_text(stmt)
    assert txt == 'Unphosphorylated GRB2 activates SOS.', txt


text:
/**
 *
 */
package test.service.impl.webhookservice;

import javastrava.config.JavastravaApplicationConfig;
import javastrava.model.webhook.StravaEventSubscription;
import javastrava.service.Strava;
import test.model.webhook.StravaEventSubscriptionTest;
import test.service.standardtests.ListMethodTest;
import test.service.standardtests.callbacks.ListCallback;
import test.service.standardtests.data.AthleteDataUtils;
import test.utils.TestUtils;

/**
 * <p>
 * Specific tests for {@link Strava#listSubscriptions(Integer, String) methods}
 * </p>
 *
 * @author Dan Shannon
 */
public class ListSubscriptionsTest extends ListMethodTest<StravaEventSubscription, Integer> {

	@Override
	protected Class<StravaEventSubscription> classUnderTest() {
		return StravaEventSubscription.class;
	}

	@Override
	protected Integer idInvalid() {
		return null;
	}

	@Override
	protected Integer idPrivate() {
		return null;
	}

	@Override
	protected Integer idPrivateBelongsToOtherUser() {
		return null;
	}

	@Override
	protected Integer idValidWithEntries() {
		return AthleteDataUtils.ATHLETE_AUTHENTICATED_ID;
	}

	@Override
	protected Integer idValidWithoutEntries() {
		return null;
	}

	@Override
	protected ListCallback<StravaEventSubscription, Integer> lister() {
		return ((strava, id) -> strava.listSubscriptions(TestUtils.STRAVA_APPLICATION_ID, TestUtils.STRAVA_CLIENT_SECRET));
	}

	@Override
	public void testInvalidId() throws Exception {
		// Can't run the test unless application has Strava's permission to access the webhooks endpoint
		if (JavastravaApplicationConfig.STRAVA_ALLOWS_WEBHOOKS_ENDPOINT) {

			super.testInvalidId();
		}
	}

	@Override
	public void testPrivateBelongsToOtherUser() throws Exception {
		// Can't run the test unless application has Strava's permission to access the webhooks endpoint
		if (JavastravaApplicationConfig.STRAVA_ALLOWS_WEBHOOKS_ENDPOINT) {

			super.testPrivateBelongsToOtherUser();
		}
	}

	@Override
	public void testPrivateWithNoViewPrivateScope() throws Exception {
		// Can't run the test unless application has Strava's permission to access the webhooks endpoint
		if (JavastravaApplicationConfig.STRAVA_ALLOWS_WEBHOOKS_ENDPOINT) {

			super.testPrivateWithNoViewPrivateScope();
		}
	}

	@Override
	public void testPrivateWithViewPrivateScope() throws Exception {
		// Can't run the test unless application has Strava's permission to access the webhooks endpoint
		if (JavastravaApplicationConfig.STRAVA_ALLOWS_WEBHOOKS_ENDPOINT) {

			super.testPrivateWithViewPrivateScope();
		}
	}

	@Override
	public void testValidParentWithEntries() throws Exception {
		// Can't run the test unless application has Strava's permission to access the webhooks endpoint
		if (JavastravaApplicationConfig.STRAVA_ALLOWS_WEBHOOKS_ENDPOINT) {

			super.testValidParentWithEntries();
		}
	}

	@Override
	public void testValidParentWithNoEntries() throws Exception {
		// Can't run the test unless application has Strava's permission to access the webhooks endpoint
		if (JavastravaApplicationConfig.STRAVA_ALLOWS_WEBHOOKS_ENDPOINT) {

			super.testValidParentWithNoEntries();
		}
	}

	@Override
	protected void validate(StravaEventSubscription object) {
		StravaEventSubscriptionTest.validate(object);
	}

}


text:
#include "oboe_common_OboeDebug_android.h"
#include "oboe_opensles_EngineOpenSLES_android.h"
#include "oboe_opensles_OpenSLESUtilities_android.h"

using namespace oboe;

EngineOpenSLES &EngineOpenSLES::getInstance() {
    static EngineOpenSLES sInstance;
    return sInstance;
}

SLresult EngineOpenSLES::open() {
    std::lock_guard<std::mutex> lock(mLock);

    SLresult result = SL_RESULT_SUCCESS;
    if (mOpenCount++ == 0) {

        // create engine
        result = slCreateEngine(&mEngineObject, 0, NULL, 0, NULL, NULL);
        if (SL_RESULT_SUCCESS != result) {
            LOGE("EngineOpenSLES - slCreateEngine() result:%s", getSLErrStr(result));
            goto error;
        }

        // realize the engine
        result = (*mEngineObject)->Realize(mEngineObject, SL_BOOLEAN_FALSE);
        if (SL_RESULT_SUCCESS != result) {
            LOGE("EngineOpenSLES - Realize() engine result:%s", getSLErrStr(result));
            goto error;
        }

        // get the engine interface, which is needed in order to create other objects
        result = (*mEngineObject)->GetInterface(mEngineObject, SL_IID_ENGINE, &mEngineInterface);
        if (SL_RESULT_SUCCESS != result) {
            LOGE("EngineOpenSLES - GetInterface() engine result:%s", getSLErrStr(result));
            goto error;
        }
    }

    return result;

error:
    close();
    return result;
}

void EngineOpenSLES::close() {
    std::lock_guard<std::mutex> lock(mLock);
    if (--mOpenCount == 0) {
        if (mEngineObject != nullptr) {
            (*mEngineObject)->Destroy(mEngineObject);
            mEngineObject = nullptr;
            mEngineInterface = nullptr;
        }
    }
}

SLresult EngineOpenSLES::createOutputMix(SLObjectItf *objectItf) {
    return (*mEngineInterface)->CreateOutputMix(mEngineInterface, objectItf, 0, 0, 0);
}

SLresult EngineOpenSLES::createAudioPlayer(SLObjectItf *objectItf,
                                           SLDataSource *audioSource,
                                           SLDataSink *audioSink) {

    const SLInterfaceID ids[] = {SL_IID_BUFFERQUEUE, SL_IID_ANDROIDCONFIGURATION};
    const SLboolean reqs[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE};

    return (*mEngineInterface)->CreateAudioPlayer(mEngineInterface, objectItf, audioSource,
                                                  audioSink,
                                                  sizeof(ids) / sizeof(ids[0]), ids, reqs);
}

SLresult EngineOpenSLES::createAudioRecorder(SLObjectItf *objectItf,
                                             SLDataSource *audioSource,
                                             SLDataSink *audioSink) {

    const SLInterfaceID ids[] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_ANDROIDCONFIGURATION };
    const SLboolean reqs[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE};

    return (*mEngineInterface)->CreateAudioRecorder(mEngineInterface, objectItf, audioSource,
                                                    audioSink,
                                                    sizeof(ids) / sizeof(ids[0]), ids, reqs);
}


text:
set -e # Exit on any error
. ${srcdir}/tests/common.sh

${VALIDATE} -validate import-export


text:
package org.jai.search.model;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

public class Category {
	private final String name;

	private final String type;

	private final Category parentCategory;

	public Category(final String catName, final Category parent,
			final String catType) {
		this.name = catName;
		this.parentCategory = parent;
		this.type = catType;
	}

	public String getName() {
		return name;
	}

	public Category getParentCategory() {
		return parentCategory;
	}

	public String getType() {
		return type;
	}

	@Override
	public int hashCode() {
		return new HashCodeBuilder().append(name).hashCode();
	}

	@Override
	public boolean equals(final Object obj) {
		final Category other = (Category) obj;
		return new EqualsBuilder().append(name, other.getName()).isEquals();
	}

	@Override
	public String toString() {
		return new ToStringBuilder(this).append(name).append(type).toString();
	}
}


text:
package it.sephiroth.android.library.floatingmenu;

/**
 * Created by alessandro on 24/05/14.
 */
public class FloatingActionItem {
	int id;
	int resId;
	int delay = 0;
	int paddingTop = 0;
	int paddingBottom = 0;
	int paddingLeft = 0;
	int paddingRight = 0;
	int backgroundResId;

	static public class Builder {
		int id;
		int resId = - 1;
		int delay = 0;
		int paddingTop = 0;
		int paddingBottom = 0;
		int paddingLeft = 0;
		int paddingRight = 0;
		int backgroundResId = 0;

		/**
		 * @param id unique id to be used with the
		 *           {@link it.sephiroth.android.library.floatingmenu.FloatingActionMenu.OnItemClickListener}
		 */
		public Builder(int id) {
			this.id = id;
		}

		/**
		 * Assign a custom background resource
		 */
		public Builder withBackgroundResId(int resId) {
			this.backgroundResId = resId;
			return this;
		}

		/**
		 * Image drawable resource-id
		 * @param resId
		 * @return
		 */
		public Builder withResId(final int resId) {
			this.resId = resId;
			return this;
		}

		/**
		 * Show/Hide delay time
		 * @param delay
		 * @return
		 */
		public Builder withDelay(final int delay) {
			this.delay = delay;
			return this;
		}

		/**
		 * Image padding
		 * @param left
		 * @param top
		 * @param right
		 * @param bottom
		 * @return
		 */
		public Builder withPadding(int left, int top, int right, int bottom) {
			this.paddingBottom = bottom;
			this.paddingLeft = left;
			this.paddingRight = right;
			this.paddingTop = top;
			return this;
		}

		/**
		 * Image padding, applied to all the padding directions
		 * @param padding
		 * @return
		 */
		public Builder withPadding(int padding) {
			return withPadding(padding, padding, padding, padding);
		}

		public FloatingActionItem build() {
			if (resId == - 1) throw new IllegalArgumentException("resId missing");
			FloatingActionItem item = new FloatingActionItem();
			item.id = id;
			item.resId = resId;
			item.delay = delay;
			item.paddingBottom = paddingBottom;
			item.paddingLeft = paddingLeft;
			item.paddingRight = paddingRight;
			item.paddingTop = paddingTop;
			item.backgroundResId = backgroundResId;
			return item;
		}
	}
}


text:
//
// Created by machiry on 12/27/16.
//

#include "bug_detectors/TaintedPointerDereference.h"
#include "bug_detectors/warnings/VulnerabilityWarning.h"

using namespace llvm;

#include "TaintUtils.h"

namespace DRCHECKER {

/*#define DEBUG_LOAD_INSTR
#define DEBUG_STORE_INSTR*/
#define ONLY_ONE_WARNING
#define NO_POINTER_CHECK

    void TaintedPointerDereference::visitLoadInst(LoadInst &I) {
        // warning already raised for this instruction.
        if(this->warnedInstructions.find(&I) != this->warnedInstructions.end()) {
            return;
        }
#ifdef DEBUG_LOAD_INSTR
        dbgs() << TAG << " Visiting Load Instruction:";
        I.print(dbgs());
        dbgs() << "\n";
#endif
        Value *srcPointer = I.getPointerOperand();
        std::set<TaintFlag*> *srcTaintInfo = TaintUtils::getTaintInfo(this->currState,
                                                                      this->currFuncCallSites,
                                                                      srcPointer);
        if(srcTaintInfo == nullptr) {
            srcPointer = srcPointer->stripPointerCasts();
            srcTaintInfo = TaintUtils::getTaintInfo(this->currState,
                                                    this->currFuncCallSites,
                                                    srcPointer);
        }

        // OK, the src pointer is tainted.
        // we are trying to dereference tainted pointer.
        if(srcTaintInfo != nullptr) {
            for(TaintFlag *currFlag:*srcTaintInfo) {
                if(currFlag->isTainted()) {
                    std::string warningMsg = "Trying to read from a user pointer.";
                    VulnerabilityWarning *currWarning = new VulnerabilityWarning(this->currFuncCallSites,
                                                                                &(currFlag->instructionTrace),
                                                                                warningMsg, &I,
                                                                                TAG);
                    this->currState.addVulnerabilityWarning(currWarning);
                    if(this->warnedInstructions.find(&I) == this->warnedInstructions.end()) {
                        this->warnedInstructions.insert(&I);
                    }
#ifdef ONLY_ONE_WARNING
                    return;
#endif
                }
            }
        }

    }

    void TaintedPointerDereference::visitStoreInst(StoreInst &I) {
        // warning already raised for this instruction.
        if(this->warnedInstructions.find(&I) != this->warnedInstructions.end()) {
            return;
        }
#ifdef DEBUG_STORE_INSTR
        dbgs() << TAG << " Visiting Store Instruction:";
        I.print(dbgs());
        dbgs() << "\n";
#endif
        Value *srcPointer = I.getPointerOperand();
        std::set<TaintFlag*> *srcTaintInfo = TaintUtils::getTaintInfo(this->currState,
                                                                      this->currFuncCallSites,
                                                                      srcPointer);
        if(srcTaintInfo == nullptr) {
            srcPointer = srcPointer->stripPointerCasts();
            srcTaintInfo = TaintUtils::getTaintInfo(this->currState,
                                                    this->currFuncCallSites,
                                                    srcPointer);
        }

        // OK, the src pointer is tainted.
        // we are trying to dereference tainted pointer.
        if(srcTaintInfo != nullptr) {
            for(TaintFlag *currFlag:*srcTaintInfo) {
                if(currFlag->isTainted()) {
                    std::string warningMsg = "Trying to write to a user pointer.";
                    VulnerabilityWarning *currWarning = new VulnerabilityWarning(this->currFuncCallSites,
                                                                                &(currFlag->instructionTrace),
                                                                                warningMsg, &I,
                                                                                TAG);
                    this->currState.addVulnerabilityWarning(currWarning);
                    if(this->warnedInstructions.find(&I) == this->warnedInstructions.end()) {
                        this->warnedInstructions.insert(&I);
                    }
#ifdef ONLY_ONE_WARNING
                    return;
#endif
                }
            }
        }
    }

    void TaintedPointerDereference::visitGetElementPtrInst(GetElementPtrInst &I) {
#ifdef NO_POINTER_CHECK
        return;
#endif
        // warning already raised for this instruction.
        if(this->warnedInstructions.find(&I) != this->warnedInstructions.end()) {
            return;
        }

#ifdef DEBUG_STORE_INSTR
        dbgs() << TAG << " Visiting GetElementPtr Instruction:";
        I.print(dbgs());
        dbgs() << "\n";
#endif
        std::set<TaintFlag*> resultTaintFlags;
        for(unsigned i=0; i<I.getNumOperands();i++) {
            Value *currOp = I.getOperand(i);
            std::set<TaintFlag*> *srcTaintInfo = TaintUtils::getTaintInfo(this->currState,
                                                                          this->currFuncCallSites,
                                                                          currOp);
            if(srcTaintInfo == nullptr) {
                srcTaintInfo = TaintUtils::getTaintInfo(this->currState,
                                                        this->currFuncCallSites,
                                                        currOp->stripPointerCasts());
            }
            if(srcTaintInfo != nullptr) {
                resultTaintFlags.insert(srcTaintInfo->begin(), srcTaintInfo->end());
            }

        }

        // OK, the src pointer is tainted.
        // we are trying to dereference tainted pointer.
        for(TaintFlag *currFlag:resultTaintFlags) {
            if(currFlag->isTainted()) {
                std::string warningMsg = "Trying to use tainted value as index.";
                VulnerabilityWarning *currWarning = new VulnerabilityWarning(this->currFuncCallSites,
                                                                             &(currFlag->instructionTrace),
                                                                             warningMsg, &I,
                                                                             TAG);
                this->currState.addVulnerabilityWarning(currWarning);
                if(this->warnedInstructions.find(&I) == this->warnedInstructions.end()) {
                    this->warnedInstructions.insert(&I);
                }
#ifdef ONLY_ONE_WARNING
                return;
#endif
            }
        }
    }

    VisitorCallback* TaintedPointerDereference::visitCallInst(CallInst &I, Function *targetFunction,
                                                              std::vector<Instruction *> *oldFuncCallSites,
                                                              std::vector<Instruction *> *currFuncCallSites) {
        if(!targetFunction->isDeclaration()) {
            // only if the function has source.

            TaintedPointerDereference *newVis = new TaintedPointerDereference(this->currState, targetFunction,
                                                                              currFuncCallSites, nullptr);

            return newVis;
        }
        return nullptr;
    }

}