text:
package tv.dyndns.kishibe.qmaclone.server.sns;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import tv.dyndns.kishibe.qmaclone.client.packet.PacketProblem;
import tv.dyndns.kishibe.qmaclone.server.database.Database;
import tv.dyndns.kishibe.qmaclone.server.database.DatabaseException;
import tv.dyndns.kishibe.qmaclone.server.util.Downloader;
import tv.dyndns.kishibe.qmaclone.server.util.DownloaderException;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
import com.restfb.DefaultFacebookClient;
import com.restfb.Parameter;
import com.restfb.Version;
import com.restfb.types.FacebookType;

public class FacebookClient implements SnsClient {
  private static final Logger logger = Logger.getLogger(FacebookClient.class.getName());
  private final Database database;
  private final Downloader downloader;

  @Inject
  public FacebookClient(Database database, Downloader downloader) {
    this.database = Preconditions.checkNotNull(database);
    this.downloader = Preconditions.checkNotNull(downloader);
  }

  @Override
  public void postProblem(PacketProblem problem) {
    String problemReportSentence = problem.getProblemReportSentence();
    String message = "問題番号" + problem.id + ":" + problemReportSentence
        + " http://kishibe.dyndns.tv/qmaclone/";
    post(message);
  }

  @Override
  public void postThemeModeUpdate(String theme) {
    String message = "テーマモード 「" + theme + "」 が更新されました" + " http://kishibe.dyndns.tv/qmaclone/";
    post(message);
  }

  private void post(String message) {
    String accessToken = getPageAccessToken();
    com.restfb.FacebookClient facebookClient = new DefaultFacebookClient(accessToken,
        Version.UNVERSIONED);
    facebookClient.publish("me/feed", FacebookType.class, Parameter.with("message", message));
  }

  @Override
  public void followBack() {
    throw new UnsupportedOperationException();
  }

  @VisibleForTesting
  String getPageAccessToken() {
    String accessToken;
    try {
      accessToken = database.getPassword("facebook_access_token");
    } catch (DatabaseException e) {
      logger.log(Level.WARNING, "Failed to get the access token from the database.", e);
      return null;
    }

    URL url;
    try {
      url = new URL("https://graph.facebook.com/1060467615/accounts?access_token=" + accessToken);
    } catch (MalformedURLException e) {
      logger.log(Level.WARNING, "URLオブジェクトの構築に失敗しました", e);
      return null;
    }

    String json;
    try {
      json = downloader.downloadAsString(url);
    } catch (DownloaderException e) {
      logger.log(Level.WARNING, "ページアクセストークンの取得に失敗しました", e);
      return null;
    }

    List<String> elements = ImmutableList.copyOf(json.replaceAll("\\s", "").split("\""));
    int accessTokenIndex = elements.indexOf("access_token");
    if (accessTokenIndex == -1) {
      return null;
    }
    return elements.get(accessTokenIndex + 2);
  }
}


text:
package com.sun.xml.internal.ws.wsdl;

import com.sun.istack.internal.NotNull;

import javax.xml.namespace.QName;

/**
 * This class models the Operation Signature as defined by WS-I BP ( 1.2 or 2.0) to use wsa:Action and payload QName to
 * identify the corresponding wsdl operation from a request SOAP Message.
 *
 * @author Rama Pulavarthi
 */
public class ActionBasedOperationSignature {
    private final String action;
    private final QName payloadQName;
    public ActionBasedOperationSignature(@NotNull String action, @NotNull QName payloadQName) {
        this.action = action;
        this.payloadQName = payloadQName;
    }

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

        ActionBasedOperationSignature that = (ActionBasedOperationSignature) o;

        if (!action.equals(that.action)) return false;
        if (!payloadQName.equals(that.payloadQName)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = action.hashCode();
        result = 31 * result + payloadQName.hashCode();
        return result;
    }

}

redpajama_set_name: RedPajamaGithub


text:
var log = require('../../Logger')('base_schema_activity');
var extend = require('mongoose-schema-extend');

var DatesSchema = require('./dates');

var ActivitySchema = DatesSchema.extend({
  title: {
    type: String,
    required: true
  },
  description: String
});

module.exports = ActivitySchema;


text:
/**
 * @since 2016-03-02 18:00
 * @author vivaxy
 */

const path = require('path');
const koaRoute = require('koa-router')();

const configKeys = require('../constant/config.js');

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

const loadRoutes = () => {
  const directory = config.get(configKeys.DIRECTORY);
  const file = path.join(directory, 'here.js');
  const routeList = require(file);
  routeList.forEach((route) => {
    koaRoute[route.method](route.path, require('./log.js'), async function(ctx) {
      ctx.body = route.data.apply(ctx, arguments);
    });
  });
};

module.exports = (server) => {
  loadRoutes();

  server.use(koaRoute.routes());
  server.use(koaRoute.allowedMethods());

  return async function(ctx, next) {
    await next();
  };
};


text:
#include "config.h"
#include "core/rendering/RenderApplet.h"

#include "core/html/HTMLAppletElement.h"

namespace WebCore {

RenderApplet::RenderApplet(HTMLAppletElement* applet)
    : RenderEmbeddedObject(applet)
{
    setInline(true);
}

RenderApplet::~RenderApplet()
{
}

} // namespace WebCore


text:
namespace HicknHack.Twofold.Abstractions
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Text;
    using SourceMapping;

    public class ConsoleMessageHandler : IMessageHandler
    {
        public void Message(TraceLevel level, string text, string file, TextPosition position)
        {
            string file_ = file ?? string.Empty;

            string position_ = string.Empty;
            var positionBuilder = new StringBuilder();
            if (position.IsValid)
            {
                positionBuilder
                    .Append("(")
                    .Append(position.Line).Append(",").Append(position.Column)
                    .Append(")");
            }
            position_ = positionBuilder.ToString();

            string level_ = string.Empty;
            switch (level)
            {
                case TraceLevel.Verbose:
                    level_ = "VER";
                    break;
                case TraceLevel.Info:
                    level_ = "INF";
                    break;
                case TraceLevel.Warning:
                    level_ = "WRN";
                    break;
                case TraceLevel.Error:
                    level_ = "ERR";
                    break;
                default:
                    Debug.Assert(false, $"Unhandled case: {level}");
                    break;
            }

            string text_ = text ?? string.Empty;

            Console.Error.WriteLine($"{file_}{position_}: {level_}: {text_}");
        }

        public void StackTrace(List<StackFrame> frames)
        {
            var sb = new StringBuilder();
            foreach (StackFrame frame in frames)
            {
                sb.Clear();
                sb.Append(' ', 4).Append("at ").Append(frame.Method ?? string.Empty);
                if (string.IsNullOrEmpty(frame.File) == false)
                {
                    sb.Append(" in ").Append(frame.File);
                    if (frame.Line.HasValue)
                    {
                        sb.Append(" (").Append(frame.Line);
                        if (frame.Column.HasValue)
                        {
                            sb.Append(",").Append(frame.Column);
                        }

                        sb.Append(")");
                    }
                }

                Console.Error.WriteLine(sb.ToString());
            }
        }
    }
}


text:
"""
@author: ondrej-tucek
@date: 2016-02-14
"""

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
import matplotlib.cm as cm
import pylab as plot

def plot_variable_importance(feature_importance, names_cols, save_name, save):
    """Show Variable importance graph."""

    # scale by max importance first 20 variables in column names
    feature_importance = feature_importance / feature_importance.max()
    sorted_idx = np.argsort(feature_importance)[::-1][:20]
    barPos = np.arange(sorted_idx.shape[0]) + .8
    barPos = barPos[::-1]

    #plot.figure(num=None, facecolor='w', edgecolor='r')
    plot.figure(num=None, facecolor='w')
    plot.barh(barPos, feature_importance[sorted_idx]*100, align='center')
    plot.yticks(barPos, names_cols[sorted_idx])
    plot.xticks(np.arange(0, 120, 20), \
      ['0 %', '20 %', '40 %', '60 %', '80 %', '100 %'])
    plot.margins(0.02)
    plot.subplots_adjust(bottom=0.15)

    plot.title('Variable Importance')

    if save:
	plot.savefig(save_name, bbox_inches='tight', dpi = 300)
	plot.close("all")
    else:
	plot.show()

def plot_confusion_matrix(conf_mat, classes, save_name, save):
    """Show correctly color of cell in Confusion matrix."""

    N, cbar_label, fake_mat = get_data_to_plot(conf_mat)
    cmap = discrete_cmap(N, 'Blues')

    fig, ax = plt.subplots(num=None, facecolor='w')
    ax.imshow(fake_mat, interpolation='nearest', cmap=cmap, vmin=0, vmax=N)
    for i in range(conf_mat.shape[0]):
	for j in range(conf_mat.shape[1]):
	    ax.text(x=j, y=i, s=conf_mat[i, j], va='center', ha='center')

    ax.set_xticks(range(len(classes)))
    #tick_marks = np.arange(len(conf_mat.columns))
    #ax.set_xticks(tick_marks, conf_mat.columns, rotation=45)
    ax.set_xticklabels(classes)
    ax.xaxis.set_ticks_position("bottom")
    ax.set_yticks(range(len(classes)))
    ax.set_yticklabels(classes)

    mappable = cm.ScalarMappable(cmap=cmap)
    mappable.set_array([])
    mappable.set_clim(-0.5, N+0.5)

    str_label = map(str, cbar_label)
    str_label[-1] = r"$\leq$" + str_label[-1]

    colorbar = plt.colorbar(mappable)
    colorbar.set_ticks(np.linspace(0, N, N))
    colorbar.ax.set_yticklabels(str_label)
    colorbar.set_ticklabels(str_label)

    plt.xlabel('Predicted class')
    plt.ylabel('Actual Class')
    plt.title("Confusion matrix")

    if save:
      plt.savefig(save_name, bbox_inches='tight', dpi = 300)
      plt.close("all")
    else:
      plt.show()

def discrete_cmap(N, base_cmap=None):
    """Create an N-bin discrete colormap from the specified input map."""

    # Note that if base_cmap is a string or None, you can simply do
    #    return plt.cm.get_cmap(base_cmap, N)
    # The following works for string, None, or a colormap instance.

    base = plt.cm.get_cmap(base_cmap)
    color_list = base(np.linspace(0, 1, N))
    cmap_name = base.name + str(N)

    return base.from_list(cmap_name, color_list, N)

def get_data_to_plot(conf_mat):
    """
    Return a triple (number N, label vector, fake_mat matrix),
    that will be used to (discretization a color, labelling
    colorbar, properly show color of cell in matrix).
    """

    min_diag = np.diag(conf_mat).min()
    dg = np.diag(np.diag(conf_mat))
    mat_zero_diag = conf_mat - dg
    uniq_el = pd.unique(mat_zero_diag.flatten())
    N = 1 + len(uniq_el)

    tmp = np.append(uniq_el, min_diag)
    tmp_sort = np.argsort(tmp)
    label = tmp[tmp_sort]

    uniq_el_sort = np.argsort(uniq_el)
    uniq_el = uniq_el[uniq_el_sort]
    idx_diff = np.where(range(N-1) != uniq_el)[0]
    #conf_mat[conf_mat == 6] = 100
    fake_mat = conf_mat.copy()
    for el in idx_diff:
	fake_mat[fake_mat == uniq_el[el]] = el

    fake_mat.flat[::len(conf_mat)+1] = N-1
    #print conf_mat
    #print ""
    #print fake_mat

    return (N, label, fake_mat)


text:
/***/
var path = require('path'), fs = require('fs'), _ = require('../../../index')._;
var taskname = __dirname.split('/').pop(); // run

module.exports = function(grunt) {
  var tmes = 'Grunt Runner test: ' + taskname;
  grunt.registerTask(taskname, tmes, _.caught(function() {
    gruntRunnerTest(grunt, _.mixedConfigure(grunt, taskname), this);
  }, grunt.fail));
};
function gruntRunnerTest(grunt, conf, gtask) {

  var line = [], done = gtask.async(), stop = function(e) {
    grunt.fail.fatal(e);
  }, log = function(m) {
    _.util.log('[' + gtask.name + '] ' + m);
  };

  line.push(function() {
    log('done.'), done();
    grunt.runner.emit('end');
  });

  _.micropipe(line);

}


text:
export const COMPOUND_PROPERTIES: Set<string> = new Set(['animationName', 'fontFamily']);

export const EXPANDED_PROPERTIES: Set<string> = new Set([
  'animation',
  'background',
  'border',
  'borderBottom',
  'borderLeft',
  'borderRight',
  'borderTop',
  'columnRule',
  'flex',
  'font',
  'listStyle',
  'margin',
  'offset',
  'outline',
  'padding',
  'textDecoration',
  'transition',
]);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TwitchLib.Events.Client
{
    /// Args representing the client left a channel event.
    public class OnLeftChannelArgs : EventArgs
    {
        /// The username of the bot that left the channel.
        public string BotUsername;
        /// Channel that bot just left (parted).
        public string Channel;
    }
}


text:
package softlayer_configuration_storage_group_array_type

// DO NOT EDIT. THIS FILE WAS AUTOMATICALLY GENERATED


text:
package bTagger;

import java.util.List;

/**
 * A Socket visible from the left side or the right side
 *
 * @author Andrea Gesmundo
 */
public class Socket{

	public final List<Label> sktLabel;

	public Socket(List<Label> ss){
		sktLabel = ss;
	}

	/**
	 * Compare the current Socket with the parameter.
	 *
	 * @param o 	The object to compare.
	 * @return 		True if the object is a BSocket equal to the current.
	 */
	public boolean equals(Object o){
		Socket s = (Socket) o;
		if (sktLabel.size() != s.sktLabel.size()) return false;
		for (int i=0; i<sktLabel.size(); i++){
			if (sktLabel.get(i) != s.sktLabel.get(i)) return false; //? the same ref to Slabel??doesn't compare the fields
		}
		return true;
	}

	/**
	 * Generate an hashcode for the current BSocket.
	 *
	 * @return 	The generated hashcode
	 */
	public int hashCode(){
		int code = 0;
		for (int i=0; i<sktLabel.size(); i++){
			code = code*64 + sktLabel.get(i).id;
		}
		return code;
	}

	/**
	 * Print the object.
	 *
	 * @return 	A representation of the object.
	 */
	public String toString(){
		StringBuffer sb = new StringBuffer("<");
		for (int i=0; i<sktLabel.size(); i++){
			if (i > 0) sb.append(", ");
			sb.append(sktLabel.get(i));
		}
		sb.append(">");
		return sb.toString();
	}

}


text:
namespace carcassonne {

class Player;
class AssetManager;
class Tile;

namespace gfx {

class Mesh;

} // namespace carcassonne::gfx

class Follower
{
public:
   Follower();
   Follower(const Follower& other);
   void operator=(const Follower& other);

   Follower(AssetManager& asset_mgr, int id);
   Follower(AssetManager& asset_mgr, Player& owner);

   Player* getOwner() const;
   bool isIdle() const;
   void setIdle(bool idle);

   bool isFloating() const;
   void setFloating(bool floating);

   bool isPlaced() const;

   void setOrientation(const Follower& other, const Tile& relative_to);
   void setPosition(const glm::vec3& position);
   const glm::vec3& getPosition() const;

   void setColor(const glm::vec4& color);

   // called by Player::draw() if the follower is idle, or Tile::draw() (after
   // setting up the tile's local transform matrix) if the follower is not idle
   // or has no owner player.
   void draw() const;

private:
   void calculateFarmingTransform();

   Player* owner_;

   gfx::Mesh* mesh_;  // the mesh used to render the follower
   glm::vec4 color_;

   bool idle_;       // false if this follower is currently in use.
   bool floating_;   // true if this follower is currently being placed.

   glm::vec3 position_; // position of follower. When idle, position is absolute in the HUD camera's world space.
                        // When follower is not idle, position is relative to the tile it is placed on.
   bool farming_; // followers are rendered laying down when farming.  Ignored when idle
   glm::mat4 farming_transform_; // transforms a standing follower to a laying down follower
   float rotation_;  // rotation around y-axis.  Ignored when idle
};

} // namespace carcassonne

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading.Tasks;

namespace TestRX.Services
{
	class GameStateService
	{
		ObservableTimerService _timerService;
		IObservable<int> _timeSequence;
		IDisposable _timeSubscription;

		public GameStateService(ObservableTimerService timerService)
		{
			if (timerService == null) throw new ArgumentNullException();

			_timerService = timerService;
			_timeSequence = _timerService.GetTimerSequence(100*1000, 1000);
			_timeSubscription = _timeSequence.Subscribe(newTime => ClockTime = newTime / 1000);

			Direction = true;
		}

		public void Initialize()
		{
			ClockTime = 100;
			IsClockStarted = false;
		}

		public void Shutdown()
		{
			_directionSubject.OnCompleted();
			_clockTimeSubject.OnCompleted();
			_clockStatusSubject.OnCompleted();
			_timeSubscription.Dispose();
		}

		#region SwitchDirection

		bool _direction;
		public bool Direction
		{
			get { return _direction; }
			set
			{
				if (_direction != value)
				{
					_direction = value;
					DirectionMonitor.OnNext(_direction);
				}
			}
		}

		BehaviorSubject<bool> _directionSubject;
		public ISubject<bool> DirectionMonitor { get { return _directionSubject ?? (_directionSubject = new BehaviorSubject<bool>(Direction)); } }

		#endregion

		#region ClockTime

		int _clockTime;
		public int ClockTime
		{
			get { return _clockTime; }
			set
			{
				if (_clockTime != value)
				{
					_clockTime = value;

					ClockTimeMonitor.OnNext(_clockTime);
				}
			}
		}

		Subject<int> _clockTimeSubject;
		public ISubject<int> ClockTimeMonitor { get { return _clockTimeSubject ?? (_clockTimeSubject = new Subject<int>()); } }

		#endregion

		bool _isClockStarted;
		public bool IsClockStarted
		{
			get { return _isClockStarted; }
			set
			{
				if (_isClockStarted != value)
				{
					_isClockStarted = value;
					ClockStatusMonitor.OnNext(_isClockStarted);
				}
			}
		}

		Subject<bool> _clockStatusSubject;
		public ISubject<bool> ClockStatusMonitor { get { return _clockStatusSubject ?? (_clockStatusSubject = new Subject<bool>()); } }

		public void StartClock()
		{
			if (IsClockStarted) throw new InvalidOperationException();

			_timerService.Start();
			IsClockStarted = true;
		}

		public void StopClock()
		{
			if (!IsClockStarted) throw new InvalidOperationException();

			_timerService.Stop();
			IsClockStarted = false;
		}
	}
}


text:
Rebar3 gpb plugin
=====

![](https://github.com/lrascao/rebar3_gpb_plugin/workflows/Common%20Test/badge.svg)

A rebar3 plugin for automatically compiling .proto files using the gpb protobuf compiler

Build
-----

    $ rebar3 compile

Use
---

Add the plugin to your rebar config:

```erlang
{erl_opts, [{i, "./_build/default/plugins/gpb/include"}]}.

{plugins, [
    { rebar3_gpb_plugin, "2.22.5" }
]}.
```

Configure gpb options (example below), full list can consulted on [gpb's project page](https://github.com/tomas-abrahamsson/gpb) [gpb_compile:file/2](https://hexdocs.pm/gpb/gpb_compile.html#file-2):

```erlang
{gpb_opts, [
    {i, "path/to/proto_dir"} | {i, {deps, "relative/path/from/deps/to/proto_dir"}},
    {f, ["desired_proto_file1.proto"]},
    {module_name_suffix, "_pb"},
    %{o, "path/to/out_dir"},    %% both .erl and .hrl are generated here
    {o_erl, "path/to/out_src"},
    {o_hrl, "path/to/out_include"},
    {strings_as_binaries, true},
    type_specs]}.
```

The `i`, `o_erl` and `o_hrl` option values are relative to the app's location.
Default values are:
* `{i, "proto"}`
* `{o_erl, "src"}`
* `{o_hrl, "include"}`

Plugin specific options (can be used together the gpb ones):

```erlang
{gpb_opts, [
    {recursive, boolean()},
    {ipath, "path/to/another/proto_dir"} | {ipath, {deps, "path/from/deps/dir/to/another/proto/dir"}}
]}.
```

* `{recursive, boolean()}` - look recursively through the provided folders
  to look for .proto files (default is true)
* `{ipath, "path/to/another/proto_dir"}` - paths that are to be added to gpb's
  include path but not searched for .proto files (useful for importing .proto
  files from other .proto).
* `{i, {deps, "relative/path/from/deps/to/proto_dir"}}` - allows you to compile
  proto files that were declared and fetched as app dependencies, the [rebar_raw_resource](https://github.com/basho/rebar_raw_resource)
  plugin is a good fit for this use case.
* `{ipath, {deps, "relative/path/from/deps/to/proto_dir"}}` - allows you to specify
  proto include paths in the same fashion as the `{i, {deps, _}}` directive.
* `{f, ["file1.proto", "file2.proto"]} - allows you to specify a subset of all proto files found.
Add the gpb include path (environment tipically is default):

    {erl_opts, [{i, "./_build/<environment>/plugins/gpb/include"}]}.

Add a hook to automatically generate modules for your protobuf files and clean them afterwards:

```erlang
{provider_hooks, [
    {pre, [
        {compile, {protobuf, compile}},
        {clean, {protobuf, clean}}
    ]}
]}.
```

Usage with umbrella projects
----------------------------

When using the gpb plugin with umbrella projects (aka having a `apps/<project>` structure) the `gpb_opts` and `provider_hooks` should **not** be in the top level `rebar.config`! Doing so would lead to undesired behavior and problems like code files not being compiled.

The solution is to create  `apps/<project>/rebar.config` and specify `gpb_opts` and `provider_hooks` in this instead of the top level config. An example config would look like this:

```erlang
%% -*- erlang -*-

%%-------------------------------------------------------------------
%% GPB
%%-------------------------------------------------------------------

{gpb_opts, [
    {i, "proto"},
    {module_name_suffix, "_pb"},
    {o_erl, "src"},
    {o_hrl, "include"},
    {strings_as_binaries, true},
    type_specs]}.
{provider_hooks,
 [{pre, [
         {compile, {protobuf, compile}},
         {clean, {protobuf, clean}}
        ]}
 ]}.
 ```

More examples
-------------

Complete usage examples are located in [doc/samples](/doc/samples).


text:
/*!
* @brief FNET Services polling mechanism API.
*
***************************************************************************/

#ifndef _FNET_POLL_H_

#define _FNET_POLL_H_

/*! @addtogroup fnet_polling
* The polling mechanism enables the execution of registered services
* (DHCP client, TFTP client, Shell, Telnet server or HTTP server) in
* "background" - during the application
* idle time. Typically, the polling callback is registered during the service
* initialization (for example the @ref fnet_http_init() or other service initialization
* function).
* In order to make the polling mechanism work, the user application should
* call the @ref fnet_poll_service() API function periodically, during the idle time.@n
* @n
* Configuration parameters:
* - @ref FNET_CFG_POLL_MAX
*/
/*! @{ */

/**************************************************************************/ /*!
 * @brief Descriptor of a registered service.
 ******************************************************************************/
typedef fnet_uint32_t fnet_poll_desc_t;

/**************************************************************************/ /*!
 * @brief Service callback function prototype.
 *
 * @param service_param   This parameter is assigned during
 *                        a service registration by the @ref
 *                        fnet_poll_service_register().
 *
 ******************************************************************************/
typedef void (* fnet_poll_service_t)(void *service_param);

#if defined(__cplusplus)
extern "C" {
#endif

/***************************************************************************/ /*!
 *
 * @brief    Main polling function.
 *
 * @see fnet_poll_service_register()
 *
 ******************************************************************************
 *
 * This function calls all registered service routines.@n
 * The user application should call this function periodically, after any service
 * initialization.
 *
 ******************************************************************************/
void fnet_poll_service(void);

/***************************************************************************/ /*!
 *
 * @brief    Unregisters all registered service routines.
 *
 * @see fnet_poll_service_register(), fnet_poll_service_unregister()
 *
 ******************************************************************************
 *
 * This function unregisters all registered service routines from
 * the polling list.
 *
 ******************************************************************************/
void fnet_poll_service_release(void);

/***************************************************************************/ /*!
 *
 * @brief    Registers the service routine in the polling list.
 *
 * @param service        Pointer to the service-polling routine.
 *
 * @param service_param  Service-polling-routine-specific parameter.
 *
 * @return This function returns:
 *   - Service descriptor, if no error occurs.
 *   - @c 0 if an error occurs.
 *
 * @see fnet_poll_service_unregister()
 *
 ******************************************************************************
 *
 * This function adds the service routine into the polling list.@n
 * This function is usually called during a service initialization.
 * User application should not call this function directly.
 *
 ******************************************************************************/
fnet_poll_desc_t fnet_poll_service_register( fnet_poll_service_t service, void *service_param );

/***************************************************************************/ /*!
 *
 * @brief    Unregisters the service routine.
 *
 * @param desc       Service descriptor to be unregistered.
 *
 * @see fnet_poll_service_register()
 *
 ******************************************************************************
 *
 * This function unregisters the service routine assigned to the @c desc
 * descriptor.@n
 * This function is usually called during a service release.
 * User application should not call this function directly.
 *
 ******************************************************************************/
void fnet_poll_service_unregister( fnet_poll_desc_t desc );

#if defined(__cplusplus)
}
#endif

/*! @} */

#endif


text:
package com.linkedin.databus2.producers;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.log4j.Logger;

import com.google.code.or.binlog.BinlogEventListener;
import com.google.code.or.binlog.BinlogEventV4;
import com.google.code.or.binlog.BinlogEventV4Header;
import com.google.code.or.binlog.impl.event.AbstractBinlogEventV4;
import com.google.code.or.binlog.impl.event.DeleteRowsEvent;
import com.google.code.or.binlog.impl.event.DeleteRowsEventV2;
import com.google.code.or.binlog.impl.event.FormatDescriptionEvent;
import com.google.code.or.binlog.impl.event.QueryEvent;
import com.google.code.or.binlog.impl.event.RotateEvent;
import com.google.code.or.binlog.impl.event.TableMapEvent;
import com.google.code.or.binlog.impl.event.UpdateRowsEvent;
import com.google.code.or.binlog.impl.event.UpdateRowsEventV2;
import com.google.code.or.binlog.impl.event.WriteRowsEvent;
import com.google.code.or.binlog.impl.event.WriteRowsEventV2;
import com.google.code.or.binlog.impl.event.XidEvent;
import com.google.code.or.common.glossary.Column;
import com.google.code.or.common.glossary.Pair;
import com.google.code.or.common.glossary.Row;
import com.google.code.or.common.glossary.column.BitColumn;
import com.google.code.or.common.glossary.column.BlobColumn;
import com.google.code.or.common.glossary.column.DateColumn;
import com.google.code.or.common.glossary.column.DatetimeColumn;
import com.google.code.or.common.glossary.column.DecimalColumn;
import com.google.code.or.common.glossary.column.DoubleColumn;
import com.google.code.or.common.glossary.column.EnumColumn;
import com.google.code.or.common.glossary.column.FloatColumn;
import com.google.code.or.common.glossary.column.Int24Column;
import com.google.code.or.common.glossary.column.LongColumn;
import com.google.code.or.common.glossary.column.LongLongColumn;
import com.google.code.or.common.glossary.column.NullColumn;
import com.google.code.or.common.glossary.column.SetColumn;
import com.google.code.or.common.glossary.column.ShortColumn;
import com.google.code.or.common.glossary.column.StringColumn;
import com.google.code.or.common.glossary.column.TimeColumn;
import com.google.code.or.common.glossary.column.TimestampColumn;
import com.google.code.or.common.glossary.column.TinyColumn;
import com.google.code.or.common.glossary.column.YearColumn;
import com.linkedin.databus.core.DatabusRuntimeException;
import com.linkedin.databus.core.DatabusThreadBase;
import com.linkedin.databus.core.DbusOpcode;
import com.linkedin.databus2.core.DatabusException;
import com.linkedin.databus2.producers.ds.DbChangeEntry;
import com.linkedin.databus2.producers.ds.KeyPair;
import com.linkedin.databus2.producers.ds.PerSourceTransaction;
import com.linkedin.databus2.producers.ds.PrimaryKeySchema;
import com.linkedin.databus2.producers.ds.Transaction;
import com.linkedin.databus2.schemas.NoSuchSchemaException;
import com.linkedin.databus2.schemas.SchemaRegistryService;
import com.linkedin.databus2.schemas.VersionedSchema;
import com.linkedin.databus2.schemas.utils.SchemaHelper;

/**
 * Open Replicator callback implementation
 *
 * The main callback API is {{@link #onEvents(BinlogEventV4)()}.
 *
 * This class is responsible for converting Bin log events to Avro records using schemaRegistry and calling an application callback
 * to let the application generate DbusEvent and append to EventBuffer.
 */
class ORListener extends DatabusThreadBase implements BinlogEventListener
{
  /**
   * Application Callback from this class to process one transaction
   */
  public interface TransactionProcessor
  {
    /**
     * Callback to process one transaction
     * @param txn
     * @throws DatabusException if unable to process the event. Relay will stop processing further
     * events if this problem happens
     */
    public abstract void onEndTransaction(Transaction txn) throws DatabusException;
  };

  /** Transaction object containing the current transaction that is being built from the Binlog **/
  private Transaction _transaction = null;

  /** Track current file number for generating SCN **/
  private int _currFileNum;

  /** Logger Service for this class **/
  private final Logger _log;

  /** Bin Log File Prefix used to extract file numbers in RotateEvents **/
  private final String _binlogFilePrefix;

  /** Schema Registry Service **/
  private final SchemaRegistryService _schemaRegistryService;

  /** Table URI to Source Id Map */
  private final Map<String, Short> _tableUriToSrcIdMap;
  /** Table URI to Source Name Map */
  private final Map<String, String> _tableUriToSrcNameMap;

  /** Transaction Processor **/
  private final TransactionProcessor _txnProcessor;

  /** Size in bytes in bin log for the transaction **/
  private long _currTxnSizeInBytes = 0;

  /** Txn End Timestamp (nanos) as seen in the binlog **/
  private long _currTxnTimestamp = 0;

  /** Nano sec timestamp at which the current timestamp begin seen **/
  private long _currTxnStartReadTimestamp = 0;

  /** Flag to indicate the begining of the txn is seen. Used to indicate  **/
  private boolean _isBeginTxnSeen = false;

  /** Track all the table map events, cleared when the binlog rotated **/
  private final Map<Long, TableMapEvent> _tableMapEvents = new HashMap<Long, TableMapEvent>();

  /** Shared queue to transfer binlog events from OpenReplicator to ORlistener thread **/
  private BlockingQueue<BinlogEventV4> _binlogEventQueue = null;

  public ORListener(String name,
                    int currentFileNumber,
                    Logger log,
                    String binlogFilePrefix,
                    TransactionProcessor txnProcessor,
                    Map<String, Short> tableUriToSrcIdMap,
                    Map<String, String> tableUriToSrcNameMap,
                    SchemaRegistryService schemaRegistryService,
                    int maxQueueSize)
  {
    super("ORListener_" + name);
    _log = log;
    _txnProcessor = txnProcessor;
    _binlogFilePrefix = binlogFilePrefix;
    _tableUriToSrcIdMap = tableUriToSrcIdMap;
    _tableUriToSrcNameMap = tableUriToSrcNameMap;
    _schemaRegistryService = schemaRegistryService;
    _currFileNum = currentFileNumber;
    _binlogEventQueue = new LinkedBlockingQueue<BinlogEventV4>(maxQueueSize);
  }

  @Override
  public void onEvents(BinlogEventV4 event)
  {
    boolean isPut = false;
    do {
      try {
        isPut = _binlogEventQueue.offer(event, 100, TimeUnit.MILLISECONDS);
      } catch (InterruptedException e) {
        _log.error("failed to put binlog event to binlogEventQueue event: " + event, e);
      }
    } while (!isPut && !isShutdownRequested());
  }

  private void processTableMapEvent(TableMapEvent tme)
  {
    _tableMapEvents.put(tme.getTableId(), tme);

    String newTableName = tme.getDatabaseName().toString().toLowerCase() + "." + tme.getTableName().toString().toLowerCase();
    startSource(newTableName);
  }

  private void startXtion(QueryEvent e)
  {
    _currTxnStartReadTimestamp = System.nanoTime();
    _log.info("startXtion" + e);
    if ( _transaction == null)
    {
      _transaction = new Transaction();
    }
    else
    {
      throw new DatabusRuntimeException("Got startXtion without an endXtion for previous transaction");
    }
  }

  /**
   * Per {@link http://code.google.com/p/open-replicator/source/browse/trunk/open-replicator/src/main/java/com/google/code/or/binlog/impl/event/XidEvent.java}
   * XidEvent signals a commit
   */
  private void endXtion(AbstractBinlogEventV4 e)
  {
    _currTxnTimestamp = e.getHeader().getTimestamp() * 1000000L;
    long txnReadLatency = System.nanoTime() - _currTxnStartReadTimestamp;
    boolean em = ((e instanceof QueryEvent) || ( e instanceof XidEvent));
    if (! em)
    {
      throw new DatabusRuntimeException("endXtion should be called with either QueryEvent of XidEvent");
    }
    _transaction.setSizeInBytes(_currTxnSizeInBytes);
    _transaction.setTxnNanoTimestamp(_currTxnTimestamp);
    _transaction.setTxnReadLatencyNanos(txnReadLatency);
    try
    {
      _txnProcessor.onEndTransaction(_transaction);
    } catch (DatabusException e3)
    {
      _log.error("Got exception in the transaction handler ",e3);
      throw new DatabusRuntimeException(e3);
    }
    finally
    {
      reset();

      if ( _log.isDebugEnabled())
      {
        _log.debug("endXtion" + e);
      }
    }
  }

  private void rollbackXtion(QueryEvent e)
  {
    reset();
    _log.info("rollbackXtion" + e);
  }

  private void reset()
  {
    _transaction = null;
    _currTxnSizeInBytes = 0;
  }

  private void startSource(String newTableName)
  {
    Short srcId = _tableUriToSrcIdMap.get(newTableName);

    assert (_transaction != null);
    if (_transaction.getPerSourceTransaction(srcId) == null)
    {
      _transaction.mergePerSourceTransaction(new PerSourceTransaction(srcId));
    }
  }

  private void deleteRows(DeleteRowsEventV2 dre)
  {
    frameAvroRecord(dre.getTableId(), dre.getHeader(), dre.getRows(), DbusOpcode.DELETE);
  }

  private void deleteRows(DeleteRowsEvent dre)
  {
    frameAvroRecord(dre.getTableId(), dre.getHeader(), dre.getRows(), DbusOpcode.DELETE);
  }

  private void updateRows(UpdateRowsEvent ure)
  {
    List<Pair<Row>> lp = ure.getRows();
    List<Row> lr =  new ArrayList<Row>(lp.size());
    for (Pair<Row> pr: lp)
    {
      Row r = pr.getAfter();
      lr.add(r);
    }
    frameAvroRecord(ure.getTableId(), ure.getHeader(), lr, DbusOpcode.UPSERT);
  }

  private void updateRows(UpdateRowsEventV2 ure)
  {
    List<Pair<Row>> lp = ure.getRows();
    List<Row> lr =  new ArrayList<Row>(lp.size());
    for (Pair<Row> pr: lp)
    {
      Row r = pr.getAfter();
      lr.add(r);
    }
    frameAvroRecord(ure.getTableId(), ure.getHeader(), lr, DbusOpcode.UPSERT);
  }

  private void insertRows(WriteRowsEvent wre)
  {
    frameAvroRecord(wre.getTableId(), wre.getHeader(), wre.getRows(), DbusOpcode.UPSERT);
  }

  private void insertRows(WriteRowsEventV2 wre)
  {
    frameAvroRecord(wre.getTableId(), wre.getHeader(), wre.getRows(), DbusOpcode.UPSERT);
  }

  private void frameAvroRecord(long tableId, BinlogEventV4Header bh, List<Row> rl, final DbusOpcode doc)
  {
    try
    {
      final long timestampInNanos = bh.getTimestamp() * 1000000L;
      final long scn = scn(_currFileNum, (int)bh.getPosition());
      final boolean isReplicated = false;
      final TableMapEvent tme = _tableMapEvents.get(tableId);
      String tableName = tme.getDatabaseName().toString().toLowerCase() + "." + tme.getTableName().toString().toLowerCase();
      VersionedSchema vs = _schemaRegistryService.fetchLatestVersionedSchemaBySourceName(_tableUriToSrcNameMap.get(tableName));
      Schema schema = vs.getSchema();

      if ( _log.isDebugEnabled())
        _log.debug("File Number :" + _currFileNum + ", Position :" + (int)bh.getPosition() + ", SCN =" + scn);

      for(Row r: rl)
      {
        List<Column> cl = r.getColumns();
        GenericRecord gr = new GenericData.Record(schema);
        generateAvroEvent(schema, cl, gr);

        List<KeyPair> kps = generateKeyPair(cl, schema);

        DbChangeEntry db = new DbChangeEntry(scn, timestampInNanos, gr, doc, isReplicated, schema, kps);
        _transaction.getPerSourceTransaction(_tableUriToSrcIdMap.get(tableName)).mergeDbChangeEntrySet(db);
      }
    } catch (NoSuchSchemaException ne)
    {
      throw new DatabusRuntimeException(ne);
    } catch (DatabusException de)
    {
      throw new DatabusRuntimeException(de);
    }
  }

  private List<KeyPair> generateKeyPair(List<Column> cl, Schema schema)
      throws DatabusException
  {

    Object o = null;
    Schema.Type st = null;

    // Build PrimaryKeySchema
    String pkFieldName = SchemaHelper.getMetaField(schema, "pk");
    if(pkFieldName == null)
    {
      throw new DatabusException("No primary key specified in the schema");
    }

    PrimaryKeySchema pkSchema = new PrimaryKeySchema(pkFieldName);
    List<Schema.Field> fields = schema.getFields();
    List<KeyPair> kpl = new ArrayList<KeyPair>();
    int cnt = 0;
    for(Schema.Field field : fields)
    {
      if (pkSchema.isPartOfPrimaryKey(field))
      {
        o = cl.get(cnt).getValue();
        st = field.schema().getType();
        KeyPair kp = new KeyPair(o, st);
        kpl.add(kp);
      }
      cnt++;
    }

    return kpl;
  }

  private void generateAvroEvent(Schema schema, List<Column> cols, GenericRecord record)
      throws DatabusException
  {
    // Get Ordered list of field by dbFieldPosition
    List<Schema.Field> orderedFields = SchemaHelper.getOrderedFieldsByMetaField(schema, "dbFieldPosition", new Comparator<String>() {

      @Override
      public int compare(String o1, String o2)
      {
        Integer pos1 = Integer.parseInt(o1);
        Integer pos2 = Integer.parseInt(o2);

        return pos1.compareTo(pos2);
      }
    });

    // Build Map<AvroFieldType, Columns>
    if (orderedFields.size() != cols.size())
    {
      throw new DatabusException("Mismatch in db schema vs avro schema");
    }

    int cnt = 0;
    Map<String, Column> avroFieldCol = new HashMap<String, Column>();

    for(Schema.Field field : orderedFields)
    {
      avroFieldCol.put(field.name(), cols.get(cnt));
      cnt++;
    }

    for(Schema.Field field : orderedFields)
    {
      if(field.schema().getType() == Schema.Type.ARRAY)
      {
        throw new DatabusException("The parser cannot handle ARRAY datatypes. Found in field: "+ field);
      }
      else
      {
        // The current database field being processed
        // (field is avro field name  and databaseFieldName is oracle field name (one to one mapping)
        String databaseFieldName = SchemaHelper.getMetaField(field, "dbFieldName").toLowerCase();
        _log.debug("databaseFieldName = " + databaseFieldName);
        //Insert the field into the generic record
        insertFieldIntoRecord(avroFieldCol, record, databaseFieldName, field);
      }
    }
    if ( _log.isDebugEnabled())
    {
      _log.debug("Generic record = " + record);
    }
  }

  /**
   * Given the following :
   * 1. A row data as a map of (dbFieldName, Column) data)
   * 2. A generic record to populate
   * 3. dbFieldName
   * 4. avroFieldName
   *
   * The method locates the Column for the dbFieldName, extracts the data as a Java Object,
   * inserts into the generic record with avroFieldName.name() as the key
   */
  private void insertFieldIntoRecord(
                                     Map<String, Column> eventFields,
                                     GenericRecord record,
                                     String dbFieldName,
                                     Schema.Field avroField)
                                         throws DatabusException
  {
    String f = avroField.name();
    Column fieldValue = eventFields.get(f);
    boolean isFieldNull = (fieldValue == null);
    Object fieldValueObj = null;
    try
    {
      if (! isFieldNull)
        fieldValueObj =  orToAvroType(fieldValue);
      else
        fieldValueObj = null;

      record.put(avroField.name(), fieldValueObj);
    }
    catch(DatabusException e)
    {
      _log.error("Unable to process field: " + avroField.name());
      throw e;
    }
    return;
  }

  /**
   * Given a OR Column, it returns a corresponding Java object that can be inserted into
   * AVRO record
   */
  private Object orToAvroType(Column s)
      throws DatabusException
  {
    if (s instanceof BitColumn)
    {
      // This is in  byte order
      BitColumn bc = (BitColumn) s;
      byte[] ba = bc.getValue();
      ByteBuffer b = ByteBuffer.wrap(ba);
      return b;
    }
    else if (s instanceof BlobColumn)
    {
      BlobColumn bc = (BlobColumn) s;
      byte[] ba = bc.getValue();
      return ByteBuffer.wrap(ba);
    }
    else if (s instanceof DateColumn)
    {
      DateColumn dc =  (DateColumn) s;
      Date d = dc.getValue();
      Long l = d.getTime();
      return l;
    }
    else if (s instanceof DatetimeColumn)
    {
      DatetimeColumn dc = (DatetimeColumn) s;
      Date d = dc.getValue();
      Long t1 = (d.getTime()/1000) * 1000; //Bug in OR for DateTIme and Time data-types. MilliSeconds is not available for these columns but is set with currentMillis() wrongly.
      return t1;
    }
    else if (s instanceof DecimalColumn)
    {
      DecimalColumn dc = (DecimalColumn) s;
      _log.info("dc Value is :" + dc.getValue());
      String s1 = dc.getValue().toString(); // Convert to string for preserving precision
      _log.info("Str : " + s1);
      return s1;
    }
    else if (s instanceof DoubleColumn)
    {
      DoubleColumn dc = (DoubleColumn) s;
      Double d = dc.getValue();
      return d;
    }
    else if (s instanceof EnumColumn)
    {
      EnumColumn ec = (EnumColumn) s;
      Integer i = ec.getValue();
      return i;
    }
    else if (s instanceof FloatColumn)
    {
      FloatColumn fc = (FloatColumn) s;
      Float f = fc.getValue();
      return f;
    }
    else if (s instanceof Int24Column)
    {
      Int24Column ic = (Int24Column) s;
      Integer i = ic.getValue();
      return i;
    }
    else if (s instanceof LongColumn)
    {
      LongColumn lc = (LongColumn) s;
      Integer i = lc.getValue();
      return i;
    }
    else if (s instanceof LongLongColumn)
    {
      LongLongColumn llc = (LongLongColumn) s;
      Long l = llc.getValue();
      return l;
    }
    else if (s instanceof NullColumn)
    {
      return null;
    }
    else if (s instanceof SetColumn)
    {
      SetColumn sc = (SetColumn) s;
      Long l = sc.getValue();
      return l;
    }
    else if (s instanceof ShortColumn)
    {
      ShortColumn sc = (ShortColumn) s;
      Integer i = sc.getValue();
      return i;
    }
    else if (s instanceof StringColumn)
    {
      StringColumn sc = (StringColumn) s;
      String str = new String(sc.getValue(), Charset.defaultCharset());
      return str;
    }
    else if (s instanceof TimeColumn)
    {
      TimeColumn tc = (TimeColumn) s;
      Time t = tc.getValue();
      /**
       * There is a bug in OR where instead of using the default year as 1970, it is using 0070.
       * This is a temporary measure to resolve it by working around at this layer. The value obtained from OR is subtracted from "0070-00-01 00:00:00"
       */
      Calendar c = Calendar.getInstance();
      c.set(70, 0, 1, 0, 0, 0);
      // round off the milli-seconds as TimeColumn type has only seconds granularity but Calendar implementation
      // includes milli-second (System.currentTimeMillis() at the time of instantiation)
      long rawVal = (c.getTimeInMillis()/1000) * 1000;
      long val2 = (t.getTime()/1000) * 1000;
      long offset = val2 - rawVal;
      return offset;
    }
    else if (s instanceof TimestampColumn)
    {
      TimestampColumn tsc = (TimestampColumn) s;
      Timestamp ts = tsc.getValue();
      Long t = ts.getTime();
      return t;
    }
    else if (s instanceof TinyColumn)
    {
      TinyColumn tc = (TinyColumn) s;
      Integer i = tc.getValue();
      return i;
    }
    else if (s instanceof YearColumn)
    {
      YearColumn yc = (YearColumn) s;
      Integer i = yc.getValue();
      return i;
    }
    else
    {
      throw new DatabusRuntimeException("Unknown MySQL type in the event" + s.getClass() + " Object = " + s);
    }
  }

  /**
   * Creates the SCN from logId and offset
   *   SCN = {          Logid           }{         Offset         }
   *         |--- High Order 32 bits ---||--- Low Order 32 bits --|
   * @param logId
   * @param offset
   * @return
   */
  public static long scn(int logId, int offset)
  {
    long scn = logId;
    scn <<= 32;
    scn |= offset;
    return scn;
  }

  @Override
  public void run() {
    List<BinlogEventV4> eventList = new ArrayList<BinlogEventV4>();
    BinlogEventV4 event;
    while (!isShutdownRequested())
    {
      if (isPauseRequested())
      {
        LOG.info("Pause requested for ORListener. Pausing !!");
        signalPause();
        LOG.info("Pausing. Waiting for resume command");
        try
        {
          awaitUnPauseRequest();
        }
        catch (InterruptedException e)
        {
          _log.info("Interrupted !!");
        }
        LOG.info("Resuming ORListener !!");
        signalResumed();
        LOG.info("ORListener resumed !!");
      }

      eventList.clear();
      int eventNumber = _binlogEventQueue.drainTo(eventList);
      for (int i = 0; i < eventNumber; i++)
      {

        event = eventList.get(i);
        if (event == null)
        {
          _log.error("Received null event");
          continue;
        }

        try {
          // Beginning of Txn
          if (event instanceof QueryEvent)
          {
            QueryEvent qe = (QueryEvent)event;
            String sql = qe.getSql().toString();
            if ("BEGIN".equalsIgnoreCase(sql))
            {
              _isBeginTxnSeen = true;
              _log.info("BEGIN sql: " + sql);
              _currTxnSizeInBytes = event.getHeader().getEventLength();
              startXtion(qe);
              continue;
            }
          }
          else if (event instanceof RotateEvent)
          {
            RotateEvent re = (RotateEvent) event;
            String fileName = re.getBinlogFileName().toString();
            _log.info("File Rotated : FileName :" + fileName + ", _binlogFilePrefix :" + _binlogFilePrefix);
            String fileNumStr = fileName.substring(fileName.lastIndexOf(_binlogFilePrefix) + _binlogFilePrefix.length() + 1);
            _currFileNum = Integer.parseInt(fileNumStr);
            _tableMapEvents.clear();
            continue;
          }

          if ( ! _isBeginTxnSeen )
          {
            if (_log.isDebugEnabled())
            {
              _log.debug("Skipping event (" + event
                  + ") as this is before the start of first transaction");
            }
            continue;
          }

          _currTxnSizeInBytes += event.getHeader().getEventLength();

          if (event instanceof QueryEvent)
          {
            QueryEvent qe = (QueryEvent)event;
            String sql = qe.getSql().toString();
            if ("COMMIT".equalsIgnoreCase(sql))
            {
              _log.debug("COMMIT sql: " + sql);
              endXtion(qe);
              continue;
            }
            else if ("ROLLBACK".equalsIgnoreCase(sql))
            {
              _log.debug("ROLLBACK sql: " + sql);
              rollbackXtion(qe);
              continue;
            }
            else
            {
              // Ignore DDL statements for now
              _log.debug("Likely DDL statement sql: " + sql);
              continue;
            }
          }
          else if (event instanceof XidEvent)
          {
            XidEvent xe = (XidEvent)event;
            long xid = xe.getXid();
            _log.debug("Treating XID event with xid = " + xid + " as commit for the transaction");
            endXtion(xe);
            continue;
          }
          else if (event instanceof FormatDescriptionEvent)
          {
            // we don't need process this event
            _log.info("received FormatDescriptionEvent event");
            continue;
          }
          else if (event instanceof WriteRowsEvent)
          {
            WriteRowsEvent wre = (WriteRowsEvent)event;
            insertRows(wre);
          }
          else if (event instanceof WriteRowsEventV2)
          {
            WriteRowsEventV2 wre = (WriteRowsEventV2)event;
            insertRows(wre);
          }
          else if (event instanceof UpdateRowsEvent)
          {
            UpdateRowsEvent ure = (UpdateRowsEvent)event;
            updateRows(ure);
          }
          else if (event instanceof UpdateRowsEventV2)
          {
            UpdateRowsEventV2 ure = (UpdateRowsEventV2)event;
            updateRows(ure);
          }
          else if (event instanceof DeleteRowsEventV2)
          {
            DeleteRowsEventV2 dre = (DeleteRowsEventV2)event;
            deleteRows(dre);
          }
          else if (event instanceof DeleteRowsEvent)
          {
            DeleteRowsEvent dre = (DeleteRowsEvent)event;
            deleteRows(dre);
          }
          else if (event instanceof TableMapEvent)
          {
            TableMapEvent tme = (TableMapEvent)event;
            processTableMapEvent(tme);
          }
          else
          {
            _log.warn("Skipping !! Unknown OR event e: " + event);
            continue;
          }

          if (_log.isDebugEnabled())
          {
            _log.debug("e: " + event);
          }
        } catch (Exception e) {
          _log.error("failed to process binlog event, event: " + event, e);
        }
      }
    }
    _log.info("ORListener Thread done");
    doShutdownNotify();
  }
}


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 beatboxserver;

import beatboxserver.updates.SessionUpdate;
import beatboxserver.Session.SessionType;

import io.netty.channel.Channel;

import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.NoSuchElementException;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.ResultSet;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

/**
 *
 * @author rahmanj
 */
public final class SessionManager {

    /**
     * Create new {@link SessionManager} instance
     * @param databaseManager {@link DatabaseManager} for the {@link SessionManager} to use
     * @param authenticationManager {@link AuthenticatationManager} for the {@link SessionManager} to use
     */
    public SessionManager(DatabaseManager databaseManager, AuthenticationManager authenticationManager) {
        databaseMgr = databaseManager;
        authManager = authenticationManager;
        sessionMap = new HashMap<>();
    }

    /**
     *
     * @param pin {@link String} pin sent by client
     * @param ipAddress {@link String} IP address of connecting client
     * @param type {@link SessionType} to create
     * @return
     * @throws SQLException
     * @throws InvocationTargetException
     */
    public Session createSession(String pin, String ipAddress, SessionType type) throws SQLException, InvocationTargetException {
        if (pin == null || type == null) {
            throw new IllegalArgumentException();
        }

        boolean authenticated;

        long sessionID;
        String tableName;
        Session session;

        authenticated = this.authManager.authenticate(pin);

        if (authenticated) {

            int unixTimestamp = (int)(System.currentTimeMillis() / 1000L);
            String query = "INSERT INTO sessions (ip_address, session_type, time_started, session_type) VALUES ( ?, ?, ?, ?)";
            try (PreparedStatement stmt = databaseMgr.createPreparedStatement(query)) {
                stmt.setString(1, ipAddress);
                stmt.setLong(2, type.ordinal());
                stmt.setLong(3, unixTimestamp);
                stmt.setLong(4, type.ordinal());

                try {

                    // Begin transaction to atomically create a new session
                    databaseMgr.startTransaction();

                    if (stmt.executeUpdate() != 1) {
                        throw new IllegalStateException();
                    }

                    // Get the newly created ID of the session
                    // Statment.getGeneratedKeys() doesn't work for SQLite :(
                    try (Statement statement = databaseMgr.createStatement()) {
                        ResultSet rs = statement.executeQuery("SELECT LAST_INSERT_ROWID() as id");

                        if (rs.next()) {
                            sessionID = rs.getLong("id");
                        } else {
                            throw new SQLException();
                        }

                        // Insert into child table
                        tableName = type.toString().toLowerCase() + "_sessions";
                        statement.executeUpdate("INSERT INTO " + tableName + " (id) VALUES ('" + sessionID + "')");
                    }

                    // TODO, should rollback in event of failure

                } finally {

                    // Commit the transaction
                    databaseMgr.stopTransaction();
                }

            }
        } else {
            throw new SecurityException("Invalid pin");
        }

        // Create instance of session class
        String typeName = this.getClass().getPackage().getName() + "." + type.toString() + "Session";
        try {
            Class cls = Class.forName(typeName);
            Constructor ctor = cls.getDeclaredConstructor(long.class, String.class);
            if (!Session.class.isAssignableFrom(cls)) {
                throw new InvocationTargetException(new ClassCastException());
            }
            session = (Session)ctor.newInstance(sessionID, ipAddress);

        } catch (Exception e) {
            throw new InvocationTargetException(e);
        }

        synchronized(this) {

            logger.trace("Adding session %d to the map", sessionID);
            sessionMap.put(sessionID, session);
        }

        return session;
    }

    /**
     *
     * @param sessionID
     * @throws SQLException
     */
    public void destroySession(long sessionID) throws SQLException {
        if (sessionID < 0) {
            throw new IllegalArgumentException();
        }

        logger.trace("Deleting session %d", sessionID);

        synchronized(this) {
            try (PreparedStatement stmt = databaseMgr.createPreparedStatement("DELETE FROM sessions WHERE id = ?")) {
                stmt.setLong(1, sessionID);
                stmt.executeUpdate();
            }

            if (sessionMap.containsKey(sessionID)) {
                sessionMap.remove(sessionID);
            }
        }
    }

    /**
     * Broadcast a given update to all the sessions of a given type
     * @param update The {@link SessionUpdate} to broadcast to the sessions
     * @param sessionType {@link long} as the database ID (ordinal) for the session type
     * @throws SQLException
     */
    public void broadcastUpdate(SessionUpdate update, long sessionType) throws SQLException {
        if (update == null) {
            throw new IllegalArgumentException();
        }

        List<Long> sessions = new ArrayList<>();

        // Get the list of sessions with the given type from the DB
        String query = "SELECT id FROM sessions WHERE sessions.session_type = ?";
        try (PreparedStatement stmt = databaseMgr.createPreparedStatement(query)) {
            stmt.setLong(1, sessionType);
            ResultSet rs = stmt.executeQuery();
            long id;
            while (rs.next()) {
                id = rs.getLong("id");
                logger.trace("Adding %d to session ID list", id);
                sessions.add(id);
            }
        }

        synchronized(this) {
            for (long id : sessions) {
                if (sessionMap.containsKey(id)) {

                    logger.debug("Sending update to session %d", id);
                    sessionMap.get(id).sendUpdate(update);
                }
            }
        }
    }

    /**
     *
     * @param update
     * @param sessionID
     */
    public void sendUpdate(SessionUpdate update, long sessionID) {
        if (update == null) {
            throw new IllegalArgumentException();
        }

        synchronized(this) {
            if (sessionMap.containsKey(sessionID)) {
                sessionMap.get(sessionID).sendUpdate(update);
            } else {
                logger.warn("Tried sending update to non-existant session");
            }
        }
    }

    /**
     * Register an update request for a given session
     * @param sessionID
     * @param chan
     */
    public void registerRequest(long sessionID, Channel chan) {
        if (chan == null) {
            throw new IllegalArgumentException();
        }

        if (!sessionMap.containsKey(sessionID)) {
            throw new IllegalArgumentException("No session with given ID");
        }

        synchronized(this) {
            Session session = sessionMap.get(sessionID);
            session.assignRequest(chan);
        }
    }

    /**
     *
     * @return
     * @throws SQLException
     */
    public long getSessionCount() throws SQLException {
        String query = "SELECT COUNT(*) as sessions FROM sessions WHERE session_type = '" + SessionType.User.ordinal() + "'";
        try (Statement stmt = databaseMgr.createStatement()) {
            ResultSet rs = stmt.executeQuery(query);
            if (rs.next()) {
                return rs.getLong("sessions");
            } else {
                throw new NoSuchElementException();
            }
        }
    }

    /**
     * Check if the given session is valid
     * @param sessionID {@link long} session ID to validate
     * @param ipAddress {@link String} IP address
     * @return
     * @throws IllegalArgumentException
     */
    public boolean validSession(long sessionID, String ipAddress) {
        if (sessionID < 0 || ipAddress == null) {
            throw new IllegalArgumentException();
        }

        try {
            String query = "SELECT ip_address, time_started FROM sessions WHERE id = ?";
            try (PreparedStatement stmt = databaseMgr.createPreparedStatement(query)) {
                stmt.setLong(1, sessionID);

                // Check to ensure we selected (1) row
                ResultSet rs = stmt.executeQuery();
                int size = 0;
                while (rs.next()) {
                    if (!rs.getString("ip_address").equals(ipAddress)) {
                        logger.warn("Session IP address mismatch");
                        return false;
                    }
                    size++;
                }

                if (size != 1) {
                    logger.warn("Invalid number of client IDs found");
                    return false;
                }

                // TODO check timestamp

            }
        } catch (SQLException e) {

            logger.warn("Failed to authenticate session", e);
            return false;
        }

        return true;
    }

    private final Map<Long, Session> sessionMap;
    private final DatabaseManager databaseMgr;
    private final AuthenticationManager authManager;

    private final static Logger logger = LogManager.getFormatterLogger(SessionManager.class.getName());
}


text:
<?xml version="1.0" ?>
<!--
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.
-->
<Root>
  <TestCase name="testCannotTranspose">
    <Resource name="sql">
      <![CDATA[
SELECT a, f FROM
    (SELECT a * 2 as a, b, d + 1 as d, e, f FROM x, y WHERE x.c = y.f) xy
WHERE xy.e > 100 AND xy.d IN (SELECT z.i FROM z WHERE z.j < 50)
      ]]>
    </Resource>
    <Resource name="planBefore">
      <![CDATA[
LogicalProject(a=[$0], f=[$4])
+- LogicalFilter(condition=[AND(>($3, 100), IN($2, {
LogicalProject(i=[$0])
  LogicalFilter(condition=[<($1, 50)])
    LogicalTableScan(table=[[default_catalog, default_database, z, source: [TestTableSource(i, j, k)]]])
}))])
   +- LogicalProject(a=[*($0, 2)], b=[$1], d=[+($3, 1)], e=[$4], f=[$5])
      +- LogicalFilter(condition=[=($2, $5)])
         +- LogicalJoin(condition=[true], joinType=[inner])
            :- LogicalTableScan(table=[[default_catalog, default_database, x, source: [TestTableSource(a, b, c)]]])
            +- LogicalTableScan(table=[[default_catalog, default_database, y, source: [TestTableSource(d, e, f)]]])
]]>
    </Resource>
    <Resource name="planAfter">
      <![CDATA[
LogicalProject(a=[$0], f=[$4])
+- LogicalFilter(condition=[>($3, 100)])
   +- LogicalJoin(condition=[=($2, $5)], joinType=[semi])
      :- LogicalProject(a=[*($0, 2)], b=[$1], d=[+($3, 1)], e=[$4], f=[$5])
      :  +- LogicalFilter(condition=[=($2, $5)])
      :     +- LogicalJoin(condition=[true], joinType=[inner])
      :        :- LogicalTableScan(table=[[default_catalog, default_database, x, source: [TestTableSource(a, b, c)]]])
      :        +- LogicalTableScan(table=[[default_catalog, default_database, y, source: [TestTableSource(d, e, f)]]])
      +- LogicalProject(i=[$0])
         +- LogicalFilter(condition=[<($1, 50)])
            +- LogicalTableScan(table=[[default_catalog, default_database, z, source: [TestTableSource(i, j, k)]]])
]]>
    </Resource>
  </TestCase>
  <TestCase name="testTranspose">
    <Resource name="sql">
      <![CDATA[
SELECT a, f FROM
    (SELECT a, b, d, e, f FROM x, y WHERE x.c = y.f) xy
WHERE xy.e > 100 AND xy.d IN (SELECT z.i FROM z WHERE z.j < 50)
      ]]>
    </Resource>
    <Resource name="planBefore">
      <![CDATA[
LogicalProject(a=[$0], f=[$4])
+- LogicalFilter(condition=[AND(>($3, 100), IN($2, {
LogicalProject(i=[$0])
  LogicalFilter(condition=[<($1, 50)])
    LogicalTableScan(table=[[default_catalog, default_database, z, source: [TestTableSource(i, j, k)]]])
}))])
   +- LogicalProject(a=[$0], b=[$1], d=[$3], e=[$4], f=[$5])
      +- LogicalFilter(condition=[=($2, $5)])
         +- LogicalJoin(condition=[true], joinType=[inner])
            :- LogicalTableScan(table=[[default_catalog, default_database, x, source: [TestTableSource(a, b, c)]]])
            +- LogicalTableScan(table=[[default_catalog, default_database, y, source: [TestTableSource(d, e, f)]]])
]]>
    </Resource>
    <Resource name="planAfter">
      <![CDATA[
LogicalProject(a=[$0], f=[$4])
+- LogicalFilter(condition=[>($3, 100)])
   +- LogicalProject(a=[$0], b=[$1], d=[$3], e=[$4], f=[$5])
      +- LogicalFilter(condition=[=($2, $5)])
         +- LogicalJoin(condition=[true], joinType=[inner])
            :- LogicalTableScan(table=[[default_catalog, default_database, x, source: [TestTableSource(a, b, c)]]])
            +- LogicalJoin(condition=[=($0, $3)], joinType=[semi])
               :- LogicalTableScan(table=[[default_catalog, default_database, y, source: [TestTableSource(d, e, f)]]])
               +- LogicalProject(i=[$0])
                  +- LogicalFilter(condition=[<($1, 50)])
                     +- LogicalTableScan(table=[[default_catalog, default_database, z, source: [TestTableSource(i, j, k)]]])
]]>
    </Resource>
  </TestCase>
</Root>


text:
require "test_helper"

class UsersControllerTest < ActionDispatch::IntegrationTest
  setup do
    @company = companies(:one)
    @user = users(:one)
  end

  test "should get index" do
    get users_url
    assert_response :success
  end

  test "should get new" do
    get new_user_url
    assert_response :success
  end

  test "should create user" do
    assert_difference('User.count') do
      post users_url, params: { user: { company_id: @company.id, email: 'new@example.com', name: 'new user', password: 'secret', password_confirmation: 'secret' } }
    end

    assert_redirected_to user_url(User.last)
  end

  test "should show user" do
    get user_url(@user)
    assert_response :success
  end

  test "should get edit" do
    get edit_user_url(@user)
    assert_response :success
  end

  test "should update user" do
    patch user_url(@user), params: { user: {  company_id: @company.id, name: 'new name' } }
    assert_redirected_to user_url(@user)
  end

  test "should destroy user" do
    assert_difference('User.count', -1) do
      delete user_url(@user)
    end

    assert_redirected_to users_url
  end
end


text: search_result['2767']=["topic_000000000000069A_props--.html","CompanyCvListDto Properties",""];


text:
import {stream, select} from 'nu-stream';
import {text, lang, parse} from 'bennu';

function grouping(open, item, joiner, close) {
  return parse.next(
    parse.next(open, ospaces),
    lang.then(
      lang.sepBy(parse.next(joiner, ospaces), lang.then(item, ospaces)),
      close
    )
  );
}

function readDigits(s) {
  return stream.foldl(
    (value, str) => value*10+parseInt(str, 10),
    0,
    s
  );
}

function applySign(s) {
  const sign = stream.first(s) === '-' ? -1 : 1;
  return sign * stream.first(stream.rest(s));
}

function opt(p) {
  return lang.betweenTimes(0, 1, p)
    .map(s => s ? stream.first(s) : null);
}

function concat(s) {
  const parts = [];
  stream.forEach(value => {
    parts.push(value);
  }, s);
  return parts.join('');
}

function deepConcat(s) {
  const parts = [];
  function readStrings(s) {
    stream.forEach(value => {
      if (typeof value === 'string') {
        parts.push(value);
      } else {
        readStrings(value);
      }
    }, s);
  }
  readStrings(s);
  return parts.join('');
}

const ospaces = parse.many(text.space);

export const json = parse.label('json', parse.late(() => parse.choice(
  string, number, object, array, token_true, token_false, token_null)));
export const string = parse.next(
    text.character('"'),
    lang.then(
      parse.many(parse.choice(
        text.noneOf('"\\'),
        parse.next(
          text.character('\\'),
          parse.choice(
            text.oneOf('"\\/'),
            text.character('b').map(() => '\b'),
            text.character('f').map(() => '\f'),
            text.character('n').map(() => '\n'),
            text.character('r').map(() => '\r'),
            text.character('t').map(() => '\t'),
            parse.next(
              text.character('u'),
              lang.times(4, text.oneOf('0123456789abcdefABCDEF'))
                .map(concat)
                .map(s => parseInt(s, 16))
                .map(String.fromCodePoint)
            )
          )
        )
      )).map(concat),
      text.character('"')
    )
  )

const digitsNoLeadingZero = parse.enumeration(
  text.oneOf('123456789'), parse.many(text.digit)
).map(s => stream.cons(stream.first(s), stream.first(stream.rest(s))));

// Custom implementation of number. Not completely accurate for floating point!
const CUSTOMnumber = parse.enumeration(
    opt(text.character('-')),
    parse.enumeration(
      parse.choice(
        text.character('0').map(() => 0),
        digitsNoLeadingZero.map(readDigits)
      ),
      opt(parse.next(text.character('.'), parse.many1(text.digit))),
      opt(
        parse.next(
          text.oneOf('eE'),
          parse.enumeration(
            opt(text.oneOf('+-')),
            parse.many1(text.digit).map(readDigits)
          ).map(applySign)
        )
      )
    )
    .map(s => {
      let value = stream.first(s);
      const fracS = stream.rest(s);

      const fracStream = stream.first(fracS);
      if (fracStream) {
        let fracValue = 0;
        let pos = -1;
        stream.forEach(str => {
          fracValue += parseInt(str) * Math.pow(10, pos--);
        }, fracStream);
        value += fracValue;
      }

      const eS = stream.rest(fracS);
      const exponent = stream.first(eS);
      if (exponent != null) {
        value *= Math.pow(10, exponent);
      }

      return value;
    })
  ).map(applySign);

// Okay, we're cheating a bit here. We're manually parsing out the parts to be
// only what the JSON standard allows, but then we're using javascript to
// interpret it so we get accurate floating point values.
const NATIVEnumber = parse.enumeration(
    opt(text.character('-')),
    parse.choice(
      text.character('0'),
      digitsNoLeadingZero
    ),
    opt(parse.enumeration(text.character('.'), parse.many1(text.digit))),
    opt(
      parse.enumeration(
        text.oneOf('eE'),
        parse.enumeration(
          opt(text.oneOf('+-')),
          parse.many1(text.digit)
        )
      )
    )
  )
  .map(deepConcat)
  .map(Number);

export const number = parse.label('number', NATIVEnumber);

const joiner = text.character(',');
const mapping_pair = parse.enumeration(
    string, ospaces, text.character(':'), ospaces, json
  ).map(s => {
    return [stream.first(s), stream.first(select.skip(4, s))];
  });
export const array = parse.label('array', grouping(
    text.character('['), json, joiner, text.character(']')
  )
  .map(s => {
    const array = [];
    stream.forEach(value => {
      array.push(value);
    }, s);
    return array;
  }));
export const object = parse.label('object', grouping(
    text.character('{'), mapping_pair, joiner, text.character('}')
  )
  .map(s => {
    const obj = {};
    stream.forEach(value => {
      obj[value[0]] = value[1];
    }, s);
    return obj;
  }));
export const token_true = text.string('true').map(() => true);
export const token_false = text.string('false').map(() => false);
export const token_null = text.string('null').map(() => null);


text:
  Breugnon est
       un village
       situé dans le département de Nièvre en Bourgogne. Elle comptait 166 habitants en 2008.

Si vous pensez emmenager à Breugnon, vous pourrez facilement trouver une maison à acheter.

Le parc d'habitations, à Breugnon, se décomposait en 2011 en quatre appartements et 85 maisons soit
 un marché relativement équilibré.

À coté de Breugnon sont positionnées géographiquement les villes de
Ouagne à 4 km, 179 habitants,
Saint-Pierre-du-Mont située à 3 km, 183 habitants,
Oisy à 5 km, 294 habitants,
Rix à 3 km, 198 habitants,
Corvol-l'Orgueilleux localisée à 3 km, 770 habitants,
Trucy-l'Orgueilleux à 3 km, 229 habitants,
 entre autres. De plus, Breugnon est située à seulement six km de Clamecy.


text:
namespace Cofoundry.Web;

/// <summary>
/// Optional interface you can use to decorate an instance of
/// IPageBlockTypeDisplayData to add some contextual information about the
/// page the block is parented to.
/// </summary>
public interface IPageBlockWithParentPageData : IPageBlockTypeDisplayModel
{
    /// <summary>
    /// Provides access to the page containing the block.
    /// </summary>
    IEditablePageViewModel ParentPage { get; set; }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <meta name="author" content="Josan Astrid Dometita, GDG Cagayan de Oro">
    <meta name="description" content="GDG DevFest is an annual developer conference offered by the Google Developer Groups">
    <meta name="keywords" content="event, gdg, devfest, google, programming, android, chrome, developers, cdo">
    <meta name="google-site-verification" content="b9imDOrFawXaBXCC4r3uJDdswSYcalD-wWpMYhFq-no" />
    <link rel="canonical" href="http://devfest.gdgcdo.org">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:site" content="@gdgcdo">
    <meta name="twitter:title" content="DevFest is back!">
    <meta name="twitter:description" content="GDG DevFest is an annual developer conference offered by the Google Developer Groups">
    <meta name="twitter:image:src" content="http://devfest.gdgcdo.org/img/seo/sharing-twitter.png">

    <meta property="og:title" content="DevFest is back!" />
    <meta property="og:site_name" content="GDG DevFest CDO 2015" />
    <meta property="og:type" content="website" />
    <meta property="og:url" content="http://devfest.gdgcdo.org" />
    <meta property="og:image" content="http://devfest.gdgcdo.org/img/seo/sharing-facebook.png" />
    <meta property="og:description" content="GDG DevFest is an annual developer conference offered by the Google Developer Groups" />

    <title>DevFest is back! • GDG DevFest CDO 2015</title>
    <link rel="shortcut icon" href="/img/favicons/favicon.ico">
    <link rel="apple-touch-icon" sizes="152x152" href="/img/favicons/apple-touch-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/img/favicons/apple-touch-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/img/favicons/apple-touch-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/img/favicons/apple-touch-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/img/favicons/apple-touch-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/img/favicons/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/img/favicons/apple-touch-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="57x57" href="/img/favicons/apple-touch-icon-57x57.png">
    <link rel="icon" type="image/png" href="/img/favicons/favicon-196x196.png">
    <link rel="icon" type="image/png" href="/img/favicons/favicon-160x160.png">
    <link rel="icon" type="image/png" href="/img/favicons/favicon-96x96.png">
    <link rel="icon" type="image/png" href="/img/favicons/favicon-32x32.png">
    <link rel="icon" type="image/png" href="/img/favicons/favicon-16x16.png">
    <meta name="msapplication-TileColor" content="#2b5797">
    <meta name="msapplication-TileImage" content="/img/favicons/mstile-144x144.png">
    <meta name="msapplication-config" content="/img/favicons/browserconfig.xml">

    <link href="/css/main.min.css" rel="stylesheet">

    <svg id="menu-trigger" class="menu-trigger icon icon-menu visible-xs" viewBox="0 0 32 32" data-effect="st-effect">
        <use xlink:href="/img/sprites/sprites.svg#icon-menu"></use>
    </svg>

                Home

                Schedule

                Speakers

                Team

                Become a delegate

            Become a delegate

DevFest is back!

We're very excited for this year's biggest developer conference offered by our local Google communities.
Yes, GDG DevFest CDO is back!

This year, our friends from Capitol University is very kind to host our event.

It's gonna be bigger!

Attendance: we're expecting over 300 attendees

Topic: more than 28 hours of pure Google technologies

Date: 29th of November

Venue: Capitol University Theatre

Hope to see you soon!

Like us on Facebook, follow on Twitter, add to circles in Google+.

                                Apply to bec... »

Links

GDGCDO.org

Google Developers

Contacts

gdgcdo@gmail.com

						<svg class="icon icon-google-plus" viewBox="0 0 30 32">
							<use xlink:href="/img/sprites/sprites.svg#icon-google-plus"></use>
						</svg>

						<svg class="icon icon-twitter" viewBox="0 0 30 32">
							<use xlink:href="/img/sprites/sprites.svg#icon-twitter"></use>
						</svg>

						<svg class="icon icon-facebook" viewBox="0 0 30 32">
							<use xlink:href="/img/sprites/sprites.svg#icon-facebook"></use>
						</svg>

            © 2014 Based on Project Zeppelin. Designed and created by Oleh Zasadnyy · GDG Lviv

            Site modified and Graphics created by Josan Astrid Dometita · GDG Cagayan de Oro


text:
using Stratis.SmartContracts;
using Stratis.SmartContracts.Standards;

/// <summary>
/// Implementation of a standard token contract for the Stratis Platform.
/// DISCLAIMER: For demonstration purposes only.
/// </summary>
public class StandardToken : SmartContract, IStandardToken
{
    /// <summary>
    /// Constructor used to create a new instance of the token. Assigns the total token supply to the creator of the contract.
    /// </summary>
    /// <param name="smartContractState">The execution state for the contract.</param>
    /// <param name="totalSupply">The total token supply.</param>
    public StandardToken(ISmartContractState smartContractState, ulong totalSupply)
        : base(smartContractState)
    {
        this.TotalSupply = totalSupply;
        this.SetBalance(Message.Sender, totalSupply);
    }

    /// <inheritdoc />
    public ulong TotalSupply
    {
        get => PersistentState.GetUInt64(nameof(this.TotalSupply));
        private set => PersistentState.SetUInt64(nameof(this.TotalSupply), value);
    }

    /// <inheritdoc />
    public ulong GetBalance(Address address)
    {
        return PersistentState.GetUInt64($"Balance:{address}");
    }

    private void SetBalance(Address address, ulong value)
    {
        PersistentState.SetUInt64($"Balance:{address}", value);
    }

    /// <inheritdoc />
    public bool TransferTo(Address to, ulong amount)
    {
        if (amount == 0)
        {
            Log(new TransferLog { From = Message.Sender, To = to, Amount = 0 });

            return true;
        }

        ulong senderBalance = GetBalance(Message.Sender);

        if (senderBalance < amount)
        {
            return false;
        }

        ulong toBalance = GetBalance(to);

        SetBalance(Message.Sender, senderBalance - amount);

        SetBalance(to, checked(toBalance + amount));

        Log(new TransferLog { From = Message.Sender, To = to, Amount = amount });

        return true;
    }

    /// <inheritdoc />
    public bool TransferFrom(Address from, Address to, ulong amount)
    {
        if (amount == 0)
        {
            Log(new TransferLog { From = from, To = to, Amount = 0 });

            return true;
        }

        ulong senderAllowance = Allowance(from, Message.Sender);
        ulong fromBalance = GetBalance(from);

        if (senderAllowance < amount || fromBalance < amount)
        {
            return false;
        }

        ulong toBalance = GetBalance(to);

        SetApproval(from, Message.Sender, senderAllowance - amount);
        SetBalance(from, fromBalance - amount);

        SetBalance(to, checked(toBalance + amount));

        Log(new TransferLog { From = from, To = to, Amount = amount });

        return true;
    }

    /// <inheritdoc />
    public bool Approve(Address spender, ulong currentAmount, ulong amount)
    {
        if (Allowance(Message.Sender, spender) != currentAmount)
        {
            return false;
        }

        SetApproval(Message.Sender, spender, amount);

        Log(new ApprovalLog { Owner = Message.Sender, Spender = spender, Amount = amount, OldAmount = currentAmount });

        return true;
    }

    private void SetApproval(Address owner, Address spender, ulong value)
    {
        PersistentState.SetUInt64($"Allowance:{owner}:{spender}", value);
    }

    /// <inheritdoc />
    public ulong Allowance(Address owner, Address spender)
    {
        return PersistentState.GetUInt64($"Allowance:{owner}:{spender}");
    }

    public struct TransferLog
    {
        [Index]
        public Address From;

        [Index]
        public Address To;

        public ulong Amount;
    }

    public struct ApprovalLog
    {
        [Index]
        public Address Owner;

        [Index]
        public Address Spender;

        public ulong OldAmount;

        public ulong Amount;
    }
}


text:
namespace cloud_print {

extern const wchar_t kPortName[];
extern const size_t kPortNameSize;
extern const wchar_t kGoogleUpdateClientsKey[];
extern const wchar_t kGoogleUpdateClientStateKey[];

}  // namespace cloud_print

#endif  // CLOUD_PRINT_VIRTUAL_DRIVER_WIN_VIRTUAL_DRIVER_CONSTS_H_


text:
<?php
namespace Neos\Flow\Security\Authentication;

use Neos\Flow\Mvc\ActionRequest;
use Neos\Flow\Security\Account;

/**
 * Contract for an authentication token.
 *
 */
interface TokenInterface
{
    /**
     * This is the default state. The token is not authenticated and holds no credentials, that could be used for authentication.
     */
    const NO_CREDENTIALS_GIVEN = 1;

    /**
     * It was tried to authenticate the token, but the credentials were wrong.
     */
    const WRONG_CREDENTIALS = 2;

    /**
     * The token has been successfully authenticated.
     */
    const AUTHENTICATION_SUCCESSFUL = 3;

    /**
     * This indicates, that the token received credentials, but has not been authenticated yet.
     */
    const AUTHENTICATION_NEEDED = 4;

    /**
     * Returns the name of the authentication provider responsible for this token
     *
     * @return string The authentication provider name
     */
    public function getAuthenticationProviderName();

    /**
     * Sets the name of the authentication provider responsible for this token
     *
     * @param string $authenticationProviderName The authentication provider name
     * @return void
     */
    public function setAuthenticationProviderName($authenticationProviderName);

    /**
     * Returns TRUE if this token is currently authenticated
     *
     * @return boolean TRUE if this this token is currently authenticated
     */
    public function isAuthenticated();

    /**
     * Sets the authentication status. Usually called by the responsible AuthenticationManagerInterface
     *
     * @param integer $authenticationStatus One of NO_CREDENTIALS_GIVEN, WRONG_CREDENTIALS, AUTHENTICATION_SUCCESSFUL
     * @return void
     */
    public function setAuthenticationStatus($authenticationStatus);

    /**
     * Returns the current authentication status
     *
     * @return integer One of NO_CREDENTIALS_GIVEN, WRONG_CREDENTIALS, AUTHENTICATION_SUCCESSFUL, REAUTHENTICATION_NEEDED
     */
    public function getAuthenticationStatus();

    /**
     * Sets the authentication entry point
     *
     * @param EntryPointInterface $entryPoint The authentication entry point
     * @return void
     */
    public function setAuthenticationEntryPoint(EntryPointInterface $entryPoint);

    /**
     * Returns the configured authentication entry point, NULL if none is available
     *
     * @return EntryPointInterface The configured authentication entry point, NULL if none is available
     */
    public function getAuthenticationEntryPoint();

    /**
     * Returns TRUE if \Neos\Flow\Security\RequestPattern were set
     *
     * @return boolean True if a \Neos\Flow\Security\RequestPatternInterface was set
     */
    public function hasRequestPatterns();

    /**
     * Sets request patterns
     *
     * @param array $requestPatterns Array of \Neos\Flow\Security\RequestPatternInterface to be set
     * @return void
     * @see hasRequestPattern()
     */
    public function setRequestPatterns(array $requestPatterns);

    /**
     * Returns an array of set \Neos\Flow\Security\RequestPatternInterface, NULL if none was set
     *
     * @return array Array of set request patterns
     * @see hasRequestPattern()
     */
    public function getRequestPatterns();

    /**
     * Updates the authentication credentials, the authentication manager needs to authenticate this token.
     * This could be a username/password from a login controller.
     * This method is called while initializing the security context. By returning TRUE you
     * make sure that the authentication manager will (re-)authenticate the tokens with the current credentials.
     * Note: You should not persist the credentials!
     *
     * @param ActionRequest $actionRequest The current request instance
     * @return boolean TRUE if this token needs to be (re-)authenticated
     */
    public function updateCredentials(ActionRequest $actionRequest);

    /**
     * Returns the credentials of this token. The type depends on the provider
     * of the token.
     *
     * @return mixed $credentials The needed credentials to authenticate this token
     */
    public function getCredentials();

    /**
     * Returns the account if one is authenticated, NULL otherwise.
     *
     * @return Account An account object
     */
    public function getAccount();

    /**
     * Set the (authenticated) account
     *
     * @param Account $account An account object
     * @return void
     */
    public function setAccount(Account $account = null);

    /**
     * Returns a string representation of the token for logging purposes.
     *
     * @return string A string representation of the token
     */
    public function __toString();
}


text:
import { Command, App } from './';

export interface NorthbrookConfig extends Object<any> {
  plugins?: Array<string | App | Command>;
  packages?: Array<string>;
}

export interface Plugin {
  plugin: App | Command;
}

export interface Object<T> {
  [key: string]: T;
}

export interface STDIO {
  stdout?: NodeJS.WritableStream;
  stderr?: NodeJS.WritableStream;
  stdin?: NodeJS.ReadableStream;
}

export interface Stdio {
  stdout: NodeJS.WritableStream;
  stderr: NodeJS.WritableStream;
  stdin: NodeJS.ReadableStream;
}


text:
/**
 * @author Pedro Sanders
 * @since v1
 */
const ObjectId = Java.type('org.bson.types.ObjectId')

class TestUtils {
  static buildEndpoint (
    kind,
    name,
    username,
    secret = '1234',
    ref = new ObjectId().toString()
  ) {
    const endpoint = {
      apiVersion: 'v1.0',
      metadata: {
        name: name,
        ref: ref
      },
      spec: {
        credentials: {
          username: username,
          secret: secret
        }
      }
    }
    endpoint.kind = kind
    return endpoint
  }

  static buildAgent (
    name,
    domains,
    username,
    secret = '1234',
    ref = new ObjectId().toString()
  ) {
    const agent = TestUtils.buildEndpoint('Agent', name, username, secret, ref)
    agent.spec.domains = domains
    return agent
  }

  static buildGateway (
    name,
    username,
    ref = new ObjectId().toString(),
    secret = '1234'
  ) {
    const gateway = {
      apiVersion: 'v1.0',
      kind: 'Gateway',
      metadata: {
        name: name,
        ref: ref
      },
      spec: {
        transport: 'tcp',
        host: 'provider.net',
        credentials: {
          username: username,
          secret: secret
        }
      }
    }
    return gateway
  }

  static buildDomain (
    name,
    domainUri,
    numberRef,
    ref = new ObjectId().toString()
  ) {
    const domain = {
      apiVersion: 'v1.0',
      kind: 'Domain',
      metadata: {
        name: name,
        ref: ref
      },
      spec: {
        context: {
          domainUri: domainUri,
          egressPolicy: {
            rule: '.*'
          }
        }
      }
    }
    if (numberRef) {
      domain.spec.context.egressPolicy.numberRef = numberRef
    }
    return domain
  }

  static buildNumber (gwRef, ref = new ObjectId().toString()) {
    const number = {
      apiVersion: 'v1.0',
      kind: 'Number',
      metadata: {
        ref: ref,
        gwRef: gwRef,
        geoInfo: {
          city: 'Sanford, GA',
          country: 'United States',
          countryISOCode: 'DR'
        }
      },
      spec: {
        location: {
          telUrl: 'tel:61198972121',
          aorLink: 'sip:1001@sip.local'
        }
      }
    }
    return number
  }

  static buildUser (
    name,
    username,
    secret = '1234',
    ref = new ObjectId().toString()
  ) {
    return {
      apiVersion: 'v1.0',
      kind: 'User',
      metadata: {
        name: name,
        ref: ref
      },
      spec: {
        credentials: {
          username: username,
          secret: secret
        }
      }
    }
  }
}

module.exports = TestUtils


text:
<?php
namespace Users\Form;

use Zend\Form\Form;
use Zend\InputFilter\Input;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterProviderInterface;

class LoginForm extends Form implements InputFilterProviderInterface
{
    public function __construct()
    {
       parent::__construct("Login Form");

        $this->setAttributes(array(
            'novalidate' => 'novalidate'
        ));

        $this-> add(array(
            'name' => 'userId',
            'type' => 'Zend\Form\Element\Text',
             'attributes' => array(
               'required' => 'required'
            ),
            'options' => array(
                    'label' => 'UserId'

            )
        ));

        $this->add(array(
            'name' => 'password',
            'type' => 'Zend\Form\Element\Password',
            'attributes' => array(
                    'placeholder' => '**********',
                    'required' => 'required'
            ),
            'options' => array(
             'label' => 'Password',
            )
        ));

        $this->add(array(
            'name' => 'submit',
            'attributes' => array(
                'type'  => 'submit',
                'value' => 'Login',
                'id' => 'submitButton',
            ),
        ));

   }

    public function getInputFilterSpecification()
    {
       return array(
           'userId' => array(
               'required' => 'true',
               'validators' => array(
                   array(
                       'name' => 'NotEmpty',
                       'options' => array(
                           'message' => 'Can not be left blank'
                       )
                   )
               ),
               'filters' => array(
                        array('name'=>'StripTags'),
                        array('name'=>'StringTrim')
                        )
           ),

           'password' => array(
               'required' => 'true',
               'validators' => array(
                   array(
                       'name' => 'NotEmpty',
                       'options' => array(
                           'message' => 'Can not be left blank'
                       ),
                   )
               ),
               'filters' => array(
                        array('name'=>'StripTags'),
                        array('name'=>'StringTrim')
                        )
           )

       );
   }
}


text:
@interface VWKDocumentationManager : NSObject

+ (NSString *)docsetInstallPath;

@end


text:
William McCohen <william.mccohen@gmail.com>

Gerhard Reitmayr


text:
package uk.co.skyem.random.stack1

import uk.co.skyem.random.stack1.StackEntry._
import uk.co.skyem.random.stack1.VM.{Stack, Program}

abstract class ProgramEntry {
	def this(params: Seq[String]) = this

	override def toString: String = s"ProgramEntry.${this.getClass.getSimpleName}"
	def apply(stack: Stack, program: Program, callStack: Stack): Int = apply(stack, program)
	protected def apply(stack: Stack, program: Program): Int = apply(stack)
	protected def apply(stack: Stack): Int = apply()
	protected def apply() : Int = 0
}

object ProgramEntry {

	def data(entry: StackEntry) = new data(entry)
	def skip(amount: Int)       = new skip(amount)
	def nop   = new nop
	def add   = new add
	def sub   = new sub
	def so    = new so
	def eq    = new eq
	def save  = new save
	def load  = new load
	def call  = new call
	def dup   = new dup
	def ret   = new ret
	def swp   = new swp
	def del   = new del
	def clear = new clear
	def swcs  = new swcs
	def cfcs  = new cfcs
	def ptcs  = new ptcs
	def dfcs  = new dfcs

	val instructions = Array[ProgramEntry](nop, add, sub, so, eq, save, load, call, dup, ret, swp, del, clear, swcs, cfcs, ptcs, dfcs)

	def replaceProgram(program: Program, replace: Program) = {
		program.clear()
		program ++= nop +: replace
	}

	class nop extends ProgramEntry

	class add extends ProgramEntry {
		override def apply(stack: Stack) = {stack.push(stack.pop + stack.pop); 0}
	}
	class sub extends ProgramEntry {
		override def apply(stack: Stack) = {stack.push(stack.pop - stack.pop); 0}
	}
	class eq extends ProgramEntry {
		override def apply(stack: Stack) = {stack.push(new StackEntry("bool", stack.pop == stack.pop)); 0}
	}
	class data(val entry: StackEntry) extends ProgramEntry {
		def this(params: Seq[String]) {
			this(stackEntry(params.head, params.tail.head))
		}

		override def toString: String = super.toString + s"($entry)"
		override def apply(stack : Stack) = {stack.push(entry);0}
	}
	class skip(val number: Int) extends ProgramEntry {
		def this(params: Seq[String]) {
			this(params.head.toInt)
		}

		override def toString: String = super.toString + s"($number)"
		override def apply() = number
	}
	class so extends ProgramEntry {
		override def apply(stack: Stack) = if (stack.pop().getData.asInstanceOf[Boolean]) 1 else 0
	}
	class save extends ProgramEntry {
		override def apply(stack: Stack, program: Program) = {stack.push(new StackEntry("programPosition", program.tail.tail)); 0}
	}
	class load extends ProgramEntry {
		override def apply(stack: Stack, program: Program) = {
			replaceProgram(program, stack.pop().getData.asInstanceOf[Program])
		0}
	}
	class call extends ProgramEntry {
		override def apply(stack: Stack, program: Program, callStack: Stack) = {
			callStack.push(stackEntry("programPosition", program.tail))
			println(stack)
			println(callStack)
			replaceProgram(program, stack.pop().getData.asInstanceOf[Program])
		0}
	}
	class dup extends ProgramEntry {
		override def apply(stack: Stack) = {stack.push(stack.head); 0}
	}
	class ret extends ProgramEntry {
		override def apply(stack: Stack, program: Program, callStack: Stack) = {
			replaceProgram(program, callStack.pop().getData.asInstanceOf[Program])
		0}
	}
	class swp extends ProgramEntry {
		override def apply(stack: Stack) = {
			val a = stack.pop()
			val b = stack.pop()
			stack.push(a)
			stack.push(b)
		0}
	}
	class del extends ProgramEntry {
		override def apply(stack: Stack) = {
			stack.pop()
		0}
	}
	class clear extends ProgramEntry {
		override def apply(stack: Stack) = {
			stack.clear()
		0}
	}
	// Swap With Call Stack
	class swcs extends ProgramEntry {
		override def apply(stack: Stack, program: Program, callStack: Stack) = {
			callStack.push(stack.pop())
			stack.push(callStack.pop())
			0}
	}
	// Copy From Call Stack
	class cfcs extends ProgramEntry {
		override def apply(stack: Stack, program: Program, callStack: Stack) = {
			stack.push(callStack.head)
		0}
	}
	// Pop To Call Stack
	class ptcs extends ProgramEntry {
		override def apply(stack: Stack, program: Program, callStack: Stack) = {
			callStack.push(stack.pop())
			0}
	}
	// Delete From Call Stack
	class dfcs extends ProgramEntry {
		override def apply(stack: Stack, program: Program, callStack: Stack) = {
			callStack.pop()
			0}
	}
}


text:
import * as  React from 'react';
import { Footer } from '../footer';
import { Header } from '../header';
import './style.scss';

interface Props {
    name: string;
}

export class Page extends React.Component<Props> {
    render() {
        const { name, children } = this.props;
        return (

                <div className={`_page ${name} ${name}-page`}>
                    {children}

        );
    }
}