text:
//////////////////////////////////////////////////////////
// QCADesigner                                          //
// Copyright 2002 Konrad Walus                          //
// All Rights Reserved                                  //
// Author: Konrad Walus                                 //
// Email: qcadesigner@gmail.com                         //
// WEB: http://qcadesigner.ca/                          //
//////////////////////////////////////////////////////////
//******************************************************//
//*********** PLEASE DO NOT REFORMAT THIS CODE *********//
//******************************************************//
// If your editor wraps long lines disable it or don't  //
// save the core files that way. Any independent files  //
// you generate format as you wish.                     //
//////////////////////////////////////////////////////////
// Please use complete names in variables and fucntions //
// This will reduce ramp up time for new people trying  //
// to contribute to the project.                        //
//////////////////////////////////////////////////////////
// This file was contributed by Gabriel Schulhof        //
// (schulhof@atips.ca).                                 //
//////////////////////////////////////////////////////////
// Contents:                                            //
//                                                      //
// The callback functions for the vector table options  //
// dialog.                                              //
//                                                      //
//////////////////////////////////////////////////////////

#include <string.h>
#include <stdlib.h>
#include <gdk/gdkkeysyms.h>
#include <gtk/gtk.h>
#include "support.h"
#include "generic_utils.h"
#include "global_consts.h"
#include "custom_widgets.h"
#include "vector_table.h"
#include "file_selection_window.h"
#include "bus_layout_dialog.h"
#include "vector_table_options_dialog_data.h"
#include "vector_table_options_dialog_interface.h"
#include "vector_table_options_dialog_callbacks.h"

static void vector_cell_editable_move_cursor (GtkEntry *entry, GtkMovementStep movement_step, gint count, gboolean arg3, gpointer data) ;

static int get_n_active_children (GtkTreeModel *model, GtkTreeIter *itr) ;

void vt_model_active_toggled (GtkCellRenderer *cr, char *pszTreePath, gpointer data)
  {
  VectorTable *pvt = g_object_get_data (G_OBJECT (cr), "pvt") ;
  GtkTreeModel *model = gtk_tree_view_get_model (GTK_TREE_VIEW (data)) ;
  GtkTreeIter itr, itrOther ;
  GtkTreePath *tp = NULL ;
  gboolean bActive = TRUE ;
  QCADCell *cell = NULL ;
  int idx ;

  if (NULL == model || NULL == pvt || NULL == (tp = gtk_tree_path_new_from_string (pszTreePath))) return ;
  gtk_tree_model_get_iter (model, &itr, tp) ;

  gtk_tree_model_get (model, &itr,
    BUS_LAYOUT_MODEL_COLUMN_CELL, &cell,
    VECTOR_TABLE_MODEL_COLUMN_ACTIVE, &bActive, -1) ;

  // Zee beeg fleep
  bActive = !bActive ;

  // Update the vector table input flag
  if (NULL != cell)
    if (-1 != (idx = VectorTable_find_input_idx (pvt, cell)))
      exp_array_index_1d (pvt->inputs, VT_INPUT, idx).active_flag = bActive ;
  gtk_tree_store_set (GTK_TREE_STORE (model), &itr, VECTOR_TABLE_MODEL_COLUMN_ACTIVE, bActive, -1) ;

  // If this node has children (IOW it's a bus node) make all the children be toggled the same way
  // as the bus node, and reflect the state in the vector table
  if (gtk_tree_model_iter_children (model, &itrOther, &itr))
    while (TRUE)
      {
      gtk_tree_model_get (model, &itrOther, BUS_LAYOUT_MODEL_COLUMN_CELL, &cell, -1) ;

      // Update the vector table input flag
      if (NULL != cell)
        if (-1 != (idx = VectorTable_find_input_idx (pvt, cell)))
          exp_array_index_1d (pvt->inputs, VT_INPUT, idx).active_flag = bActive ;
      gtk_tree_store_set (GTK_TREE_STORE (model), &itrOther, VECTOR_TABLE_MODEL_COLUMN_ACTIVE, bActive, -1) ;
      if (!gtk_tree_model_iter_next (model, &itrOther)) break ;
      }
  else
  if (gtk_tree_model_iter_parent (model, &itrOther, &itr))
    {
    gboolean bBusActive = FALSE ;
    gboolean bChildActive = FALSE ;
    GtkTreeIter itrChild ;

    // If all of a bus' children are deselected, so is the bus
    if (gtk_tree_model_iter_children (model, &itrChild, &itrOther))
      {
      while (TRUE)
        {
        gtk_tree_model_get (model, &itrChild, VECTOR_TABLE_MODEL_COLUMN_ACTIVE, &bChildActive, -1) ;
        if ((bBusActive = bChildActive)) break ;
        if (!gtk_tree_model_iter_next (model, &itrChild)) break ;
        }
      gtk_tree_store_set (GTK_TREE_STORE (model), &itrOther, VECTOR_TABLE_MODEL_COLUMN_ACTIVE, bBusActive, -1) ;
      }
    }

  gtk_tree_path_free (tp) ;
  }

void vector_table_options_dialog_btnDelete_clicked (GtkWidget *widget, gpointer data)
  {
  char *psz = NULL ;
  GtkCellRenderer *cr = NULL ;
  int Nix; ;
  GList *llItr = NULL, *llCols = NULL, *llRemove = NULL, *llFirst = NULL, *llClick = NULL ;
  vector_table_options_D *dialog = g_object_get_data (G_OBJECT (data), "dialog") ;
  int idxVector = (int)g_object_get_data (G_OBJECT (data), "idxVector") ;
  VectorTable *pvt = g_object_get_data (G_OBJECT (data), "user_pvt") ;

  if (NULL == dialog || NULL == pvt) return ;

  if (NULL != (llCols = gtk_tree_view_get_columns (GTK_TREE_VIEW (dialog->tv))))
    // The first vector
    if (NULL != (llFirst = g_list_nth (llCols, 2)))
      if (NULL != (llRemove = g_list_nth (llFirst, idxVector)))
        llClick = ((NULL == llRemove->next) ? ((NULL == llRemove->prev) ? NULL : llRemove->prev) : llRemove->next) ;

  if (NULL != llRemove)
    gtk_tree_view_remove_column (GTK_TREE_VIEW (dialog->tv), GTK_TREE_VIEW_COLUMN (llRemove->data)) ;

  for (Nix = 0, llItr = llFirst ; llItr != NULL ; llItr = llItr->next, Nix++)
    if (llItr != llRemove)
      {
      if (NULL != (cr = g_object_get_data (G_OBJECT (llItr->data), "cr")))
        {
        g_object_set_data (G_OBJECT (cr), "idxVector", (gpointer)Nix) ;
        gtk_tree_view_column_set_title (GTK_TREE_VIEW_COLUMN (llItr->data), psz = g_strdup_printf ("%d", Nix)) ;
        g_free (psz) ;
        }
      }
    else
      Nix-- ;

  if (NULL != llClick)
    gtk_tree_view_column_clicked (GTK_TREE_VIEW_COLUMN (llClick->data)) ;

  VectorTable_del_vector (pvt, idxVector) ;

  vector_table_options_dialog_reflect_state (dialog) ;
  }

void vector_table_options_dialog_btnClose_clicked (GtkWidget *widget, gpointer data)
  {
  vector_table_options_D *dialog = g_object_get_data (G_OBJECT (widget), "dialog") ;

  if (NULL == dialog) return ;

  if (NULL != dialog)
    gtk_widget_hide (dialog->dialog) ;
  }

void vector_table_options_dialog_btnSimType_clicked (GtkWidget *widget, gpointer data)
  {
  vector_table_options_D *dialog = (vector_table_options_D *)data ;
  int sim_type = (int)g_object_get_data (G_OBJECT (widget), "sim_type") ;
  int *user_sim_type = NULL ;

  if (!gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget))) return ;
  if (NULL == dialog) return ;

  if (NULL != (user_sim_type = g_object_get_data (G_OBJECT (dialog->dialog), "user_sim_type")))
    (*user_sim_type) = sim_type ;

  vector_table_options_dialog_reflect_state (dialog) ;
  }

void vector_table_options_dialog_btnOpen_clicked (GtkWidget *widget, gpointer data)
  {
  VTL_RESULT vtl_result = VTL_FILE_FAILED ;
  char *pszOldFName = NULL, *psz = NULL ;
  vector_table_options_D *dialog = (vector_table_options_D *)data ;
  BUS_LAYOUT *bus_layout = NULL ;
  int *sim_type = NULL ;
  VectorTable *pvt = NULL ;

  if (NULL == dialog) return ;
  if (NULL == (pvt = g_object_get_data (G_OBJECT (dialog->dialog), "user_pvt"))) return ;
  if (NULL == (psz = get_file_name_from_user (GTK_WINDOW (dialog->dialog), _("Open Vector Table"), pvt->pszFName, FALSE))) return ;

  pszOldFName = pvt->pszFName ;
  pvt->pszFName = psz ;

  vtl_result = VectorTable_load (pvt) ;

  if (VTL_FILE_FAILED == vtl_result || VTL_MAGIC_FAILED == vtl_result)
    {
    GtkWidget *msg = NULL ;

    gtk_dialog_run (GTK_DIALOG (msg =
      gtk_message_dialog_new (GTK_WINDOW (dialog->dialog),
        GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
          (VTL_FILE_FAILED == vtl_result
            ? _("Failed to open vector table file \"%s\"!")
            : _("File \"%s\" does not appear to be a vector table file !")), psz))) ;

    gtk_widget_hide (msg) ;
    gtk_widget_destroy (msg) ;

    g_free (psz) ;
    pvt->pszFName = pszOldFName ;

    return ;
    }
  else
    {
    if (VTL_SHORT == vtl_result || VTL_TRUNC == vtl_result)
      {
      GtkWidget *msg = NULL ;

      gtk_dialog_run (GTK_DIALOG (msg =
        gtk_message_dialog_new (GTK_WINDOW (dialog->dialog),
          GTK_DIALOG_MODAL, GTK_MESSAGE_WARNING, GTK_BUTTONS_CLOSE,
            (VTL_SHORT == vtl_result
              ? _("File \"%s\" contains fewer inputs than the current vector table. Padding with zeroes.")
              : _("File \"%s\" contains more inputs than the current design. Truncating.")), psz))) ;

      gtk_widget_hide (msg) ;
      gtk_widget_destroy (msg) ;
      }

    if (NULL != (bus_layout = g_object_get_data (G_OBJECT (dialog->dialog), "user_bus_layout")) &&
        NULL != (sim_type = g_object_get_data (G_OBJECT (dialog->dialog), "user_sim_type")))
      VectorTableToDialog (dialog, bus_layout, sim_type, pvt) ;

    g_free (pszOldFName) ;

    vector_table_options_dialog_reflect_state (dialog) ;
    }
  }

void vector_table_options_dialog_btnSave_clicked (GtkWidget *widget, gpointer data)
  {
  char *psz = NULL, *psz1 = NULL ;
  VectorTable *pvt = g_object_get_data (G_OBJECT (data), "user_pvt") ;
  int sim_type = (int)g_object_get_data (G_OBJECT (data), "user_sim_type") ;

  if (EXHAUSTIVE_VERIFICATION == sim_type) return ;

  if (NULL == (psz = get_file_name_from_user (GTK_WINDOW (data), _("Save Vector Table"), pvt->pszFName, TRUE)))
    return ;

  psz1 = pvt->pszFName ;
  pvt->pszFName = psz ;

  if (VectorTable_save (pvt))
    vector_table_options_dialog_reflect_state (g_object_get_data (G_OBJECT (data), "dialog")) ;
  else
    {
    GtkWidget *msg = NULL ;

    gtk_dialog_run (GTK_DIALOG (msg =
      gtk_message_dialog_new (GTK_WINDOW (data),
        GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
           _("Failed to save vector table file \"%s\"!"), psz))) ;

    gtk_widget_hide (msg) ;
    gtk_widget_destroy (msg) ;

    pvt->pszFName = psz1 ;
    g_free (psz) ;
    }
  }

void vector_table_options_dialog_btnAdd_clicked (GtkWidget *widget, gpointer data)
  {
  vector_table_options_D *dialog = g_object_get_data (G_OBJECT (data), "dialog") ;
  VectorTable *pvt = NULL ;
  int idxVector = -1 ;

  if (NULL == dialog) return ;
  if (NULL == (pvt = g_object_get_data (G_OBJECT (dialog->dialog), "user_pvt"))) return ;
  if (dialog->btnInsert == widget)
    idxVector = (int)g_object_get_data (G_OBJECT (data), "idxVector") ;

  VectorTable_add_vector (pvt, idxVector) ;

  add_vector_to_dialog (dialog, pvt, idxVector) ;

  vector_table_options_dialog_reflect_state (dialog) ;
  }

void vector_column_clicked (GtkObject *obj, gpointer data)
  {
  GList *llCols = NULL ;
  vector_table_options_D *dialog = (vector_table_options_D *)data ;
  GtkTreeViewColumn *col = NULL ;
  GtkCellRenderer *cr = NULL ;

  if (NULL == dialog) return ;

  col = GTK_TREE_VIEW_COLUMN (GTK_IS_CELL_RENDERER (obj) ? g_object_get_data (G_OBJECT (obj), "col") : obj) ;
  cr = g_object_get_data (G_OBJECT (col), "cr") ;
  g_object_set_data (G_OBJECT (dialog->dialog), "idxVector", g_object_get_data (G_OBJECT (cr), "idxVector")) ;

  if (NULL != (llCols = gtk_tree_view_get_columns (GTK_TREE_VIEW (dialog->tv))))
    {
    GList *llItr = NULL ;
    GtkCellRenderer *cr = NULL ;

    for (llItr = llCols ; llItr != NULL ; llItr = llItr->next)
      if (NULL != (cr = g_object_get_data (G_OBJECT (llItr->data), "cr")))
        g_object_set (G_OBJECT (cr), "cell-background-set", (llItr->data == col), NULL) ;

    g_list_free (llCols) ;

    gtk_widget_queue_draw (dialog->tv) ;
    }
  }

void vector_data_func (GtkTreeViewColumn *col, GtkCellRenderer *cr, GtkTreeModel *model, GtkTreeIter *itr, gpointer data)
  {
  GtkTreeIter itrChild ;
  long long bus_value = 0 ;
  int idxInput = -1 ;
  int idxVector = (int)g_object_get_data (G_OBJECT (cr), "idxVector") ;
  QCADCell *cell = NULL ;
  VectorTable *pvt = (VectorTable *)data ;
  gboolean bActive = FALSE ;

  gtk_tree_model_get (model, itr,
    BUS_LAYOUT_MODEL_COLUMN_CELL, &cell, -1) ;

  if (NULL != cell)
    if (-1 != (idxInput = VectorTable_find_input_idx (pvt, cell)))
      {
      g_object_set (cr, "active", exp_array_index_2d (pvt->vectors, gboolean, idxVector, idxInput), NULL) ;
      return ;
      }

  if (gtk_tree_model_iter_children (model, &itrChild, itr))
    {
    char *psz = NULL ;
    while (TRUE)
      {
      gtk_tree_model_get (model, &itrChild,
        BUS_LAYOUT_MODEL_COLUMN_CELL, &cell,
        BUS_LAYOUT_MODEL_COLUMN_NAME, &psz,
        VECTOR_TABLE_MODEL_COLUMN_ACTIVE, &bActive,
        -1) ;
      if (bActive)
        {
        bus_value = bus_value << 1 ;
        if (-1 != (idxInput = VectorTable_find_input_idx (pvt, cell)))
          bus_value += exp_array_index_2d (pvt->vectors, gboolean, idxVector, idxInput) ? 1 : 0 ;
        }
      if (!gtk_tree_model_iter_next (model, &itrChild)) break ;
      }
    g_object_set (cr, "text", psz = g_strdup_printf ("%llu", bus_value), NULL) ;
    g_free (psz) ;
    return ;
    }
  g_object_set (cr, "text", "", NULL) ;
  }

void tree_view_style_set (GtkWidget *widget, GtkStyle *old_style, gpointer data)
  {
  gboolean bUseBackground = FALSE ;
  GdkColor *clrNew = &((gtk_widget_get_style (widget))->base[3]) ;
  GList *llCols = NULL, *llItr = NULL ;
  GtkCellRenderer *cr = NULL ;

  if (NULL == (llCols = gtk_tree_view_get_columns (GTK_TREE_VIEW (widget)))) return ;

  for (llItr = llCols ; llItr != NULL ; llItr = llItr->next)
    if (NULL != (cr = g_object_get_data (G_OBJECT (llItr->data), "cr")))
      {
      // Why does cell-background-gdk modify cell-background-set ?
      g_object_get (G_OBJECT (cr), "cell-background-set", &bUseBackground, NULL) ;
      g_object_set (G_OBJECT (cr),
        "cell-background-gdk", clrNew,
        "cell-background-set", bUseBackground, NULL) ;
      }
  }

void vector_value_editing_started (GtkCellRendererText *cr, GtkCellEditable *editable, char *pszPath, gpointer data)
  {
  if (GTK_IS_ENTRY (editable))
    {
    g_object_set_data_full (G_OBJECT (editable), "pszPath", g_strdup (pszPath), (GDestroyNotify)g_free) ;
    if (!g_signal_handler_find (G_OBJECT (editable), G_SIGNAL_MATCH_FUNC, 0, 0, NULL, vector_cell_editable_move_cursor, data))
      g_signal_connect (G_OBJECT (editable), "move_cursor", (GCallback)vector_cell_editable_move_cursor, data) ;
    }
  }

static void vector_cell_editable_move_cursor (GtkEntry *entry, GtkMovementStep movement_step, gint count, gboolean arg3, gpointer data)
  {
  int position = -1 ;
  const char *pszText = NULL ;
  gboolean bWhichColumn = FALSE ; // FALSE <=> Next column

  if (NULL == (pszText = gtk_entry_get_text (entry))) return ;
  g_object_get (G_OBJECT (entry), "cursor-position", &position, NULL) ;

  if ((bWhichColumn = (0 == position && count < 0)) ||
      (strlen (pszText) == position && count > 0))
    {
    vector_table_options_D *dialog = (vector_table_options_D *)data ;
    GList *llCols = NULL, *llIdx = NULL ;
    char *pszPath = NULL ;
    int idxVector = -1 ;

    if (NULL == dialog) return ;
    if (NULL == (llCols = gtk_tree_view_get_columns (GTK_TREE_VIEW (dialog->tv)))) return ;
    if (NULL != (llIdx = g_list_nth (llCols, (idxVector = (int)g_object_get_data (G_OBJECT (dialog->dialog), "idxVector")) + 2)))
      {
      if (NULL != (pszPath = g_object_get_data (G_OBJECT (entry), "pszPath")))
        {
        GList *llDst = NULL ;

        // if (0 == idxVector) do not grab a frozen column
        if (NULL != (llDst = (bWhichColumn ? (0 == idxVector ? NULL : llIdx->prev) : llIdx->next)))
          {
          GtkTreePath *tp = NULL ;

          if (NULL != (tp = gtk_tree_path_new_from_string (pszPath)))
            {
            GtkCellRenderer *cr = NULL ;

            if (NULL != (cr = g_object_get_data (G_OBJECT (llIdx->data), "cr")))
              {
              gtk_cell_editable_editing_done (GTK_CELL_EDITABLE (entry)) ;
              gtk_cell_editable_remove_widget (GTK_CELL_EDITABLE (entry)) ;
              gtk_bindings_activate (GTK_OBJECT (dialog->tv), bWhichColumn ? GDK_Left : GDK_Right, 0) ;
//              gtk_tree_view_set_cursor (GTK_TREE_VIEW (dialog->tv), tp, GTK_TREE_VIEW_COLUMN (llIdx->data), FALSE) ;
//              GTK_TREE_VIEW_CLASS (g_type_class_peek (GTK_TYPE_TREE_VIEW))->move_cursor (GTK_TREE_VIEW (dialog->tv), GTK_MOVEMENT_VISUAL_POSITIONS, bWhichColumn ? -1 : 1) ;
              while (gtk_events_pending ())
                gtk_main_iteration () ;
              gtk_tree_view_set_cursor (GTK_TREE_VIEW (dialog->tv), tp, GTK_TREE_VIEW_COLUMN (llDst->data), TRUE) ;
              }

            gtk_tree_path_free (tp) ;
            }
          }
        }
      }
    g_list_free (llCols) ;
    }
  }

void vector_value_edited (GtkCellRendererText *cr, char *pszPath, char *pszNewText, gpointer data)
  {
  GtkTreeModel *model = gtk_tree_view_get_model (GTK_TREE_VIEW (data)) ;
  VectorTable *pvt = g_object_get_data (G_OBJECT (cr), "pvt") ;
  int idxVector = (int)g_object_get_data (G_OBJECT (cr), "idxVector") ;
  GtkTreePath *tp = NULL ;
  GtkTreeIter itr, itrChild ;
  int idx = -1, the_shift = 0 ;
  long long new_value = -1 ;
  QCADCell *cell = NULL ;
  GtkTreeViewColumn *col = g_object_get_data (G_OBJECT (cr), "col") ;
  gboolean bActive = FALSE ;

  if (NULL != col)
    gtk_tree_view_column_clicked (col) ;

  if (NULL == (tp = gtk_tree_path_new_from_string (pszPath))) return ;
  gtk_tree_model_get_iter (model, &itr, tp) ;

  new_value = (long long)atoi (pszNewText) ;

  // If this is a bus node, update the children
  if (gtk_tree_model_iter_children (model, &itrChild, &itr))
    {
    long long max_val = (1 << (the_shift = get_n_active_children (model, &itr))) - 1 ;

    new_value = CLAMP (new_value, 0, max_val) ;
    while (TRUE)
      {
      gtk_tree_model_get (model, &itrChild,
        BUS_LAYOUT_MODEL_COLUMN_CELL, &cell,
        VECTOR_TABLE_MODEL_COLUMN_ACTIVE, &bActive, -1) ;
      if (NULL != cell && bActive)
        if (-1 != (idx = VectorTable_find_input_idx (pvt, cell)))
          exp_array_index_2d (pvt->vectors, gboolean, idxVector, idx) = (new_value >> (--the_shift)) & 0x1 ;
      if (!gtk_tree_model_iter_next (model, &itrChild)) break ;
      }
    }
  // Otherwise, update the checkbox and the corresponding bus
  else
    {
    if (new_value == 0 || new_value == 1)
      if (!(NULL == model || NULL == pvt))
        {
        gtk_tree_model_get (model, &itr, BUS_LAYOUT_MODEL_COLUMN_CELL, &cell, -1) ;
        if (NULL != cell)
          if (-1 != (idx = VectorTable_find_input_idx (pvt, cell)))
            {
            tree_model_row_changed (model, &itr) ;
            // Zee ozer beeg fleep (1 == value ) would be noop
            exp_array_index_2d (pvt->vectors, gboolean, idxVector, idx) = (0 == new_value) ;
            }
        }
    }

  gtk_tree_path_free (tp) ;
  }

static int get_n_active_children (GtkTreeModel *model, GtkTreeIter *itr)
  {
  int ret = 0 ;
  GtkTreeIter itrChild ;
  gboolean bActive = FALSE ;

  if (NULL == model || NULL == itr) return 0 ;
  if (!gtk_tree_model_iter_children (model, &itrChild, itr)) return 0 ;

  while (TRUE)
    {
    gtk_tree_model_get (model, &itrChild, VECTOR_TABLE_MODEL_COLUMN_ACTIVE, &bActive, -1) ;
    if (bActive) ret++ ;
    if (!gtk_tree_model_iter_next (model, &itrChild)) break ;
    }
  return ret ;
  }


text:
import requests
from requests.compat import urlencode, urlparse

# import urllib2

import time

try:
    import json
except:
    # Python 2.6 support
    import simplejson as json

try:
    import oauth2 as oauth
    has_oauth = True
except:
    has_oauth = False

try:
    import httplib2
    has_httplib2 = True
except:
    has_httplib2 = False

from .googlereader import GoogleReader
from .url import ReaderUrl

def toUnicode(obj, encoding='utf-8'):
    return obj
    # if isinstance(obj, basestring):
    #     if not isinstance(obj, unicode):
    #         obj = unicode(obj, encoding)
    # return obj

class AuthenticationMethod(object):
    """
    Defines an interface for authentication methods, must have a get method
    make this abstract?
    1. auth on setup
    2. need to have GET method
    """
    def __init__(self):
        self.client = "libgreader" #@todo: is this needed?

    def getParameters(self, extraargs=None):
        parameters = {'ck':time.time(), 'client':self.client}
        if extraargs:
            parameters.update(extraargs)
        return urlencode(parameters)

    def postParameters(self, post=None):
        return post

class ClientAuthMethod(AuthenticationMethod):
    """
    Auth type which requires a valid Google Reader username and password
    """
    CLIENT_URL = 'https://www.google.com/accounts/ClientLogin'

    def __init__(self, username, password):
        super(ClientAuthMethod, self).__init__()
        self.username   = username
        self.password   = password
        self.auth_token = self._getAuth()
        self.token      = self._getToken()

    def postParameters(self, post=None):
        post.update({'T': self.token})
        return super(ClientAuthMethod, self).postParameters(post)

    def get(self, url, parameters=None):
        """
        Convenience method for requesting to google with proper cookies/params.
        """
        getString = self.getParameters(parameters)
        headers = {'Authorization':'GoogleLogin auth=%s' % self.auth_token}
        req = requests.get(url + "?" + getString, headers=headers)
        return req.text

    def post(self, url, postParameters=None, urlParameters=None):
        """
        Convenience method for requesting to google with proper cookies/params.
        """
        if urlParameters:
            url = url + "?" + self.getParameters(urlParameters)
        headers = {'Authorization':'GoogleLogin auth=%s' % self.auth_token,
                    'Content-Type': 'application/x-www-form-urlencoded'
                    }
        postString = self.postParameters(postParameters)
        req = requests.post(url, data=postString, headers=headers)
        return req.text

    def _getAuth(self):
        """
        Main step in authorizing with Reader.
        Sends request to Google ClientAuthMethod URL which returns an Auth token.

        Returns Auth token or raises IOError on error.
        """
        parameters = {
            'service'     : 'reader',
            'Email'       : self.username,
            'Passwd'      : self.password,
            'accountType' : 'GOOGLE'}
        req = requests.post(ClientAuthMethod.CLIENT_URL, data=parameters)
        if req.status_code != 200:
            raise IOError("Error getting the Auth token, have you entered a"
                    "correct username and password?")
        data = req.text
        #Strip newline and non token text.
        token_dict = dict(x.split('=') for x in data.split('\n') if x)
        return token_dict["Auth"]

    def _getToken(self):
        """
        Second step in authorizing with Reader.
        Sends authorized request to Reader token URL and returns a token value.

        Returns token or raises IOError on error.
        """
        headers = {'Authorization':'GoogleLogin auth=%s' % self.auth_token}
        req = requests.get(ReaderUrl.API_URL + 'token', headers=headers)
        if req.status_code != 200:
            raise IOError("Error getting the Reader token.")
        return req.content

class OAuthMethod(AuthenticationMethod):
    """
    Loose wrapper around OAuth2 lib. Kinda awkward.
    """
    GOOGLE_URL        = 'https://www.google.com/accounts/'
    REQUEST_TOKEN_URL = (GOOGLE_URL + 'OAuthGetRequestToken?scope=%s' %
                         ReaderUrl.READER_BASE_URL)
    AUTHORIZE_URL     = GOOGLE_URL + 'OAuthAuthorizeToken'
    ACCESS_TOKEN_URL  = GOOGLE_URL + 'OAuthGetAccessToken'

    def __init__(self, consumer_key, consumer_secret):
        if not has_oauth:
            raise ImportError("No module named oauth2")
        super(OAuthMethod, self).__init__()
        self.oauth_key         = consumer_key
        self.oauth_secret      = consumer_secret
        self.consumer          = oauth.Consumer(self.oauth_key, self.oauth_secret)
        self.authorized_client = None
        self.token_key         = None
        self.token_secret      = None
        self.callback          = None
        self.username          = "OAuth"

    def setCallback(self, callback_url):
        self.callback = '&oauth_callback=%s' % callback_url

    def setRequestToken(self):
        # Step 1: Get a request token. This is a temporary token that is used for
        # having the user authorize an access token and to sign the request to obtain
        # said access token.
        client = oauth.Client(self.consumer)
        if not self.callback:
            resp, content = client.request(OAuthMethod.REQUEST_TOKEN_URL)
        else:
            resp, content = client.request(OAuthMethod.REQUEST_TOKEN_URL + self.callback)
        if int(resp['status']) != 200:
            raise IOError("Error setting Request Token")
        token_dict = dict(urlparse.parse_qsl(content))
        self.token_key = token_dict['oauth_token']
        self.token_secret = token_dict['oauth_token_secret']

    def setAndGetRequestToken(self):
        self.setRequestToken()
        return (self.token_key, self.token_secret)

    def buildAuthUrl(self, token_key=None):
        if not token_key:
            token_key = self.token_key
        #return auth url for user to click or redirect to
        return "%s?oauth_token=%s" % (OAuthMethod.AUTHORIZE_URL, token_key)

    def setAccessToken(self):
        self.setAccessTokenFromCallback(self.token_key, self.token_secret, None)

    def setAccessTokenFromCallback(self, token_key, token_secret, verifier):
        token = oauth.Token(token_key, token_secret)
        #step 2 depends on callback
        if verifier:
            token.set_verifier(verifier)
        client = oauth.Client(self.consumer, token)

        resp, content = client.request(OAuthMethod.ACCESS_TOKEN_URL, "POST")
        if int(resp['status']) != 200:
            raise IOError("Error setting Access Token")
        access_token = dict(urlparse.parse_qsl(content))

        #created Authorized client using access tokens
        self.authFromAccessToken(access_token['oauth_token'],
                                 access_token['oauth_token_secret'])

    def authFromAccessToken(self, oauth_token, oauth_token_secret):
        self.token_key         = oauth_token
        self.token_secret      = oauth_token_secret
        token                  = oauth.Token(oauth_token,oauth_token_secret)
        self.authorized_client = oauth.Client(self.consumer, token)

    def getAccessToken(self):
        return (self.token_key, self.token_secret)

    def get(self, url, parameters=None):
        if self.authorized_client:
            getString = self.getParameters(parameters)
            #can't pass in urllib2 Request object here?
            resp, content = self.authorized_client.request(url + "?" + getString)
            return toUnicode(content)
        else:
            raise IOError("No authorized client available.")

    def post(self, url, postParameters=None, urlParameters=None):
        """
        Convenience method for requesting to google with proper cookies/params.
        """
        if self.authorized_client:
            if urlParameters:
                getString = self.getParameters(urlParameters)
                req = urllib2.Request(url + "?" + getString)
            else:
                req = urllib2.Request(url)
            postString = self.postParameters(postParameters)
            resp,content = self.authorized_client.request(req, method="POST", body=postString)
            return toUnicode(content)
        else:
            raise IOError("No authorized client available.")

class OAuth2Method(AuthenticationMethod):
    '''
    Google OAuth2 base method.
    '''
    GOOGLE_URL = 'https://accounts.google.com'
    AUTHORIZATION_URL = GOOGLE_URL + '/o/oauth2/auth'
    ACCESS_TOKEN_URL = GOOGLE_URL + '/o/oauth2/token'
    SCOPE = [
        'https://www.googleapis.com/auth/userinfo.email',
        'https://www.googleapis.com/auth/userinfo.profile',
        'https://www.google.com/reader/api/',
    ]

    def __init__(self, client_id, client_secret):
        super(OAuth2Method, self).__init__()
        self.client_id         = client_id
        self.client_secret     = client_secret
        self.authorized_client = None
        self.code              = None
        self.access_token      = None
        self.action_token      = None
        self.redirect_uri      = None
        self.username          = "OAuth2"

    def setRedirectUri(self, redirect_uri):
        self.redirect_uri = redirect_uri

    def buildAuthUrl(self):
        args = {
            'client_id': self.client_id,
            'redirect_uri': self.redirect_uri,
            'scope': ' '.join(self.SCOPE),
            'response_type': 'code',
        }
        return self.AUTHORIZATION_URL + '?' + urlencode(args)

    def setActionToken(self):
        '''
        Get action to prevent XSRF attacks
        http://code.google.com/p/google-reader-api/wiki/ActionToken

        TODO: mask token expiring? handle regenerating?
        '''
        self.action_token = self.get(ReaderUrl.ACTION_TOKEN_URL)

    def setAccessToken(self):
        params = {
            'grant_type': 'authorization_code',  # request auth code
            'code': self.code,                   # server response code
            'client_id': self.client_id,
            'client_secret': self.client_secret,
            'redirect_uri': self.redirect_uri
        }
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        request = requests.post(self.ACCESS_TOKEN_URL, data=params,
                                headers=headers)

        if request.status_code != 200:
            raise IOError('Error getting Access Token')

        response = request.json()
        if 'access_token' not in response:
            raise IOError('Error getting Access Token')
        else:
            self.authFromAccessToken(response['access_token'])

    def authFromAccessToken(self, access_token):
        self.access_token = access_token

    def get(self, url, parameters=None):
        """
        Convenience method for requesting to google with proper cookies/params.
        """
        if not self.access_token:
            raise IOError("No authorized client available.")
        if parameters is None:
            parameters = {}
        parameters.update({'access_token': self.access_token, 'alt': 'json'})
        request = requests.get(url + '?' + self.getParameters(parameters))
        if request.status_code != 200:
            return None
        else:
            return toUnicode(request.text)

    def post(self, url, postParameters=None, urlParameters=None):
        """
        Convenience method for requesting to google with proper cookies/params.
        """
        if not self.access_token:
            raise IOError("No authorized client available.")
        if not self.action_token:
            raise IOError("Need to generate action token.")
        if urlParameters is None:
            urlParameters = {}
        headers = {'Authorization': 'Bearer ' + self.access_token,
                   'Content-Type': 'application/x-www-form-urlencoded'}
        postParameters.update({'T':self.action_token})
        request = requests.post(url + '?' + self.getParameters(urlParameters),
                                data=postParameters, headers=headers)
        if request.status_code != 200:
            return None
        else:
            return toUnicode(request.text)

class GAPDecoratorAuthMethod(AuthenticationMethod):
    """
    An adapter to work with Google API for Python OAuth2 wrapper.
    Especially useful when deploying to Google AppEngine.
    """
    def __init__(self, credentials):
        """
        Initialize auth method with existing credentials.
        Args:
            credentials: OAuth2 credentials obtained via GAP OAuth2 library.
        """
        if not has_httplib2:
            raise ImportError("No module named httplib2")
        super(GAPDecoratorAuthMethod, self).__init__()
        self._http = None
        self._credentials = credentials
        self._action_token = None

    def _setupHttp(self):
        """
        Setup an HTTP session authorized by OAuth2.
        """
        if self._http == None:
            http = httplib2.Http()
            self._http = self._credentials.authorize(http)

    def get(self, url, parameters=None):
        """
        Implement libgreader's interface for authenticated GET request
        """
        if self._http == None:
            self._setupHttp()
        uri = url + "?" + self.getParameters(parameters)
        response, content = self._http.request(uri, "GET")
        return content

    def post(self, url, postParameters=None, urlParameters=None):
        """
        Implement libgreader's interface for authenticated POST request
        """
        if self._action_token == None:
            self._action_token = self.get(ReaderUrl.ACTION_TOKEN_URL)

        if self._http == None:
            self._setupHttp()
        uri = url + "?" + self.getParameters(urlParameters)
        postParameters.update({'T':self._action_token})
        body = self.postParameters(postParameters)
        response, content = self._http.request(uri, "POST", body=body)
        return content

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace MyProject\Frontend\Controllers;

use MyProject\Phalcon\Controller;

class ErrorController extends Controller
{

    public function e404Action() {

    }

}


text:
package com.legendshop.core.dao.support;

import com.legendshop.core.UserManager;
import com.legendshop.core.constant.SysParameterEnum;
import com.legendshop.core.helper.FoundationUtil;
import com.legendshop.core.helper.PropertiesUtil;
import com.legendshop.util.AppUtils;
import com.legendshop.util.sql.ConfigCode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

public class SimpleHqlQuery extends HqlQuery
{
  private static final long serialVersionUID = -4278947596603935645L;
  private Map<String, Object> _$1 = new HashMap();

  public SimpleHqlQuery()
  {
  }

  public SimpleHqlQuery(String paramString)
  {
    this.curPage = paramString;
  }

  public void fillParameter(String paramString, Object paramObject)
  {
    if (AppUtils.isNotBlank(paramObject))
    {
      this._$1.put(paramString, paramObject);
      this.params.add(paramObject);
    }
  }

  public void fillOrder(HttpServletRequest paramHttpServletRequest, String paramString1, String paramString2)
  {
    if (!(FoundationUtil.isDataSortByExternal(this, paramHttpServletRequest, this._$1)))
      this._$1.put(paramString1, paramString2);
  }

  public void fillOrder(HttpServletRequest paramHttpServletRequest, String paramString)
  {
    if (!(FoundationUtil.isDataSortByExternal(this, paramHttpServletRequest, this._$1)))
      this._$1.put("orderIndicator", paramString);
  }

  public void fillPageSize(HttpServletRequest paramHttpServletRequest)
  {
    if (!(FoundationUtil.isDataForExport(this, paramHttpServletRequest)))
      setPageSize(((Integer)PropertiesUtil.getObject(SysParameterEnum.PAGE_SIZE, Integer.class)).intValue());
  }

  public void fillLikeParameter(String paramString, Object paramObject)
  {
    if (AppUtils.isNotBlank(paramObject))
    {
      String str = paramObject.toString().trim() + "%";
      this._$1.put(paramString, str);
      this.params.add(str);
    }
  }

  public void initSQL(String paramString1, String paramString2)
  {
    setQueryString(ConfigCode.getInstance().getCode(paramString1, this._$1));
    setAllCountString(ConfigCode.getInstance().getCode(paramString2, this._$1));
  }

  public String hasAllDataFunction(HttpServletRequest paramHttpServletRequest, String paramString)
  {
    String str = UserManager.getUserName(paramHttpServletRequest);
    if (!(FoundationUtil.haveViewAllDataFunction(paramHttpServletRequest)))
    {
      this._$1.put("userName", str);
      addParams(str);
    }
    else if (AppUtils.isNotBlank(paramString))
    {
      this._$1.put("userName", paramString);
      addParams(paramString);
    }
    return str;
  }

  public String getUserName()
  {
    return ((String)this._$1.get("userName"));
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<AssetDeclaration xmlns="uri:ea.com:eala:asset">

	<LogicCommand
		Type="SPECIAL_POWER"
		id="Command_SpecialPowerGuardShield">
		<SpecialPower>SpecialPower_GuardShield</SpecialPower>
	</LogicCommand>

	<LogicCommand
		Type="SPECIAL_POWER"
		id="Command_SpecialPower_ForceFieldDistractionWeapon">
		<SpecialPower>SpecialPower_ForceFieldDistractionWeapon</SpecialPower>
	</LogicCommand>

	<LogicCommand
		Type="SPECIAL_POWER"
		id="Command_SpecialPower_ForceFieldAttractionWeapon">
		<SpecialPower>SpecialPower_ForceFieldAttractionWeapon</SpecialPower>
	</LogicCommand>

	<LogicCommand
		id="Command_ConstructGuardShieldEmitter"
		Type="CONSTRUCTION_YARD_CONSTRUCT"
		Options="">
		<Object>GuardShieldEmitter</Object>
	</LogicCommand>

	<LogicCommand
		id="Command_Upgrade_GuardShieldAIModusON"
		Type="PLAYER_UPGRADE"
		Options="">
		<UpgradeTemplate>Upgrade_GuardShieldAIModusON</UpgradeTemplate>
	</LogicCommand>

	<LogicCommand
		id="Command_Upgrade_GuardShieldAIModusOFF"
		Type="PLAYER_UPGRADE"
		Options="">
		<UpgradeTemplate>Upgrade_GuardShieldAIModusOFF</UpgradeTemplate>
	</LogicCommand>

	<LogicCommand
		Type="SPECIAL_POWER"
		id="Command_SpecialPower_GuardShieldAIModusActivator">
		<SpecialPower>SpecialPower_GuardShieldAIModusActivator</SpecialPower>
	</LogicCommand>

	<LogicCommand
		Type="SPECIAL_POWER"
		id="Command_SpecialPower_GuardShieldAIModusDeactivator">
		<SpecialPower>SpecialPower_GuardShieldAIModusDeactivator</SpecialPower>
	</LogicCommand>

</AssetDeclaration>


text:
namespace MassTransit
{
    /// <summary>
    /// A consumer convention is used to find message types inside a consumer class.
    /// </summary>
    public interface IConsumerConvention
    {
        /// <summary>
        /// Returns the message convention for the type of T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        IConsumerMessageConvention GetConsumerMessageConvention<T>()
            where T : class;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
	<item android:state_enabled="true" android:state_pressed="true" android:drawable="@drawable/tieba_icon_s1" />
	<item android:state_enabled="true" android:state_focused="true"  android:drawable="@drawable/tieba_icon_s1" />
	<item android:drawable="@drawable/tieba_icon_s1" />
</selector>


text:
package com.github.nmorel.gwtjackson.client.annotation;

import com.github.nmorel.gwtjackson.client.GwtJacksonTestCase;
import com.github.nmorel.gwtjackson.client.ObjectReader;
import com.github.nmorel.gwtjackson.shared.ObjectReaderTester;
import com.github.nmorel.gwtjackson.shared.annotations.JsonDeserializeBuilderTester;
import com.github.nmorel.gwtjackson.shared.model.Animal;
import com.google.gwt.core.client.GWT;

/**
 * @author Nicolas Morel
 */
public class JsonDeserializeBuilderGwtTest extends GwtJacksonTestCase {

    public interface AnimalMapper extends ObjectReader<Animal>,
            ObjectReaderTester<Animal> {

        static AnimalMapper INSTANCE = GWT.create( AnimalMapper.class );
    }

    public void testDeserialize() {
        JsonDeserializeBuilderTester.INSTANCE.testDeserialize( AnimalMapper.INSTANCE );
    }
}


text:
#ifndef BOOKSHELF_PARSER_H
#define	BOOKSHELF_PARSER_H

#include "rsyn/phy/util/BookshelfDscp.h"

#include <string>
#include <fstream>
#include <vector>

// -----------------------------------------------------------------------------

class BookshelfParser {
private:

	std::string clsBaseFilename; // obtained from aux filename
	std::string clsPath; // path to aux file (without filename)

	std::ifstream      clsCurrentFile;
	std::string        clsCurrentFilename; // the file currently being parsed
	int           clsCurrentLine;

	std::vector<std::string> clsTokens;
	int clsCurrentToken;

	std::string clsFilenameNodes;
	std::string clsFilenameNets;
	std::string clsFilenamePL;
	std::string clsFilenameSCL;
	std::string clsFilenameWTS;
	std::string clsFilenameColors;

	void parseAuxiliary( const std::string &filename, BookshelfDscp &dscp );
	void parsePL( const std::string &filename, BookshelfDscp &dscp );
	void parseSCL( const std::string &filename, BookshelfDscp &dscp );
	void parseNets( const std::string &filename, BookshelfDscp &dscp );
	void parseNodes( const std::string &filename, BookshelfDscp &dscp );
	void parseWTS( const std::string &filename, BookshelfDscp &dscp );

	void parsingError( const std::string &msg );

	bool openFile( const std::string &filename );

	void nextLine( const bool skipDummyLines = true, const bool tokenize = true ); // dummy lines = comment lines, blank lines
	bool tryNextLine( const bool skipDummyLines = true, const bool tokenize = true ); // dummy lines = comment lines, blank lines
	bool tryNextToken( std::string &token );

	void readSign( const std::string &sign );
	void readString( std::string &value );
	void readInteger( int &value );
	void readDouble( double &value );
	void readColon();
	void readKeyword( const std::string &keyword );
	void readIntegerAssignment( const std::string &keyword, int &value );
	void readStringAssignment( const std::string &keyword, std::string &value );

	bool tryReadString( std::string &value );
	bool tryReadInteger( int &value );
	bool tryReadDouble( double &value );
	bool tryReadColon();
	bool tryReadKeyword( const std::string &keyword );

	// Remove path from a path + filename string.
	std::string removePath( const std::string &str ) const;

	// Remove extension from filename string.
	std::string removeExtension( const std::string &str ) const;

	// Obtain the extension from a filename.
	std::string obtainExtension( const std::string &str ) const;

	// Obtain the path from a filename.
	std::string obtainPath( const std::string &str ) const;
public:

	const std::string &getBaseFilename() const { return clsBaseFilename; }
	const std::string &getPath() const { return clsPath; }
	void parsePlaced(const std::string & filename, BookshelfDscp & dscp) { parsePL(filename, dscp); }
	void parse( const std::string &filename, BookshelfDscp &dscp );
}; // end class

#endif


text:
  Amathay-Vésigneux est
       un village
       localisé dans le département des Doubs en Franche-Comté. Elle totalisait 134 habitants en 2008.

À coté de Amathay-Vésigneux sont localisées les communes de
Septfontaines située à 4 km, 280 habitants,
Châteauvieux-les-Fossés située à 4 km, huit habitants,
Reugney localisée à 3 km, 311 habitants,
Vuillafans à 4 km, 709 habitants,
Flagey à 5 km, 134 habitants,
Lods localisée à 4 km, 251 habitants,
 entre autres. De plus, Amathay-Vésigneux est située à seulement 27 km de Besançon.

Le parc de logements, à Amathay-Vésigneux, se décomposait en 2011 en trois appartements et 82 maisons soit
 un marché relativement équilibré.

Si vous pensez demenager à Amathay-Vésigneux, vous pourrez aisément trouver une maison à acheter.


text:
from pymisp import PyMISP
from keys import url_priv, key_priv
# from keys import url_cert, key_cert
import argparse

def init(url, key):
    return PyMISP(url, key, True, 'json')

def fetch(m, all_events, event):
    if all_events:
        print(misp.download_all_suricata().text)
    else:
        print(misp.download_suricata_rule_event(event).text)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Download Suricata events.')
    parser.add_argument("-a", "--all", action='store_true', help="Download all suricata rules available.")
    parser.add_argument("-e", "--event", help="Download suricata rules from one event.")

    args = parser.parse_args()

    misp = init(url_priv, key_priv)
    # misp = init(url_cert, key_cert)

    fetch(misp, args.all, args.event)


text:
package micronet.tools.model.nodes;

import micronet.tools.model.IVisitor;
import micronet.tools.model.ModelConstants;

public class EnumRootNode extends ModelNode {

	public EnumRootNode() {
		super(ModelConstants.ENUM_DEFINITION_ROOT_KEY);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void accept(IVisitor visitor) {
		visitor.visit(this);
	}

}


text:
package recursive

import org.scalatest.FunSuite
import pkg._

@plusTwo class CPreToplevelNocomp   { override def toString = "CPreToplevelNocomp"     }
object CPreToplevelPrecomp          { def apply()           = new CPreToplevelPrecomp  }
@plusTwo class CPreToplevelPrecomp  { override def toString = "CPreToplevelPrecomp"    }
@plusTwo class CPreToplevelPostcomp { override def toString = "CPreToplevelPostcomp"   }
object CPreToplevelPostcomp         { def apply()           = new CPreToplevelPostcomp }

class Recursive extends FunSuite {
  val objects = scala.collection.mutable.ListBuffer[Any]()
  objects += new CPreToplevelNocomp()
  objects += CPreToplevelPrecomp()
  objects += CPreToplevelPostcomp()
  objects += new CPostToplevelNocomp()
  objects += CPostToplevelPrecomp()
  objects += CPostToplevelPostcomp()

  @plusTwo class CPreMemberNocomp   { override def toString = "CPreMemberNocomp"     }
  object CPreMemberPrecomp          { def apply()           = new CPreMemberPrecomp  }
  @plusTwo class CPreMemberPrecomp  { override def toString = "CPreMemberPrecomp"    }
  @plusTwo class CPreMemberPostcomp { override def toString = "CPreMemberPostcomp"   }
  object CPreMemberPostcomp         { def apply()           = new CPreMemberPostcomp }
  objects += new CPreMemberNocomp()
  objects += CPreMemberPrecomp()
  objects += CPreMemberPostcomp()
  objects += new CPostMemberNocomp()
  objects += CPostMemberPrecomp()
  objects += CPostMemberPostcomp()
  @plusTwo class CPostMemberNocomp   { override def toString = "CPostMemberNocomp"     }
  object CPostMemberPrecomp          { def apply()           = new CPostMemberPrecomp  }
  @plusTwo class CPostMemberPrecomp  { override def toString = "CPostMemberPrecomp"    }
  @plusTwo class CPostMemberPostcomp { override def toString = "CPostMemberPostcomp"   }
  object CPostMemberPostcomp         { def apply()           = new CPostMemberPostcomp }

  test("combo") {
    @plusTwo class CPreLocalNocomp   { override def toString = "CPreLocalNocomp"     }
    object CPreLocalPrecomp          { def apply()           = new CPreLocalPrecomp  }
    @plusTwo class CPreLocalPrecomp  { override def toString = "CPreLocalPrecomp"    }
    @plusTwo class CPreLocalPostcomp { override def toString = "CPreLocalPostcomp"   }
    object CPreLocalPostcomp         { def apply()           = new CPreLocalPostcomp }
    objects += new CPreLocalNocomp()
    objects += CPreLocalPrecomp()
    objects += CPreLocalPostcomp()
    objects += new CPostLocalNocomp()
    objects += CPostLocalPrecomp()
    objects += CPostLocalPostcomp()
    @plusTwo class CPostLocalNocomp   { override def toString = "CPostLocalNocomp"     }
    object CPostLocalPrecomp          { def apply()           = new CPostLocalPrecomp  }
    @plusTwo class CPostLocalPrecomp  { override def toString = "CPostLocalPrecomp"    }
    @plusTwo class CPostLocalPostcomp { override def toString = "CPostLocalPostcomp"   }
    object CPostLocalPostcomp         { def apply()           = new CPostLocalPostcomp }

    assert(objects.mkString("\n") === """
      |CPreToplevelNocomp+1+1
      |CPreToplevelPrecomp+1+1
      |CPreToplevelPostcomp+1+1
      |CPostToplevelNocomp+1+1
      |CPostToplevelPrecomp+1+1
      |CPostToplevelPostcomp+1+1
      |CPreMemberNocomp+1+1
      |CPreMemberPrecomp+1+1
      |CPreMemberPostcomp+1+1
      |CPostMemberNocomp+1+1
      |CPostMemberPrecomp+1+1
      |CPostMemberPostcomp+1+1
      |CPreLocalNocomp+1+1
      |CPreLocalPrecomp+1+1
      |CPreLocalPostcomp+1+1
      |CPostLocalNocomp+1+1
      |CPostLocalPrecomp+1+1
      |CPostLocalPostcomp+1+1
    """.trim.stripMargin)
  }
}

@plusTwo class CPostToplevelNocomp { override def toString = "CPostToplevelNocomp" }
object CPostToplevelPrecomp { def apply() = new CPostToplevelPrecomp }
@plusTwo class CPostToplevelPrecomp { override def toString = "CPostToplevelPrecomp" }
@plusTwo class CPostToplevelPostcomp { override def toString = "CPostToplevelPostcomp" }
object CPostToplevelPostcomp { def apply() = new CPostToplevelPostcomp }


text:
// Copyright (c) 2004, Open Cloud Limited.

package org.postgresql.core.v3;

import org.postgresql.core.Field;
import org.postgresql.core.NativeQuery;
import org.postgresql.core.Oid;
import org.postgresql.core.ParameterList;
import org.postgresql.core.Query;
import org.postgresql.core.SqlCommand;
import org.postgresql.core.Utils;
import org.postgresql.jdbc.PgResultSet;

import java.lang.ref.PhantomReference;
import java.util.Map;

/**
 * V3 Query implementation for a single-statement query. This also holds the state of any associated
 * server-side named statement. We use a PhantomReference managed by the QueryExecutor to handle
 * statement cleanup.
 *
 * @author Oliver Jowett (oliver@opencloud.com)
 */
class SimpleQuery implements Query {

  SimpleQuery(SimpleQuery src) {
    this(src.nativeQuery, src.transferModeRegistry, src.sanitiserDisabled);
  }

  SimpleQuery(NativeQuery query, TypeTransferModeRegistry transferModeRegistry,
      boolean sanitiserDisabled) {
    this.nativeQuery = query;
    this.transferModeRegistry = transferModeRegistry;
    this.sanitiserDisabled = sanitiserDisabled;
  }

  public ParameterList createParameterList() {
    if (nativeQuery.bindPositions.length == 0) {
      return NO_PARAMETERS;
    }

    return new SimpleParameterList(getBindCount(), transferModeRegistry);
  }

  public String toString(ParameterList parameters) {
    return nativeQuery.toString(parameters);
  }

  public String toString() {
    return toString(null);
  }

  public void close() {
    unprepare();
  }

  public SimpleQuery[] getSubqueries() {
    return null;
  }

  /**
   * Return maximum size in bytes that each result row from this query may return. Mainly used for
   * batches that return results.
   *
   * Results are cached until/unless the query is re-described.
   *
   * @return Max size of result data in bytes according to returned fields, 0 if no results, -1 if
   *         result is unbounded.
   * @throws IllegalStateException if the query is not described
   */
  public int getMaxResultRowSize() {
    if (cachedMaxResultRowSize != null) {
      return cachedMaxResultRowSize;
    }
    if (!this.statementDescribed) {
      throw new IllegalStateException(
          "Cannot estimate result row size on a statement that is not described");
    }
    int maxResultRowSize = 0;
    if (fields != null) {
      for (Field f : fields) {
        final int fieldLength = f.getLength();
        if (fieldLength < 1 || fieldLength >= 65535) {
          /*
           * Field length unknown or large; we can't make any safe estimates about the result size,
           * so we have to fall back to sending queries individually.
           */
          maxResultRowSize = -1;
          break;
        }
        maxResultRowSize += fieldLength;
      }
    }
    cachedMaxResultRowSize = maxResultRowSize;
    return maxResultRowSize;
  }

  //
  // Implementation guts
  //

  public String getNativeSql() {
    return nativeQuery.nativeSql;
  }

  void setStatementName(String statementName, short deallocateEpoch) {
    assert statementName != null : "statement name should not be null";
    this.statementName = statementName;
    this.encodedStatementName = Utils.encodeUTF8(statementName);
    this.deallocateEpoch = deallocateEpoch;
  }

  void setStatementTypes(int[] paramTypes) {
    this.preparedTypes = paramTypes;
  }

  int[] getStatementTypes() {
    return preparedTypes;
  }

  String getStatementName() {
    return statementName;
  }

  boolean isPreparedFor(int[] paramTypes, short deallocateEpoch) {
    if (statementName == null) {
      return false; // Not prepared.
    }
    if (this.deallocateEpoch != deallocateEpoch) {
      return false;
    }

    assert preparedTypes == null || paramTypes.length == preparedTypes.length
        : String.format("paramTypes:%1$d preparedTypes:%2$d", paramTypes.length,
        paramTypes == null ? -1 : preparedTypes.length);
    // Check for compatible types.
    for (int i = 0; i < paramTypes.length; ++i) {
      if (paramTypes[i] != Oid.UNSPECIFIED && paramTypes[i] != preparedTypes[i]) {
        return false;
      }
    }

    return true;
  }

  boolean hasUnresolvedTypes() {
    if (preparedTypes == null) {
      return true;
    }

    for (int preparedType : preparedTypes) {
      if (preparedType == Oid.UNSPECIFIED) {
        return true;
      }
    }

    return false;
  }

  byte[] getEncodedStatementName() {
    return encodedStatementName;
  }

  /**
   * Sets the fields that this query will return.
   *
   * @param fields The fields that this query will return.
   */
  void setFields(Field[] fields) {
    this.fields = fields;
    this.resultSetColumnNameIndexMap = null;
    this.cachedMaxResultRowSize = null;
    this.needUpdateFieldFormats = fields != null;
    this.hasBinaryFields = false; // just in case
  }

  /**
   * Returns the fields that this query will return. If the result set fields are not known returns
   * null.
   *
   * @return the fields that this query will return.
   */
  Field[] getFields() {
    return fields;
  }

  /**
   * Returns true if current query needs field formats be adjusted as per connection configuration.
   * Subsequent invocations would return {@code false}. The idea is to perform adjustments only
   * once, not for each
   * {@link QueryExecutorImpl#sendBind(SimpleQuery, SimpleParameterList, Portal, boolean)}.
   *
   * @return true if current query needs field formats be adjusted as per connection configuration
   */
  boolean needUpdateFieldFormats() {
    if (needUpdateFieldFormats) {
      needUpdateFieldFormats = false;
      return true;
    }
    return false;
  }

  public boolean hasBinaryFields() {
    return hasBinaryFields;
  }

  public void setHasBinaryFields(boolean hasBinaryFields) {
    this.hasBinaryFields = hasBinaryFields;
  }

  // Have we sent a Describe Portal message for this query yet?
  boolean isPortalDescribed() {
    return portalDescribed;
  }

  void setPortalDescribed(boolean portalDescribed) {
    this.portalDescribed = portalDescribed;
    this.cachedMaxResultRowSize = null;
  }

  // Have we sent a Describe Statement message for this query yet?
  // Note that we might not have need to, so this may always be false.
  public boolean isStatementDescribed() {
    return statementDescribed;
  }

  void setStatementDescribed(boolean statementDescribed) {
    this.statementDescribed = statementDescribed;
    this.cachedMaxResultRowSize = null;
  }

  public boolean isEmpty() {
    return getNativeSql().isEmpty();
  }

  void setCleanupRef(PhantomReference<?> cleanupRef) {
    if (this.cleanupRef != null) {
      this.cleanupRef.clear();
      this.cleanupRef.enqueue();
    }
    this.cleanupRef = cleanupRef;
  }

  void unprepare() {
    if (cleanupRef != null) {
      cleanupRef.clear();
      cleanupRef.enqueue();
      cleanupRef = null;
    }

    statementName = null;
    encodedStatementName = null;
    fields = null;
    this.resultSetColumnNameIndexMap = null;
    portalDescribed = false;
    statementDescribed = false;
    cachedMaxResultRowSize = null;
  }

  public int getBatchSize() {
    return 1;
  }

  NativeQuery getNativeQuery() {
    return nativeQuery;
  }

  public final int getBindCount() {
    return nativeQuery.bindPositions.length * getBatchSize();
  }

  private Map<String, Integer> resultSetColumnNameIndexMap;

  @Override
  public Map<String, Integer> getResultSetColumnNameIndexMap() {
    Map<String, Integer> columnPositions = this.resultSetColumnNameIndexMap;
    if (columnPositions == null && fields != null) {
      columnPositions =
          PgResultSet.createColumnNameIndexMap(fields, sanitiserDisabled);
      if (statementName != null) {
        // Cache column positions for server-prepared statements only
        this.resultSetColumnNameIndexMap = columnPositions;
      }
    }
    return columnPositions;
  }

  @Override
  public SqlCommand getSqlCommand() {
    return nativeQuery.getCommand();
  }

  private final NativeQuery nativeQuery;

  private final TypeTransferModeRegistry transferModeRegistry;
  private String statementName;
  private byte[] encodedStatementName;
  /**
   * The stored fields from previous execution or describe of a prepared statement. Always null for
   * non-prepared statements.
   */
  private Field[] fields;
  private boolean needUpdateFieldFormats;
  private boolean hasBinaryFields;
  private boolean portalDescribed;
  private boolean statementDescribed;
  private final boolean sanitiserDisabled;
  private PhantomReference<?> cleanupRef;
  private int[] preparedTypes;
  private short deallocateEpoch;

  private Integer cachedMaxResultRowSize;

  static final SimpleParameterList NO_PARAMETERS = new SimpleParameterList(0, null);
}


text:
package de.longri.cachebox3.gui.help;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.PixmapTextureData;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.kotcrab.vis.ui.VisUI;
import de.longri.cachebox3.CB;
import de.longri.cachebox3.PlatformConnector;
import de.longri.cachebox3.Utils;
import de.longri.cachebox3.gui.widgets.Window;
import de.longri.cachebox3.utils.CB_RectF;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * Created by Longri on 18.08.2016.
 */
public class HelpWindow extends Window {

    private final String SVG_TEMPLATE = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
            "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n" +
            "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" baseProfile=\"full\" width=\"#WIDTH#\" height=\"#HEIGHT#\"   xml:space=\"preserve\">\n" +
            "\n" +
            "<g fill-rule=\"evenodd\" fill=\"#FILLCOLOR#\" fill-opacity=\"#FILLOPACITY#\" stroke=\"#BORDERCOLOR#\" stroke-opacity=\"#BORDEROPACITY#\" stroke-width=\"#BORDERSIZE#\">\n" +
            " <path d=\"M 0,0 L #WIDTH#,0 #WIDTH#,#HEIGHT# 0,#HEIGHT# 0,0 z\n" +
            "\t     M centerX,posY \n" +
            "\t     A radiusX radiusY 0 0 0 centerX,maxY \n" +
            "\t     A radiusX radiusY 0 0 0 centerX,posY \n" +
            "\t     z\"/>\n" +
            "</g>\n" +
            "</svg>";

    private HelpWindowStyle style;
    protected final CB_RectF ellipseRectangle;

    public HelpWindow(final CB_RectF ellipseRectangle) {
        super("helpWindow");
        this.ellipseRectangle = ellipseRectangle;
    }

    public void show() {

        if (this.getStageBackground() == null) {

            if (this.style == null)
                this.style = VisUI.getSkin().get(HelpWindowStyle.class);

            //create a background texture as stageBackground with a ellipsed hole
            //Use SVG-drawing for create => http://svg.tutorial.aptico.de/start3.php?knr=10&kname=Pfade&uknr=10.8&ukname=A%20und%20a%20-%20Bogenkurven
            final Pixmap[] pixmap = new Pixmap[1];
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {

                    //replace Template with values

                    String width = Float.toString(Gdx.graphics.getWidth());
                    String height = Float.toString(Gdx.graphics.getHeight());

                    String centerX = Float.toString(ellipseRectangle.getCenterPosX());
                    String posY = Float.toString(Gdx.graphics.getHeight() - ellipseRectangle.getY()); // Y flipped
                    String maxY = Float.toString(Gdx.graphics.getHeight() - ellipseRectangle.getMaxY()); // Y flipped
                    String radiusX = Float.toString(ellipseRectangle.getHalfWidth());
                    String radiusY = Float.toString(ellipseRectangle.getHalfHeight());
                    String borderSize = Float.toString(HelpWindow.this.style.borderSize);

                    Color color = HelpWindow.this.style.backgroundColor;
                    String value = Integer
                            .toHexString(((int) (255 * color.r) << 16) | ((int) (255 * color.g) << 8) | ((int) (255 * color.b)));
                    while (value.length() < 6)
                        value = "0" + value;
                    String fillColor = "#" + value;
                    String fillOpacity = Float.toString(color.a);

                    color = HelpWindow.this.style.borderColor;
                    value = Integer
                            .toHexString(((int) (255 * color.r) << 16) | ((int) (255 * color.g) << 8) | ((int) (255 * color.b)));
                    while (value.length() < 6)
                        value = "0" + value;
                    String borderColor = "#" + value;
                    String borderOpacity = Float.toString(color.a);

                    String svgString = SVG_TEMPLATE.replaceAll("#WIDTH#", width);
                    svgString = svgString.replaceAll("#HEIGHT#", height);
                    svgString = svgString.replaceAll("#FILLCOLOR#", fillColor);
                    svgString = svgString.replaceAll("#FILLOPACITY#", fillOpacity);
                    svgString = svgString.replaceAll("#BORDERCOLOR#", borderColor);
                    svgString = svgString.replaceAll("#BORDEROPACITY#", borderOpacity);
                    svgString = svgString.replaceAll("centerX", centerX);
                    svgString = svgString.replaceAll("posY", posY);
                    svgString = svgString.replaceAll("radiusX", radiusX);
                    svgString = svgString.replaceAll("radiusY", radiusY);
                    svgString = svgString.replaceAll("maxY", maxY);
                    svgString = svgString.replaceAll("#BORDERSIZE#", borderSize);

                    //create a InputStream from SVG-String
                    InputStream stream = new ByteArrayInputStream(svgString.getBytes(Charset.forName("UTF-8")));

                    try {
                        pixmap[0] = Utils.getPixmapFromBitmap(PlatformConnector.getSvg("",stream, PlatformConnector.SvgScaleType.NONE, 1));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    // create texture on GlThread
                    Gdx.app.postRunnable(new Runnable() {
                        @Override
                        public void run() {
                            Texture texture = new Texture(new PixmapTextureData(pixmap[0], Pixmap.Format.RGBA8888, false, true));
                            TextureRegion region = new TextureRegion(texture);
                            setStageBackground(new TextureRegionDrawable(region));
                        }
                    });
                }
            });
            thread.start();
        }
        super.show();
    }

    public static CB_RectF getHelpEllipseFromActor(Actor actor) {
        Vector2 stagePos = actor.localToStageCoordinates(new Vector2(0, 0));
        return new CB_RectF(stagePos.x - CB.scaledSizes.MARGIN, stagePos.y - CB.scaledSizes.MARGIN, actor.getWidth() + CB.scaledSizes.MARGINx2,
                actor.getHeight() + CB.scaledSizes.MARGINx2);
    }

    public void setStyle(HelpWindowStyle style) {
        this.style = style;
    }

    public static class HelpWindowStyle {
        public Color backgroundColor, borderColor, fontColor;
        public BitmapFont font;
        public float borderSize;
    }
}


text:
'use strict';

var parser = require('php-parser');
var filter = require('./helpers/filter');
var serialize = require('./helpers/serializer');
var Method = require('./method');
var Property = require('./property');
var Constant = require('./constant');
var traits = require('./helpers/traits');

/**
 * @constructor
 */
var Class = function Class(ast) {
    this.ast = ast;
};

/**
 * Sets the class name
 */
Class.prototype.setName = function(name) {
    this.ast.name = name;
    return this;
};

/**
 * Extends with the specified classname
 */
Class.prototype.setExtends = function(name) {
    if(name) {
        var ast = parser.parseEval('class a extends '+name+' {}');
        this.ast.extends = ast.children[0].extends;
    } else {
        this.ast.extends = null;
    }
    return this;
};

/**
 * Sets a list of implementation classes
 */
Class.prototype.setImplements = function(names) {
  if (Array.isArray(names)) names = names.join(', ');
  if(names) {
    var ast = parser.parseEval('class a implements '+names+' {}');
    this.ast.implements = ast.children[0].implements;
  } else {
    this.ast.implements = null;
  }
  return this;
};

/**
 * Gets a list of implemented classes
 */
Class.prototype.getImplements = function() {
  if (!this.ast.implements) {
    return []
  }

  return this.ast.implements.map(function (_interface) {
    return _interface.resolution === 'rn'
      ? 'namespace\\' + _interface.name
      : _interface.name;
  });
}

/**
 * Adds a new class implement (if not already defined)
 */
Class.prototype.addImplements = function(name) {
    var list = this.getImplements();
    if (list.indexOf(name) === -1) {
        list.push(name);
        this.setImplements(list);
    }
    return this;
};

Class.prototype.setTraits = traits.setTraits;

Class.prototype.getTraits = traits.getTraits;

Class.prototype.addTrait = traits.addTrait;

/**
 * Retrieves a class property
 */
Class.prototype.getProperty = function(name) {
    return Property.locate(this.ast.body, name);
};

/**
 * Sets a property value
 */
Class.prototype.setProperty = function(name, value, flags) {

    var property = this.getProperty(name);
    if (!property) {
        // append the function
        var ast = parser.parseEval('class a { \n' +
            flags + ' $' + name + (
                value ? ' = ' + value : ''
            ) + ';\n' +
        ' }');
        this.ast.body.unshift(
            ast.children[0].body[0]
        );
    } else {
        if (typeof flags !== 'undefined') property.setFlags(flags);
        if (typeof value !== 'undefined') property.setValue(value);
    }

};

/**
 * Sets a constant value
 */
Class.prototype.getConstant = function(name) {
    return Constant.locate(this.ast.body, name);
};

/**
 * Sets a constant value
 */
Class.prototype.setConstant = function(name, value) {
    var constant = this.getConstant(name);
    if (!constant) {
        // append the function
        var ast = parser.parseEval('class a { \n' +
            'const ' + name + (
                value ? ' = ' + value : ''
            ) + ';\n' +
        ' }');
        this.ast.body.unshift(
            ast.children[0].body[0]
        );
    } else {
        if (typeof value !== 'undefined') constant.setValue(value);
    }
    return this;
};

/**
 * Lookup for a function
 */
Class.prototype.getMethod = function(name) {
    return Method.locate(this.ast.body, name);
};

/**
 * Appends or update an function
 */
Class.prototype.setMethod = function(name, args, body, flags) {
    var method = this.getMethod(name);
    if (!method) {
        // append the function
        var ast = parser.parseEval('class a { \n' +
            flags + ' function ' + name + '(' + args +  ') {\n' +
                body + '\n' +
            '}\n' +
        ' }');
        this.ast.body.push(
            ast.children[0].body[0]
        );
    } else {
        // update the function
        if (typeof flags !== 'undefined') method.setFlags(flags);
        if (typeof args !== 'undefined') method.setArgs(args);
        if (typeof body !== 'undefined') method.setCode(body);
    }
    return this;
};

/**
 * Locate the node in the specified ast
 */
Class.locate = function(ast, name) {
  return filter(ast, 'class', function(node) {
    if (!name || node.name === name) {
      return new Class(node);
    }
  });
};

module.exports = Class;


text:
<?php

namespace EcommerceBundle\Controller;

use EcommerceBundle\Entity\Products;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

/**
 * Product controller.
 *
 */
class ProductsAdminController extends Controller
{
    /**
     * Lists all product entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $products = $em->getRepository('EcommerceBundle:Products')->findAll();

        return $this->render('EcommerceBundle:Administration:Products/layout/index.html.twig', array(
            'products' => $products,
        ));
    }

    /**
     * Creates a new product entity.
     *
     */
    public function newAction(Request $request)
    {
        $product = new Products();
        $form = $this->createForm('EcommerceBundle\Form\ProductsType', $product);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($product);
            $em->flush();

            return $this->redirectToRoute('adminProducts_show', array('id' => $product->getId()));
        }

        return $this->render('EcommerceBundle:Administration:Products/layout/new.html.twig', array(
            'product' => $product,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a product entity.
     *
     */
    public function showAction(Products $product)
    {
        $deleteForm = $this->createDeleteForm($product);

        return $this->render('EcommerceBundle:Administration:Products/layout/show.html.twig', array(
            'product' => $product,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing product entity.
     *
     */
    public function editAction(Request $request, Products $product)
    {
        $deleteForm = $this->createDeleteForm($product);
        $editForm = $this->createForm('EcommerceBundle\Form\ProductsType', $product);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('adminProducts_show', array('id' => $product->getId()));
        }

        return $this->render('EcommerceBundle:Administration:Products/layout/edit.html.twig', array(
            'product' => $product,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a product entity.
     *
     */
    public function deleteAction(Request $request, Products $product)
    {
        $form = $this->createDeleteForm($product);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($product);
            $em->flush();
        }

        return $this->redirectToRoute('adminProducts_index');
    }

    /**
     * Creates a form to delete a product entity.
     *
     * @param Products $product The product entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(Products $product)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('adminProducts_delete', array('id' => $product->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

 <item android:id="@+id/option_service_url"
          android:title="@string/menu_service_url"
          android:showAsAction="never|withText" />
    <item android:id="@+id/option_user_number"
          android:title="@string/menu_user_number"
          android:showAsAction="never|withText" />

</menu>


text:
package guru.breakthemonolith.docker;

import org.force66.vobase.ValueObjectBase;

/**
 * Describes a docker compose environment.
 *
 * @author D. Ashmore
 *
 */
public class DockerComposeConfiguration extends ValueObjectBase {

	private String configYamlFileName;
	private String projectName;

	public DockerComposeConfiguration(String configurationYamlFileName) {
		this.setConfigYamlFileName(configurationYamlFileName);
	}

	public String getConfigYamlFileName() {
		return configYamlFileName;
	}

	public void setConfigYamlFileName(String configurationYamlFileName) {
		this.configYamlFileName = configurationYamlFileName;
	}

	public String getProjectName() {
		return projectName;
	}

	public void setProjectName(String projectName) {
		this.projectName = projectName;
	}

}


text:
/*
 Local Storage support for the JS Bindings for iOS.
 Works on cocos2d-iphone and cocos2d-x.
 */

#ifndef __JSB_LOCALSTORAGE_H
#define __JSB_LOCALSTORAGE_H

#include <stdio.h>
#include <stdlib.h>

/** Initializes the database. If path is null, it will create an in-memory DB */
void localStorageInit( const char *fullpath);

/** Frees the allocated resources */
void localStorageFree();

/** sets an item in the LS */
void localStorageSetItem( const char *key, const char *value);

/** gets an item from the LS */
const char* localStorageGetItem( const char *key );

/** removes an item from the LS */
void localStorageRemoveItem( const char *key );

#endif // __JSB_LOCALSTORAGE_H


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Cat. Lich. Univers. 7: 209 (1931)

#### Original name
Fulgensia lubrica (Stizenb.) Gyeln.

### Remarks
null


text:
//
//  MainViewController.m
//
// Copyright (c) 2014. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "MainViewController.h"
#import "LeftPanelViewController.h"

#define CENTER_TAG 1
#define LEFT_PANEL_TAG 2

#define CORNER_RADIUS 4

#define SLIDE_TIMING .25
#define PANEL_WIDTH 60
#define IPAD_PANEL_WIDTH 500

@implementation MainViewController

@synthesize centerViewController;

#pragma mark -
#pragma mark View Did Load/Unload

-(void)viewDidLoad {
    [super viewDidLoad];
    [self setupView];

    [[self navigationController] setNavigationBarHidden:YES animated:YES];

}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

#pragma mark -
#pragma mark View Will/Did Appear

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
	[super viewDidAppear:animated];
}

#pragma mark -
#pragma mark View Will/Did Disappear

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
        if(toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
        {
            [self changeTheViewToPortrait:YES andDuration:duration];
        }
        else if(toInterfaceOrientation == UIInterfaceOrientationLandscapeRight || toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft)
        {
            //self.view = landscapeView;
            [self changeTheViewToPortrait:NO andDuration:duration];
        }
        [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    }
}

- (void) changeTheViewToPortrait:(BOOL)portrait andDuration:(NSTimeInterval)duration
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:duration];
    //CGRect rectQuote;

    if(portrait)
    {
        //change the view and subview frames for the portrait view
        /*UIImage *img = [UIImage imageNamed:@"aum_360-Portrait.png"];
         [backgroungImage setImage:img];

         CGRect rectButton = CGRectMake((backgroungImage.bounds.origin.x - 50), (backgroungImage.bounds.origin.y + 180), backgroungImage.bounds.size.width, backgroungImage.bounds.size.height);
         [backgroungImage setFrame:rectButton];*/

        //rectQuote = CGRectMake((collectionView.bounds.origin.x), (collectionView.bounds.origin.y + 103),
        //                       (collectionView.bounds.size.width), collectionView.bounds.size.height);
    }
    else
    {
        //[self.view setFrame:[[UIScreen mainScreen] bounds]];

        //change the view and subview  frames for the landscape view
        /*UIImage *img = [UIImage imageNamed:@"aum_360-Landscape.png"];
         [backgroungImage setImage:img]; */

        //rectQuote = CGRectMake((collectionView.bounds.origin.x + 200), (collectionView.bounds.origin.y + 170),
        //                       (collectionView.bounds.size.width + 100), collectionView.bounds.size.height);

    }

    //[collectionView setFrame:rectQuote];

    [UIView commitAnimations];
}

#pragma mark -
#pragma mark Setup View

-(void)setupView {

   	NSLog(@"Debug Setting up MainViewController...");

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
        // nothing we are phone
        self.centerViewController = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
    }
    else
    {
        self.centerViewController = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
    }

	self.centerViewController.view.tag = CENTER_TAG;
	self.centerViewController.delegate = self;
	[self.view addSubview:self.centerViewController.view];
	[self addChildViewController:centerViewController];
	[centerViewController didMoveToParentViewController:self];

    self.centerViewController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin |
    UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin |
    UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;

    self.centerViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

    self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin |
    UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin |
    UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;

   	NSLog(@"Debug Setting up Gestures...");

	[self setupGestures];
}

-(void)showCenterViewWithShadow:(BOOL)value withOffset:(double)offset {
	if (value) {
		[centerViewController.view.layer setCornerRadius:CORNER_RADIUS];
		[centerViewController.view.layer setShadowColor:[UIColor blackColor].CGColor];
		[centerViewController.view.layer setShadowOpacity:0.8];
		[centerViewController.view.layer setShadowOffset:CGSizeMake(offset, offset)];

	} else {
		[centerViewController.view.layer setCornerRadius:0.0f];
		[centerViewController.view.layer setShadowOffset:CGSizeMake(offset, offset)];
	}
}

-(void)resetMainView {
	// remove left and right views, and reset variables, if needed
	if (_leftPanelViewController != nil) {
		[self.leftPanelViewController.view removeFromSuperview];
		self.leftPanelViewController = nil;
		centerViewController.leftSettingsButton.tag = 1;
		self.showingLeftPanel = NO;
	}
	// remove view shadows
	[self showCenterViewWithShadow:NO withOffset:0];
}

-(UIView *)getLeftView {
	// init view if it doesn't already exist
	if (_leftPanelViewController == nil)
	{
		// this is where you define the view for the left panel
		self.leftPanelViewController = [[LeftPanelViewController alloc] initWithNibName:@"LeftPanelViewController" bundle:nil];
		self.leftPanelViewController.view.tag = LEFT_PANEL_TAG;
		self.leftPanelViewController.delegate = centerViewController;

		[self.view addSubview:self.leftPanelViewController.view];

		[self addChildViewController:_leftPanelViewController];
		[_leftPanelViewController didMoveToParentViewController:self];

		_leftPanelViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
	}

	self.showingLeftPanel = YES;

	// setup view shadows
	[self showCenterViewWithShadow:YES withOffset:-2];

	UIView *view = self.leftPanelViewController.view;
	return view;
}

#pragma mark -
#pragma mark Swipe Gesture Setup/Actions

#pragma mark - setup

-(void)setupGestures {
	UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(movePanel:)];
	[panRecognizer setMinimumNumberOfTouches:1];
	[panRecognizer setMaximumNumberOfTouches:1];
	[panRecognizer setDelegate:self];

	[centerViewController.view addGestureRecognizer:panRecognizer];
}

-(void)movePanel:(id)sender {
	[[[(UITapGestureRecognizer*)sender view] layer] removeAllAnimations];

	CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view];
	CGPoint velocity = [(UIPanGestureRecognizer*)sender velocityInView:[sender view]];

	if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) {
        UIView *childView = nil;

        if(velocity.x > 0) {
            childView = [self getLeftView];
        }

        // make sure the view we're working with is front and center
        [self.view sendSubviewToBack:childView];
        [[sender view] bringSubviewToFront:[(UIPanGestureRecognizer*)sender view]];
	}

	if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) {

        if(velocity.x > 0) {
            // NSLog(@"gesture went right");
        } else {
            // NSLog(@"gesture went left");
        }

        if (!_showPanel) {
            [self movePanelToOriginalPosition];
        } else {
            if (_showingLeftPanel) {
                [self movePanelRight];
            }
        }
	}

	if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateChanged) {
        if(velocity.x > 0) {
            // NSLog(@"gesture went right");
        } else {
            // NSLog(@"gesture went left");
        }

        // are we more than halfway, if so, show the panel when done dragging by setting this value to YES (1)
        _showPanel = abs([sender view].center.x - centerViewController.view.frame.size.width/2) > centerViewController.view.frame.size.width/2;

        // allow dragging only in x coordinates by only updating the x coordinate with translation position
        [sender view].center = CGPointMake([sender view].center.x + translatedPoint.x, [sender view].center.y);
        [(UIPanGestureRecognizer*)sender setTranslation:CGPointMake(0,0) inView:self.view];

        // if you needed to check for a change in direction, you could use this code to do so
        if(velocity.x*_preVelocity.x + velocity.y*_preVelocity.y > 0) {
            // NSLog(@"same direction");
        } else {
            // NSLog(@"opposite direction");
        }

        _preVelocity = velocity;
	}
}

#pragma mark -
#pragma mark Delegate Actions

-(void)movePanelRight {
	UIView *childView = [self getLeftView];
	[self.view sendSubviewToBack:childView];

	[UIView animateWithDuration:SLIDE_TIMING delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{

        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        {
            centerViewController.view.frame = CGRectMake(self.view.frame.size.width - IPAD_PANEL_WIDTH, 0, self.view.frame.size.width, self.view.frame.size.height);
        }
        else
        {
            centerViewController.view.frame = CGRectMake(self.view.frame.size.width - PANEL_WIDTH, 0, self.view.frame.size.width, self.view.frame.size.height);
        }
	 }
	 completion:^(BOOL finished) {
		 if (finished) {
			 centerViewController.leftSettingsButton.tag = 0;
		 }
	 }];
}

-(void)movePanelToOriginalPosition
{
	[UIView animateWithDuration:SLIDE_TIMING delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
		 centerViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
	 }
	 completion:^(BOOL finished) {
		 if (finished) {
			 [self resetMainView];
		 }
	 }];
}

#pragma mark -
#pragma mark Default System Code

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end


text:
package main

import "path/filepath"

func writeEnvScripts(env *Environment, goenv_bin string) {
	writeWrap(env, filepath.Join(goenv_bin, "activate"), WriteEnvUnixFile)
	writeWrap(env, filepath.Join(goenv_bin, "activate.ps1"), WriteEnvPSFile)
}


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

using ASC.Core;
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.Web.Core;
using ASC.Web.People.Core;
using ASC.Web.People.Resources;
using ASC.Web.Studio;
using ASC.Web.Studio.Controls.Common;
using ASC.Web.Studio.Utility;

namespace ASC.Web.People
{
    public partial class Birthdays : MainPage
    {
        protected List<UserInfo> todayBirthdays;
        protected List<BirthdayWrapper> upcomingBirthdays;

        protected void Page_Load(object sender, EventArgs e)
        {
            var isBirthdaysAvailable = WebItemManager.Instance.GetSubItems(PeopleProduct.ID).Any(item => item.ID == WebItemManager.BirthdaysProductID);

            if (!isBirthdaysAvailable)
            {
                Response.Redirect(PeopleProduct.GetStartURL());
            }

            RenderScripts();

            todayBirthdays = GetTodayBirthdays();
            upcomingBirthdays = GetUpcomingBirthdays().ToList();

            if (upcomingBirthdays == null || !upcomingBirthdays.Any())
            {
                upcomingEmptyContent.Controls.Add(new EmptyScreenControl
                {
                    ImgSrc = VirtualPathUtility.ToAbsolute("~/Products/People/App_Themes/default/images/birthdayEmpScr.png"),
                    Header = BirthdaysResource.BirthdayEmptyScreenCaption,
                    Describe = BirthdaysResource.BirthdaysEmptyModuleDescription
                });
            }

            Title = HeaderStringHelper.GetPageTitle(BirthdaysResource.BirthdaysModuleTitle);
        }

        protected void RenderScripts()
        {
            Page
                .RegisterStyle("~/Products/People/App_Themes/default/css/birthdays.css")
                .RegisterBodyScripts("~/Products/People/js/birthdays.js");
        }

        private static List<UserInfo> GetTodayBirthdays()
        {
            var today = TenantUtil.DateTimeNow();
            return (from u in CoreContext.UserManager.GetUsers(EmployeeStatus.Active, EmployeeType.User)
                    where u.BirthDate.HasValue && u.BirthDate.Value.Month.Equals(today.Month) && u.BirthDate.Value.Day.Equals(today.Day)
                    orderby u.DisplayUserName()
                    select u)
                .ToList();
        }

        private class BirthDateComparer : IComparer<DateTime>
        {
            public int Compare(DateTime x, DateTime y)
            {
                var today = TenantUtil.DateTimeNow();
                var leap = new DateTime(2000, today.Month, today.Day);

                var dx = new DateTime(2000, x.Month, x.Day).DayOfYear - leap.DayOfYear;
                var dy = new DateTime(2000, y.Month, y.Day).DayOfYear - leap.DayOfYear;

                if (dx < 0 && dy >= 0) return 1;
                if (dx >= 0 && dy < 0) return -1;

                return dx.CompareTo(dy);
            }
        }

        private static IEnumerable<BirthdayWrapper> GetUpcomingBirthdays()
        {
            var today = TenantUtil.DateTimeNow();

            return CoreContext.UserManager.GetUsers(EmployeeStatus.Active, EmployeeType.User)
                              .Where(x => x.BirthDate.HasValue)
                              .OrderBy(x => x.BirthDate.Value, new BirthDateComparer())
                              .GroupBy(x => new DateTime(2000, x.BirthDate.Value.Month, x.BirthDate.Value.Day)) // 29 february
                              .Select(x => new BirthdayWrapper { Date = x.Key, Users = x.ToList() })
                              .SkipWhile(x => x.Date.Month.Equals(today.Month) && x.Date.Day.Equals(today.Day))
                              .Take(10);
        }

        protected bool IsInRemindList(Guid userID)
        {
            return BirthdaysNotifyClient.Instance.IsSubscribe(SecurityContext.CurrentAccount.ID, userID);
        }

        protected class BirthdayWrapper
        {
            public DateTime Date;
            public List<UserInfo> Users;
        }
    }
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>The end of ROSI, one can but hope</title>

	<meta name="author" content="raesene">

	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<link href="https://raesene.github.io/assets/resources/bootstrap/css/bootstrap.min.css" rel="stylesheet">
	<link href="https://raesene.github.io/assets/resources/font-awesome/css/font-awesome.min.css" rel="stylesheet">
	<link href="https://raesene.github.io/assets/resources/syntax/syntax.css" rel="stylesheet">
	<link href="https://raesene.github.io/assets/css/style.css" rel="stylesheet">

	<link rel="alternate" type="application/rss+xml" title="" href="https://raesene.github.io/feed.xml">

			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
				Toggle navigation

			</button>

				Raesene's Ramblings

Home

Categories

Tags

		<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">

		</button>

Home

Categories

Tags

Top of Page

        Raesene's Ramblings

	Security Geek, Kubernetes, Docker, Ruby, Hillwalking

The end of ROSI, one can but hope

	   April
	   23rd,

	   2004

information security: RoSI: R.I.P.

There's an interesting link over at Axel Eble's blog to a report that, hopefully, people are geting round to the throught that security is not something that you calculate the R.O.I on, more that you view it like insurance or fire control system, as loss avoidance.

The problem with calculating ROSI has always been quantification, and it's always struck me that people that suggest it as a good way of justifying security spend, come up very short on specifics when asked, how it would actually be implemented.....

					General Security (88)

Share Post

          Twitter

          Facebook

          Google+

raesene

Security Geek, Kubernetes, Docker, Ruby, Hillwalking

← Previous

Next →

				© 2022 raesene with Jekyll. Theme: dbyll by dbtek.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
        <meta name="generator" content="Doxygen 1.8.13"/>

        <title>CubbyFlow: Member List</title>

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

        <link href="doxygen.css" rel="stylesheet" type="text/css" />
        <link href="customdoxygen.css" rel="stylesheet" type="text/css"/>
        <link href='https://fonts.googleapis.com/css?family=Roboto+Slab' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

        <link href="jquery.smartmenus.bootstrap.css" rel="stylesheet">

                    CubbyFlow v0.71

CubbyFlow

ParticleEmitter3

CubbyFlow::ParticleEmitter3 Member List

This is the complete list of members for CubbyFlow::ParticleEmitter3, including all inherited members.

GetIsEnabled() const	CubbyFlow::ParticleEmitter3

GetTarget() const	CubbyFlow::ParticleEmitter3

OnBeginUpdateCallback typedef	CubbyFlow::ParticleEmitter3

OnSetTarget(const ParticleSystemData3Ptr &particles)	CubbyFlow::ParticleEmitter3	protectedvirtual

OnUpdate(double currentTimeInSeconds, double timeIntervalInSeconds)=0	CubbyFlow::ParticleEmitter3	protectedpure virtual

operator=(const ParticleEmitter3 &)=default	CubbyFlow::ParticleEmitter3

operator=(ParticleEmitter3 &&) noexcept=default	CubbyFlow::ParticleEmitter3

ParticleEmitter3()=default	CubbyFlow::ParticleEmitter3

ParticleEmitter3(const ParticleEmitter3 &)=default	CubbyFlow::ParticleEmitter3

ParticleEmitter3(ParticleEmitter3 &&) noexcept=default	CubbyFlow::ParticleEmitter3

SetIsEnabled(bool enabled)	CubbyFlow::ParticleEmitter3

SetOnBeginUpdateCallback(const OnBeginUpdateCallback &callback)	CubbyFlow::ParticleEmitter3

SetTarget(const ParticleSystemData3Ptr &particles)	CubbyFlow::ParticleEmitter3

Update(double currentTimeInSeconds, double timeIntervalInSeconds)	CubbyFlow::ParticleEmitter3

~ParticleEmitter3()=default	CubbyFlow::ParticleEmitter3	virtual

<address class="footer">
Generated on Thu Jul 15 2021 02:18:16 for CubbyFlow by

 1.8.13
</address>


text:
const extractBodyObjectFromDom = require('./parseDom').getBodyObject
const extractBodyHtmlFromDom = require('./parseDom').getBodyHtml
const extractMetadataFromDom = require('./parseDom').getMetadata
const extractJsonFromDom = require('./parseDom').getJson

const extractMetadataFromJson = require('./parseJson').getMetadata

const mergeMetadata = require('./mergeMetadata')

module.exports = function parse ($) {
  const bodyObject = extractBodyObjectFromDom($)
  const bodyHtml = extractBodyHtmlFromDom($)
  const metadata1 = extractMetadataFromDom($)

  const metadata2 = extractMetadataFromJson(extractJsonFromDom($))

  return {
    body: {
      html: bodyHtml,
      object: bodyObject
    },
    metadata: mergeMetadata(metadata1, metadata2)
  }
}


text:
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  v8_fuzzer::FuzzerSupport* support = v8_fuzzer::FuzzerSupport::Get();
  v8::Isolate* isolate = support->GetIsolate();

  v8::Isolate::Scope isolate_scope(isolate);
  v8::HandleScope handle_scope(isolate);
  v8::Context::Scope context_scope(support->GetContext());
  v8::TryCatch try_catch(isolate);

  if (size > INT_MAX) return 0;
  v8::Local<v8::String> source;
  if (!v8::String::NewFromOneByte(isolate, data, v8::NewStringType::kNormal,
                                  static_cast<int>(size))
           .ToLocal(&source)) {
    return 0;
  }

  v8::JSON::Parse(isolate, source).IsEmpty();
  return 0;
}


text:
//=================================================================================================

//=================================================================================================

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/HermitianMatrix.h>
#include <blaze/math/SymmetricMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatdmatadd/OperationTest.h>
#include <blazetest/system/MathTest.h>

//=================================================================================================
//
//  MAIN FUNCTION
//
//=================================================================================================

//*************************************************************************************************
int main()
{
   std::cout << "   Running 'HDaSDb'..." << std::endl;

   using blazetest::mathtest::NumericA;
   using blazetest::mathtest::NumericB;

   try
   {
      // Matrix type definitions
      typedef blaze::HermitianMatrix< blaze::DynamicMatrix<NumericA> >  HDa;
      typedef blaze::SymmetricMatrix< blaze::DynamicMatrix<NumericB> >  SDb;

      // Creator type definitions
      typedef blazetest::Creator<HDa>  CHDa;
      typedef blazetest::Creator<SDb>  CSDb;

      // Running tests with small matrices
      for( size_t i=0UL; i<=9UL; ++i ) {
         RUN_DMATDMATADD_OPERATION_TEST( CHDa( i ), CSDb( i ) );
      }

      // Running tests with large matrices
      RUN_DMATDMATADD_OPERATION_TEST( CHDa(  67UL ), CSDb(  67UL ) );
      RUN_DMATDMATADD_OPERATION_TEST( CHDa( 128UL ), CSDb( 128UL ) );
   }
   catch( std::exception& ex ) {
      std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix addition:\n"
                << ex.what() << "\n";
      return EXIT_FAILURE;
   }

   return EXIT_SUCCESS;
}
//*************************************************************************************************