text:
package com.streamsets.pipeline.lib.parser.avro;

import com.streamsets.pipeline.api.OnRecordError;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.Stage;
import com.streamsets.pipeline.lib.parser.DataParser;
import com.streamsets.pipeline.lib.parser.DataParserException;
import com.streamsets.pipeline.lib.parser.DataParserFactory;
import com.streamsets.pipeline.lib.parser.DataParserFactoryBuilder;
import com.streamsets.pipeline.lib.parser.DataParserFormat;
import com.streamsets.pipeline.lib.util.SdcAvroTestUtil;
import com.streamsets.pipeline.sdk.ContextInfoCreator;
import com.streamsets.pipeline.stage.common.HeaderAttributeConstants;
import org.apache.avro.Schema;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.DatumWriter;
import org.junit.Assert;
import org.junit.Test;

import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static com.streamsets.pipeline.config.OriginAvroSchemaSource.SOURCE;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.SCHEMA_KEY;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.SCHEMA_SOURCE_KEY;

public class TestAvroDataFileParser {

  @Test
  public void testAvroDataFileParser() throws Exception {
    File avroDataFile = SdcAvroTestUtil.createAvroDataFile();
    DataParser avroDataFileParser = getDataParser(avroDataFile, 1024, null);

    Record parse = avroDataFileParser.parse();
    Assert.assertNotNull(parse);
    Assert.assertEquals("244::1", avroDataFileParser.getOffset());
    Assert.assertNotNull(parse.getHeader().getAttribute(HeaderAttributeConstants.AVRO_SCHEMA));
    Assert.assertEquals(Schema.parseJson(SdcAvroTestUtil.AVRO_SCHEMA), Schema.parseJson(parse.getHeader().getAttribute(HeaderAttributeConstants.AVRO_SCHEMA)));

    parse = avroDataFileParser.parse();
    Assert.assertNotNull(parse);
    Assert.assertEquals("244::2", avroDataFileParser.getOffset());

    parse = avroDataFileParser.parse();
    Assert.assertNotNull(parse);
    Assert.assertEquals("244::3", avroDataFileParser.getOffset());

    parse = avroDataFileParser.parse();
    Assert.assertNull(parse);
    Assert.assertEquals("-1", avroDataFileParser.getOffset());

  }

  @Test
  public void testAvroDataFileParserOffset() throws Exception {
    File avroDataFile = SdcAvroTestUtil.createAvroDataFile();
    DataParser dataParser = getDataParser(avroDataFile, 1024, null);

    Record parse = dataParser.parse();
    Assert.assertNotNull(parse);
    Assert.assertEquals("244::1", dataParser.getOffset());

    dataParser = getDataParser(avroDataFile, 1024, dataParser.getOffset());
    parse = dataParser.parse();
    Assert.assertNotNull(parse);
    Assert.assertEquals("244::2", dataParser.getOffset());

    dataParser = getDataParser(avroDataFile, 1024, dataParser.getOffset());
    parse = dataParser.parse();
    Assert.assertNotNull(parse);
    Assert.assertEquals("244::3", dataParser.getOffset());

    dataParser = getDataParser(avroDataFile, 1024, dataParser.getOffset());
    parse = dataParser.parse();
    Assert.assertNull(parse);
    Assert.assertEquals("-1", dataParser.getOffset());

  }

  public static final String AVRO_SCHEMA = "{\n"
    +"\"type\": \"record\",\n"
    +"\"name\": \"Employee\",\n"
    +"\"fields\": [\n"
    +" {\"name\": \"name\", \"type\": \"string\"},\n"
    +" {\"name\": \"id\", \"type\": \"int\"}\n"
    +"]}";

  private static final String[] NAMES = {
    "Brock", "Hari"
  };

  @Test
  public void testIncorrectOffset() throws Exception {
    File avroDataFile = SdcAvroTestUtil.createAvroDataFile();
    avroDataFile.delete();
    Schema schema = new Schema.Parser().parse(AVRO_SCHEMA);
    DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema);
    DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter);
    dataFileWriter.create(schema, avroDataFile);
    for (int i = 0; i < 5; i++) {
      GenericRecord r = new GenericData.Record(schema);
      r.put("name", NAMES[i % NAMES.length]);
      r.put("id", i);
      dataFileWriter.setSyncInterval(1073741824);
      dataFileWriter.append(r);
      dataFileWriter.sync();
    }
    dataFileWriter.flush();
    dataFileWriter.close();
    DataParserFactoryBuilder dataParserFactoryBuilder = new DataParserFactoryBuilder(getContext(),
      DataParserFormat.AVRO);
    DataParserFactory factory = dataParserFactoryBuilder
        .setMaxDataLen(1024 * 1024)
        .setOverRunLimit(1000 * 1000)
        .setConfig(SCHEMA_SOURCE_KEY, SOURCE)
        .build();
    DataParser dataParser = factory.getParser(avroDataFile, null);
    Map<String, Record> records = new HashMap<>();
    Record record;
    while((record = dataParser.parse()) != null) {
      records.put(dataParser.getOffset(), record);
    }
    Assert.assertEquals(String.valueOf(records), 5, records.size());
    Assert.assertEquals(0, records.get("141::1").get("/id").getValueAsInteger());
    Assert.assertEquals(1, records.get("166::1").get("/id").getValueAsInteger());
    Assert.assertEquals(2, records.get("190::1").get("/id").getValueAsInteger());
    Assert.assertEquals(3, records.get("215::1").get("/id").getValueAsInteger());
    Assert.assertEquals(4, records.get("239::1").get("/id").getValueAsInteger());
  }

  private Stage.Context getContext() {
    return ContextInfoCreator.createSourceContext("i", false, OnRecordError.TO_ERROR,
      Collections.<String>emptyList());
  }

  private DataParser getDataParser(File file, int maxObjectLength, String readerOffset) throws DataParserException {
    DataParserFactoryBuilder dataParserFactoryBuilder = new DataParserFactoryBuilder(getContext(),
      DataParserFormat.AVRO);
    DataParserFactory factory = dataParserFactoryBuilder
      .setMaxDataLen(maxObjectLength)
      .setConfig(SCHEMA_KEY, SdcAvroTestUtil.AVRO_SCHEMA)
      .setOverRunLimit(1000)
      .build();
    return factory.getParser(file, readerOffset);
  }
}

redpajama_set_name: RedPajamaGithub


text:
Imports System.Data
Imports System.Data.Common
Imports EIDSS.model.Enums
Imports bv.common.Enums

Public Class VetAggregateAction_DB
    Inherits BaseDbService

    Public Sub New()
        ObjectName = "VetAggregateAction"
    End Sub

#Region "Flex Forms"

    ' Get Template for Human Case
    Public Function GetFFTemplate(ByVal strFFormTypeID As String, ByVal strDeterminantsList As String) As String
        Dim dt As New DataTable
        Dim cmd As IDbCommand

        cmd = CreateSPCommand("dbo.sp_FF_GetFFTemplate", Connection)
        AddParam(cmd, "@FFTypeID", strFFormTypeID)
        AddParam(cmd, "@strDeterminant", strDeterminantsList)
        AddParam(cmd, "@strUniRefTypes", "")

        ' EXACTLY Template
        dt.Clear()
        FillTable(cmd, dt)
        If Not dt.Rows.Count = 0 Then
            If Not dt.Rows(0).Item(0) Is DBNull.Value Then
                Return dt.Rows(0).Item(0).ToString
            End If
        End If

        ' UNI BY ALL

        cmd = CreateSPCommand("dbo.sp_FF_GetFFTemplateUni", Connection)
        AddParam(cmd, "@FFTypeID", strFFormTypeID)

        dt.Clear()
        FillTable(cmd, dt)
        If Not dt.Rows.Count = 0 Then
            If Not dt.Rows(0).Item(0) Is DBNull.Value Then
                Return dt.Rows(0).Item(0).ToString
            Else
                Return ""
            End If
        End If

        Return ""
    End Function

#End Region

    Public Const TableAggregateHeader As String = "AggregateHeader"
    Public Const TableDiagnosticMatrixVersion As String = "DiagnosticMatrixVersion"
    Public Const TableProphilacticMatrixVersion As String = "ProphilacticMatrixVersion"
    Public Const TableSanitaryMatrixVersion As String = "SanitaryMatrixVersion"
    Public Const TableSettings As String = "Settings"

    Public Overrides Function GetDetail(ByVal ID As Object) As DataSet
        Dim ds As New DataSet
        Try
            Dim cmd As IDbCommand = CreateSPCommand("spVetAggregateAction_SelectDetail")
            AddParam(cmd, "@idfAggrCase", ID)

            Dim AggregateCaseDetail_Adapter As DbDataAdapter = CreateAdapter(cmd)
            AggregateCaseDetail_Adapter.Fill(ds, TableAggregateHeader)
            CorrectTable(ds.Tables(0), TableAggregateHeader)
            CorrectTable(ds.Tables(1), TableSettings)
            CorrectTable(ds.Tables(2), TableDiagnosticMatrixVersion)
            CorrectTable(ds.Tables(3), TableProphilacticMatrixVersion)
            CorrectTable(ds.Tables(4), TableSanitaryMatrixVersion)
            ClearColumnsAttibutes(ds)
            If ID Is Nothing Then
                ID = NewIntID()
                Dim r As DataRow = ds.Tables(TableAggregateHeader).NewRow
                r("idfAggrCase") = ID
                r("idfsAggrCaseType") = CLng(AggregateCaseType.VetAggregateAction)
                r("strCaseID") = "(new)"

                If ds.Tables(TableDiagnosticMatrixVersion).Rows.Count > 0 Then
                    r("idfDiagnosticVersion") = ds.Tables(TableDiagnosticMatrixVersion).Rows(0)("idfVersion")
                End If
                If ds.Tables(TableProphilacticMatrixVersion).Rows.Count > 0 Then
                    r("idfProphylacticVersion") = ds.Tables(TableProphilacticMatrixVersion).Rows(0)("idfVersion")
                End If
                If ds.Tables(TableSanitaryMatrixVersion).Rows.Count > 0 Then
                    r("idfSanitaryVersion") = ds.Tables(TableSanitaryMatrixVersion).Rows(0)("idfVersion")
                End If

                r("idfEnteredByOffice") = eidss.model.Core.EidssUserContext.User.OrganizationID
                r("idfEnteredByPerson") = eidss.model.Core.EidssUserContext.User.EmployeeID
                r("datEnteredByDate") = DateTime.Now
                r("idfDiagnosticObservation") = NewIntID()
                r("idfProphylacticObservation") = NewIntID()
                r("idfSanitaryObservation") = NewIntID()
                ds.Tables(TableAggregateHeader).Rows.Add(r)
                ds.EnforceConstraints = False
                m_IsNewObject = True
            Else
                m_IsNewObject = False
            End If
            m_ID = ID
            Return ds

        Catch ex As Exception
            m_Error = New ErrorMessage(StandardError.FillDatasetError, ex)
            Return Nothing
        End Try
    End Function

    Public Overrides Function PostDetail(ByVal ds As DataSet, ByVal postType As Integer, Optional ByVal transaction As IDbTransaction = Nothing) As Boolean
        If ds Is Nothing Then Return True
        Try
            If (postType = bv.common.Enums.PostType.FinalPosting) Then
                If IsNewObject Then
                    m_IsNewObject = False
                    AddEvent(EventType.VetAggregateActionCreatedLocal, , False)
                ElseIf ds.Tables(TableAggregateHeader).Rows.Count > 0 Then
                    Dim r As DataRow = ds.Tables(TableAggregateHeader).Rows(0)
                    If r.HasVersion(DataRowVersion.Original) Then
                        If (Not r("idfsAdministrativeUnit").Equals(r("idfsAdministrativeUnit", DataRowVersion.Original))) _
                            OrElse (Not r("datStartDate").Equals(r("datStartDate", DataRowVersion.Original))) _
                            OrElse (Not r("datFinishDate").Equals(r("datFinishDate", DataRowVersion.Original))) Then
                            AddEvent(EventType.VetAggregateActionChangedLocal, , False)
                        End If
                    End If
                End If
            End If
            ExecPostProcedure("spAggregateCaseHeader_Post", ds.Tables(TableAggregateHeader), Connection, transaction)
        Catch ex As Exception
            m_Error = New ErrorMessage(StandardError.PostError, ex)
            Return False
        End Try
        Return True
    End Function

End Class


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_margin="20dp"
        android:padding="10dp"
        android:text="Get preferences"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:padding="10dp"
        android:text="String preferences: "
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/et_GetStringPref"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@id/textView2"
        android:ems="10"
        android:inputType="text"
        android:singleLine="true" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_GetStringPref"
        android:padding="10dp"
        android:text="Integer preferences: "
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/et_GetIntegerPref"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/et_GetStringPref"
        android:layout_below="@+id/et_GetStringPref"
        android:ems="10"
        android:inputType="number"
        android:singleLine="true" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_GetIntegerPref"
        android:padding="10dp"
        android:text="Long preferences: "
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/et_GetLongPref"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/et_GetStringPref"
        android:layout_below="@id/et_GetIntegerPref"
        android:ems="10"
        android:inputType="number"
        android:singleLine="true" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_GetLongPref"
        android:padding="10dp"
        android:text="Boolean preferences: "
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <CheckBox
        android:id="@+id/cb_GetBoolean"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/et_GetStringPref"
        android:layout_below="@id/et_GetLongPref"
        android:padding="10dp"
        android:text="False" />

    <TextView
        android:id="@+id/textView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/cb_GetBoolean"
        android:padding="10dp"
        android:text="Float preferences: "
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/et_GetFloatPref"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/et_GetStringPref"
        android:layout_below="@id/cb_GetBoolean"
        android:ems="10"
        android:inputType="numberDecimal"
        android:singleLine="true" />

    <Button
        android:id="@+id/btn_GetPref"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_GetFloatPref"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="58dp"
        android:text="Get preferences"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Button
        android:id="@+id/btn_RemoveAllPref"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btn_GetPref"
        android:layout_centerHorizontal="true"
        android:text="Remove all preferences"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>
<!-- From: file:/F:/Workspace/CommonSDK/Multidots/android/utils/src/main/res/layout/get_pref_act.xml -->


text:
#include "includes.h"
#include <assert.h>

#include "common.h"
#include "eloop.h"
#include "uuid.h"
#include "http_client.h"
#include "wps_defs.h"
#include "wps_upnp.h"
#include "wps_upnp_i.h"

/*
 * Event message generation (to subscribers)
 *
 * We make a separate copy for each message for each subscriber. This memory
 * wasted could be limited (adding code complexity) by sharing copies, keeping
 * a usage count and freeing when zero.
 *
 * Sending a message requires using a HTTP over TCP NOTIFY
 * (like a PUT) which requires a number of states..
 */

#define MAX_EVENTS_QUEUED 20	/* How far behind queued events */
#define MAX_FAILURES 10			/* Drop subscription after this many failures */

/* How long to wait before sending event */
#define EVENT_DELAY_SECONDS 0
#define EVENT_DELAY_MSEC 0

/*
 * Event information that we send to each subscriber is remembered in this
 * struct. The event cannot be sent by simple UDP; it has to be sent by a HTTP
 * over TCP transaction which requires various states.. It may also need to be
 * retried at a different address (if more than one is available).
 *
 * TODO: As an optimization we could share data between subscribers.
 */
struct wps_event_ {
	struct dl_list list;
	struct subscription *s;		/* parent */
	unsigned subscriber_sequence;	/* which event for this subscription */
	unsigned int retry;			/* which retry */
	struct subscr_addr *addr;	/* address to connect to */
	struct wpabuf *data;		/* event data to send */
	struct http_client *http_event;
};

/* event_clean -- clean sockets etc. of event
 * Leaves data, retry count etc. alone.
 */
static void event_clean(struct wps_event_ *e)
{
	if (e->s->current_event == e) {
		e->s->current_event = NULL;
	}
	http_client_free(e->http_event);
	e->http_event = NULL;
}

/* event_delete -- delete single unqueued event
 * (be sure to dequeue first if need be)
 */
static void event_delete(struct wps_event_ *e)
{
	wpa_printf(MSG_DEBUG, "WPS UPnP: Delete event %p", e);
	event_clean(e);
	wpabuf_free(e->data);
	os_free(e);
}

/* event_dequeue -- get next event from the queue
 * Returns NULL if empty.
 */
static struct wps_event_ *event_dequeue(struct subscription *s)
{
	struct wps_event_ *e;
	e = dl_list_first(&s->event_queue, struct wps_event_, list);
	if (e) {
		wpa_printf(MSG_DEBUG, "WPS UPnP: Dequeue event %p for " "subscription %p", e, s);
		dl_list_del(&e->list);
	}
	return e;
}

/* event_delete_all -- delete entire event queue and current event */
void event_delete_all(struct subscription *s)
{
	struct wps_event_ *e;
	while ((e = event_dequeue(s)) != NULL) {
		event_delete(e);
	}
	if (s->current_event) {
		event_delete(s->current_event);
		/* will set: s->current_event = NULL;  */
	}
}

/**
 * event_retry - Called when we had a failure delivering event msg
 * @e: Event
 * @do_next_address: skip address e.g. on connect fail
 */
static void event_retry(struct wps_event_ *e, int do_next_address)
{
	struct subscription *s = e->s;
	struct upnp_wps_device_sm *sm = s->sm;

	wpa_printf(MSG_DEBUG, "WPS UPnP: Retry event %p for subscription %p", e, s);
	event_clean(e);
	/* will set: s->current_event = NULL; */

	if (do_next_address) {
		e->retry++;
		wpa_printf(MSG_DEBUG, "WPS UPnP: Try address %d", e->retry);
	}
	if (e->retry >= dl_list_len(&s->addr_list)) {
		wpa_printf(MSG_DEBUG, "WPS UPnP: Giving up on sending event " "for %s", e->addr->domain_and_port);
		event_delete(e);
		s->last_event_failed = 1;
		if (!dl_list_empty(&s->event_queue)) {
			event_send_all_later(s->sm);
		}
		return;
	}
	dl_list_add(&s->event_queue, &e->list);
	event_send_all_later(sm);
}

static struct wpabuf *event_build_message(struct wps_event_ *e)
{
	struct wpabuf *buf;
	char *b;

	buf = wpabuf_alloc(1000 + wpabuf_len(e->data));
	if (buf == NULL) {
		return NULL;
	}
	wpabuf_printf(buf, "NOTIFY %s HTTP/1.1\r\n", e->addr->path);
	wpabuf_put_str(buf, "SERVER: Unspecified, UPnP/1.0, Unspecified\r\n");
	wpabuf_printf(buf, "HOST: %s\r\n", e->addr->domain_and_port);
	wpabuf_put_str(buf, "CONTENT-TYPE: text/xml; charset=\"utf-8\"\r\n" "NT: upnp:event\r\n" "NTS: upnp:propchange\r\n");
	wpabuf_put_str(buf, "SID: uuid:");
	b = wpabuf_put(buf, 0);
	uuid_bin2str(e->s->uuid, b, 80);
	wpabuf_put(buf, os_strlen(b));
	wpabuf_put_str(buf, "\r\n");
	wpabuf_printf(buf, "SEQ: %u\r\n", e->subscriber_sequence);
	wpabuf_printf(buf, "CONTENT-LENGTH: %d\r\n", (int)wpabuf_len(e->data));
	wpabuf_put_str(buf, "\r\n");	/* terminating empty line */
	wpabuf_put_buf(buf, e->data);
	return buf;
}

static void event_addr_failure(struct wps_event_ *e)
{
	struct subscription *s = e->s;

	e->addr->num_failures++;
	wpa_printf(MSG_DEBUG, "WPS UPnP: Failed to send event %p to %s " "(num_failures=%u)", e, e->addr->domain_and_port, e->addr->num_failures);

	if (e->addr->num_failures < MAX_FAILURES) {
		/* Try other addresses, if available */
		event_retry(e, 1);
		return;
	}

	/*
	 * If other side doesn't like what we say, forget about them.
	 * (There is no way to tell other side that we are dropping them...).
	 */
	wpa_printf(MSG_DEBUG, "WPS UPnP: Deleting subscription %p " "address %s due to errors", s, e->addr->domain_and_port);
	dl_list_del(&e->addr->list);
	subscr_addr_delete(e->addr);
	e->addr = NULL;

	if (dl_list_empty(&s->addr_list)) {
		/* if we've given up on all addresses */
		wpa_printf(MSG_DEBUG, "WPS UPnP: Removing subscription %p " "with no addresses", s);
		dl_list_del(&s->list);
		subscription_destroy(s);
		return;
	}

	/* Try other addresses, if available */
	event_retry(e, 0);
}

static void event_http_cb(void *ctx, struct http_client *c, enum http_client_event event)
{
	struct wps_event_ *e = ctx;
	struct subscription *s = e->s;

	wpa_printf(MSG_DEBUG, "WPS UPnP: HTTP client callback: e=%p c=%p " "event=%d", e, c, event);
	switch (event) {
	case HTTP_CLIENT_OK:
		wpa_printf(MSG_DEBUG, "WPS UPnP: Got event %p reply OK from %s", e, e->addr->domain_and_port);
		e->addr->num_failures = 0;
		s->last_event_failed = 0;
		event_delete(e);

		/* Schedule sending more if there is more to send */
		if (!dl_list_empty(&s->event_queue)) {
			event_send_all_later(s->sm);
		}
		break;
	case HTTP_CLIENT_FAILED:
		wpa_printf(MSG_DEBUG, "WPS UPnP: Event send failure");
		event_addr_failure(e);
		break;
	case HTTP_CLIENT_INVALID_REPLY:
		wpa_printf(MSG_DEBUG, "WPS UPnP: Invalid reply");
		event_addr_failure(e);
		break;
	case HTTP_CLIENT_TIMEOUT:
		wpa_printf(MSG_DEBUG, "WPS UPnP: Event send timeout");
		event_addr_failure(e);
		break;
	}
}

/* event_send_start -- prepare to send a event message to subscriber
 *
 * This gets complicated because:
 * -- The message is sent via TCP and we have to keep the stream open
 *      for 30 seconds to get a response... then close it.
 * -- But we might have other event happen in the meantime...
 *      we have to queue them, if we lose them then the subscriber will
 *      be forced to unsubscribe and subscribe again.
 * -- If multiple URLs are provided then we are supposed to try successive
 *      ones after 30 second timeout.
 * -- The URLs might use domain names instead of dotted decimal addresses,
 *      and resolution of those may cause unwanted sleeping.
 * -- Doing the initial TCP connect can take a while, so we have to come
 *      back after connection and then send the data.
 *
 * Returns nonzero on error;
 *
 * Prerequisite: No current event send (s->current_event == NULL)
 *      and non-empty queue.
 */
static int event_send_start(struct subscription *s)
{
	struct wps_event_ *e;
	unsigned int itry;
	struct wpabuf *buf;

	/*
	 * Assume we are called ONLY with no current event and ONLY with
	 * nonempty event queue and ONLY with at least one address to send to.
	 */
	if (dl_list_empty(&s->addr_list)) {
		return -1;
	}
	if (s->current_event) {
		return -1;
	}
	if (dl_list_empty(&s->event_queue)) {
		return -1;
	}

	s->current_event = e = event_dequeue(s);

	/* Use address according to number of retries */
	itry = 0;
	dl_list_for_each(e->addr, &s->addr_list, struct subscr_addr, list)
	if (itry++ == e->retry) {
		break;
	}
	if (itry < e->retry) {
		return -1;
	}

	buf = event_build_message(e);
	if (buf == NULL) {
		event_retry(e, 0);
		return -1;
	}

	e->http_event = http_client_addr(&e->addr->saddr, buf, 0, event_http_cb, e);
	if (e->http_event == NULL) {
		wpabuf_free(buf);
		event_retry(e, 0);
		return -1;
	}

	return 0;
}

/* event_send_all_later_handler -- actually send events as needed */
static void event_send_all_later_handler(void *eloop_data, void *user_ctx)
{
	struct upnp_wps_device_sm *sm = user_ctx;
	struct subscription *s, *tmp;
	int nerrors = 0;

	sm->event_send_all_queued = 0;
	dl_list_for_each_safe(s, tmp, &sm->subscriptions, struct subscription, list) {
		if (s->current_event == NULL /* not busy */  &&
			!dl_list_empty(&s->event_queue) /* more to do */) {
			if (event_send_start(s)) {
				nerrors++;
			}
		}
	}

	if (nerrors) {
		/* Try again later */
		event_send_all_later(sm);
	}
}

/* event_send_all_later -- schedule sending events to all subscribers
 * that need it.
 * This avoids two problems:
 * -- After getting a subscription, we should not send the first event
 *      until after our reply is fully queued to be sent back,
 * -- Possible stack depth or infinite recursion issues.
 */
void event_send_all_later(struct upnp_wps_device_sm *sm)
{
	/*
	 * The exact time in the future isn't too important. Waiting a bit
	 * might let us do several together.
	 */
	if (sm->event_send_all_queued) {
		return;
	}
	sm->event_send_all_queued = 1;
	eloop_register_timeout(EVENT_DELAY_SECONDS, EVENT_DELAY_MSEC, event_send_all_later_handler, NULL, sm);
}

/* event_send_stop_all -- cleanup */
void event_send_stop_all(struct upnp_wps_device_sm *sm)
{
	if (sm->event_send_all_queued) {
		eloop_cancel_timeout(event_send_all_later_handler, NULL, sm);
	}
	sm->event_send_all_queued = 0;
}

/**
 * event_add - Add a new event to a queue
 * @s: Subscription
 * @data: Event data (is copied; caller retains ownership)
 * @probereq: Whether this is a Probe Request event
 * Returns: 0 on success, -1 on error, 1 on max event queue limit reached
 */
int event_add(struct subscription *s, const struct wpabuf *data, int probereq)
{
	struct wps_event_ *e;
	unsigned int len;

	len = dl_list_len(&s->event_queue);
	if (len >= MAX_EVENTS_QUEUED) {
		wpa_printf(MSG_DEBUG, "WPS UPnP: Too many events queued for " "subscriber %p", s);
		if (probereq) {
			return 1;
		}

		/* Drop oldest entry to allow EAP event to be stored. */
		e = event_dequeue(s);
		if (!e) {
			return 1;
		}
		event_delete(e);
	}

	if (s->last_event_failed && probereq && len > 0) {
		/*
		 * Avoid queuing frames for subscribers that may have left
		 * without unsubscribing.
		 */
		wpa_printf(MSG_DEBUG, "WPS UPnP: Do not queue more Probe " "Request frames for subscription %p since last " "delivery failed", s);
		return -1;
	}

	e = os_zalloc(sizeof(*e));
	if (e == NULL) {
		return -1;
	}
	dl_list_init(&e->list);
	e->s = s;
	e->data = wpabuf_dup(data);
	if (e->data == NULL) {
		os_free(e);
		return -1;
	}
	e->subscriber_sequence = s->next_subscriber_sequence++;
	if (s->next_subscriber_sequence == 0) {
		s->next_subscriber_sequence++;
	}
	wpa_printf(MSG_DEBUG, "WPS UPnP: Queue event %p for subscriber %p " "(queue len %u)", e, s, len + 1);
	dl_list_add_tail(&s->event_queue, &e->list);
	event_send_all_later(s->sm);
	return 0;
}


text:
> Tech stack: Electron, PouchDB, Webtorrent, Express, AngularJS

To start project type command:

`npm install`

`npm start`

#If problem on windows try
[Windows issues](https://github.com/Microsoft/nodejs-guidelines/blob/master/windows-environment.md#resolving-common-issues)
or try typing in console: `.\node_modules\.bin\electron-rebuild.cmd`


text:
package com.alibaba.json.bvt;

import java.util.Random;

import org.junit.Assert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;

import junit.framework.TestCase;

public class LongFieldTest_4 extends TestCase {

    public void test_min() throws Exception {
        Random random = new Random();
        Model[] array = new Model[2048];
        for (int i = 0; i < array.length; ++i) {
            array[i] = new Model();
            array[i].value = random.nextLong();
        }

        String text = JSON.toJSONString(array);

        Model[] array2 = JSON.parseObject(text, Model[].class);

        Assert.assertEquals(array.length, array2.length);
        for (int i = 0; i < array.length; ++i) {
            Assert.assertEquals(array[i].value, array2[i].value);
        }
    }

    @JSONType(serialzeFeatures = SerializerFeature.BeanToArray, parseFeatures = Feature.SupportArrayToBean)
    public static class Model {

        public long value;

    }
}


text:
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <magick/ImageMagick.h>
#include "image.h"

#define DEFAULT_SIZE	128

int image_init (const char *path)
{
	InitializeMagick(path);
	return 0;
}

int image_cleanup (void)
{
	DestroyMagick();
	return 0;
}

int image_ping (const char *filename, int *width, int *height)
{
	int ret = -1;
	ExceptionInfo *exception;
	ImageInfo *image_info;
	Image *image;
	exception = AcquireExceptionInfo();
	assert(exception != NULL);
	image_info = AcquireImageInfo();
	assert(image_info != NULL);
	strcpy(image_info->filename, filename);

	image = PingImage(image_info, exception);
	if (image == NULL) CatchException(exception);
	else
	{
		ret = 0;
		*width = image->columns;
		*height = image->rows;
	}
	DestroyImage(image);
	DestroyImageInfo(image_info);
	DestroyExceptionInfo(exception);
	return ret;
}

int image_read_rgb (const char *filename, int *width, int *height, unsigned char **data)
{
	ExceptionInfo *exception;
	ImageInfo *image_info;
	Image	*image;
	unsigned char *rgb;
	int columns, rows;
	MagickBooleanType ret;

	exception = AcquireExceptionInfo();
	assert(exception != NULL);
	image_info = AcquireImageInfo();
	assert(exception != NULL);
	strcpy(image_info->filename, filename);

	image = ReadImage(image_info, exception);
	if (image == NULL)
	{
		CatchException(exception);
	}
	assert(image != NULL);

	columns = image->columns;
	rows = image->rows;
	rgb = (unsigned char *)malloc(columns * rows * CHAN);
	assert(rgb != NULL);
	ret = ExportImagePixels(image, 0, 0, columns, rows, "RGB", CharPixel, rgb, exception);
	if (ret == MagickFalse)
	{
		CatchException(exception);
	}
	assert(ret == MagickTrue);

	DestroyImage(image);
	DestroyImageInfo(image_info);
	DestroyExceptionInfo(exception);

	*width = columns;
	*height = rows;
	*data = rgb;
	return 0;
}

int image_read_hsv (const char *filename, int *width, int *height, unsigned char **data)
{
	ExceptionInfo *exception;
	ImageInfo *image_info;
	Image	*image;
	unsigned char *hsv;
	int columns, rows;
	MagickBooleanType ret;

	exception = AcquireExceptionInfo();
	assert(exception != NULL);
	image_info = AcquireImageInfo();
	assert(exception != NULL);
	strcpy(image_info->filename, filename);

	image = ReadImage(image_info, exception);
	if (image == NULL)
	{
		CatchException(exception);
	}
	assert(image != NULL);
	ret = SetImageColorspace(image, HSBColorspace);
	assert(ret == MagickTrue);
	columns = image->columns;
	rows = image->rows;
	hsv = (unsigned char *)malloc(columns * rows * CHAN);
	assert(hsv != NULL);
	ret = ExportImagePixels(image, 0, 0, columns, rows, "RGB", CharPixel, hsv, exception);
	if (ret == MagickFalse)
	{
		CatchException(exception);
	}
	assert(ret == MagickTrue);

	DestroyImage(image);
	DestroyImageInfo(image_info);
	DestroyExceptionInfo(exception);

	*width = columns;
	*height = rows;
	*data = hsv;
	return 0;
}

int image_write_rgb (const char *filename, int width, int height, unsigned char *data)
{
	ExceptionInfo *exception;
	ImageInfo *image_info;
	Image	*image;
	MagickBooleanType ret;

	exception = AcquireExceptionInfo();
	assert(exception != NULL);
	image_info = AcquireImageInfo();
	assert(exception != NULL);

	image = ConstituteImage(width, height, "RGB", CharPixel, data, exception);
	if (image == NULL) CatchException(exception);
	assert(image != NULL);
	strcpy(image->filename, filename);
	ret = WriteImage(image_info, image);
	assert(ret == MagickTrue);

	DestroyImage(image);
	DestroyImageInfo(image_info);
	DestroyExceptionInfo(exception);
	return 0;
}

int image_read_gray (const char *filename, int *width, int *height, float **data)
{
	ExceptionInfo *exception;
	ImageInfo *image_info;
	Image	*image;
	float *gray;
	int columns, rows;
	MagickBooleanType ret;

	exception = AcquireExceptionInfo();
	assert(exception != NULL);
	image_info = AcquireImageInfo();
	assert(exception != NULL);
	strcpy(image_info->filename, filename);

	image = ReadImage(image_info, exception);
	if (image == NULL)
	{
		CatchException(exception);
	}
	assert(image != NULL);
	columns = image->columns;
	rows = image->rows;
	gray = (float *)malloc(columns * rows * sizeof(float));
	assert(gray != NULL);
	ret = ExportImagePixels(image, 0, 0, columns, rows, "I", FloatPixel, gray, exception);
	if (ret == MagickFalse)
	{
		CatchException(exception);
	}
	assert(ret == MagickTrue);

	DestroyImage(image);
	DestroyImageInfo(image_info);
	DestroyExceptionInfo(exception);

	*width = columns;
	*height = rows;
	*data = gray;
	return 0;
}

int image_read_rgb_hsv (const char *filename, int *width, int *height, unsigned char **data_rgb, unsigned char **data_hsv)
{
	ExceptionInfo *exception;
	ImageInfo *image_info;
	Image	*image, *image2;
	unsigned char *rgb, *hsv;
	int columns, rows;
	MagickBooleanType ret;

	exception = AcquireExceptionInfo();
	assert(exception != NULL);
	image_info = AcquireImageInfo();
	assert(exception != NULL);
	strcpy(image_info->filename, filename);

	image = ReadImage(image_info, exception);
	if (image == NULL)
	{
		CatchException(exception);
	}
	assert(image != NULL);

	image2 = image;
	image = ThumbnailImage(image2, DEFAULT_SIZE, DEFAULT_SIZE, exception);
	assert(image != NULL);
	DestroyImage(image2);

	columns = image->columns;
	rows = image->rows;
	rgb = (unsigned char *)malloc(columns * rows * CHAN);
	assert(rgb != NULL);
	ret = ExportImagePixels(image, 0, 0, columns, rows, "RGB", CharPixel, rgb, exception);
	if (ret == MagickFalse)
	{
		CatchException(exception);
	}
	assert(ret == MagickTrue);

	*data_rgb = rgb;

	ret = SetImageColorspace(image, HSBColorspace);
	assert(ret == MagickTrue);
	columns = image->columns;
	rows = image->rows;
	hsv = (unsigned char *)malloc(columns * rows * CHAN);
	assert(hsv != NULL);
	ret = ExportImagePixels(image, 0, 0, columns, rows, "RGB", CharPixel, hsv, exception);
	if (ret == MagickFalse)
	{
		CatchException(exception);
	}
	assert(ret == MagickTrue);

	*data_hsv = hsv;

	DestroyImage(image);
	DestroyImageInfo(image_info);
	DestroyExceptionInfo(exception);

	*width = columns;
	*height = rows;
	return 0;
}


text:
<!DOCTYPE html>

    <title>Knot.js Example - Ticket</title>

    <link rel="stylesheet" href="styles/example.css">

    <link rel="stylesheet" href="./styles/github.css">

    <link rel="stylesheet" href="styles/tabpage.css">

    <link rel="stylesheet" href="styles/tabpage.css" id="tabpageCSS">

From knockout.js

Knot.js example- Ticket 1

        this example uses template to fill the options of the combobox

        Choose a ticket class: <select id="classSelect"><option knot-template></option></select>
        <button class="clearButton">clear</button>

        You have chosen
        ($)

Knot.js example- Ticket 2

        this example uses access point "options" of "select" element.

        Choose a ticket class: <select id="classSelect2"></select>
        <button class="clearButton">clear</button>

        You have chosen
        ($)


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/contraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.tanmayvirkar.instagramclone.MainActivity">

    <ImageView
        android:id="@+id/logo"
        android:layout_width="204dp"
        android:layout_height="141dp"
        android:layout_marginTop="16dp"
        android:contentDescription="@string/app_logo"
        android:src="@drawable/instagram_logo"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1" />

    <EditText
        android:id="@+id/txtUsername"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="50dp"
        android:ems="10"
        android:hint="Username"
        android:inputType="textPersonName"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/logo"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1" />

    <EditText
        android:id="@+id/txtPassword"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="22dp"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPassword"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txtUsername"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1" />

    <Button
        android:id="@+id/btnSignup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="19dp"
        android:onClick="signUpOrLogin"
        android:text="@string/btn_sign_up"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txtPassword"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1" />

    <TextView
        android:id="@+id/logIn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn_login"
        android:textColor="@android:color/holo_blue_dark"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.822" />

</android.support.constraint.ConstraintLayout>


text:
$(window).scroll(function () {
    if ($(this).scrollTop() > 50) {
        $('.scrolltop:hidden').stop(true, true).fadeIn();
    } else {
        $('.scrolltop').stop(true, true).fadeOut();
    }
});
$(function () {
    $(".scroll").click(function () {
        $("html,body").animate({scrollTop: $(".top").offset().top}, "1000");
        return false
    })
});


text:
package org.tiltedwindmills.fantasy.mfl.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

// TODO: Auto-generated Javadoc
/**
 * The Class Franchise.
 *
 * @author John Daniel
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class Franchise extends AbstractObject {

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = 5569509644131422019L;

    /** The name. */
    private String name;

    /** The id. */
    private String id;

    /** The last visit. */
    private long lastVisit;

    /** The division. */
    private Integer division;

    /** The waiver order. */
    @JsonProperty("waiverSortOrder")
    private int waiverOrder;

    /**
     * Gets the name.
     *
     * @return the name
     */
    public final String getName() {
        return name;
    }

    /**
     * Sets the name.
     *
     * @param name the new name
     */
    public final void setName(final String name) {
        this.name = name;
    }

    /**
     * Gets the id.
     *
     * @return the id
     */
    public final String getId() {
        return id;
    }

    /**
     * Sets the id.
     *
     * @param id the new id
     */
    public final void setId(final String id) {
        this.id = id;
    }

    /**
     * Gets the last visit.
     *
     * @return the last visit
     */
    public final long getLastVisit() {
        return lastVisit;
    }

    /**
     * Sets the last visit.
     *
     * @param lastVisit the new last visit
     */
    public final void setLastVisit(final long lastVisit) {
        this.lastVisit = lastVisit;
    }

    /**
     * Gets the division.
     *
     * @return the division
     */
    public final Integer getDivision() {
        return division;
    }

    /**
     * Sets the division.
     *
     * @param division the new division
     */
    public final void setDivision(final Integer division) {
        this.division = division;
    }

    /**
     * Gets the waiver sort order.
     *
     * @return the waiver sort order
     */
    public final int getWaiverOrder() {
        return waiverOrder;
    }

    /**
     * Sets the waiver sort order.
     *
     * @param waiverOrder the new waiver sort order
     */
    public final void setWaiverOrder(final int waiverOrder) {
        this.waiverOrder = waiverOrder;
    }
}


text:
#ifndef COM_MIKEWELLER_HAMCREST_COMPARE_TO_VALUE_MATCHER_HPP
#define COM_MIKEWELLER_HAMCREST_COMPARE_TO_VALUE_MATCHER_HPP

#include "matcher.hpp"

namespace MWHamcrest
{

/** A matcher base class which compares inputs against some value. Accepts a
 value in the constructor to compare inputs to, and provides the
 comparison_value() getter to access this value.

 Subclass this for all matchers which accept a single constructor arg,
 such as equal_to(x).

 */
template <typename TType>
class ComparisonMatcher : public Matcher
{
public:
        typedef TType comparison_value_type;

        ComparisonMatcher(TType comparison)
                 // need to use () not {} to construct here because some types
                 // may need that
                : _comparison(std::move(comparison))
        {}

        const TType& comparison_value() const
        {
                return _comparison;
        }

private:
        TType _comparison;

};

}

#endif


text:
package org.deidentifier.arx.examples;

import java.io.IOException;

import org.deidentifier.arx.ARXAnonymizer;
import org.deidentifier.arx.ARXConfiguration;
import org.deidentifier.arx.ARXPopulationModel;
import org.deidentifier.arx.ARXPopulationModel.Region;
import org.deidentifier.arx.ARXResult;
import org.deidentifier.arx.AttributeType;
import org.deidentifier.arx.AttributeType.Hierarchy;
import org.deidentifier.arx.AttributeType.Hierarchy.DefaultHierarchy;
import org.deidentifier.arx.Data;
import org.deidentifier.arx.Data.DefaultData;
import org.deidentifier.arx.DataHandle;
import org.deidentifier.arx.criteria.AverageReidentificationRisk;
import org.deidentifier.arx.risk.RiskEstimateBuilder;
import org.deidentifier.arx.risk.RiskModelAttributes;
import org.deidentifier.arx.risk.RiskModelAttributes.QuasiIdentifierRisk;
import org.deidentifier.arx.risk.RiskModelHistogram;

/**
 * This class implements an example that shows handling of suppressed values and records in input data
 *
 * @author Fabian Prasser
 */
public class Example59 extends Example {

    /**
     * Entry point.
     *
     * @param args the arguments
     */
    public static void main(String[] args) throws IOException {

        // Define data
        DefaultData data = Data.create();
        data.add("age", "gender", "zipcode");
        data.add("45", "male", "81675");
        data.add("34", "male", "81667");
        data.add("66", "male", "81925");
        data.add("70", "female", "81931");
        data.add("34", "female", "81931");
        data.add("70", "male", "81931");
        data.add("45", "male", "81931");

        // Define hierarchies
        DefaultHierarchy age = Hierarchy.create();
        age.add("34", "<50", "*");
        age.add("45", "<50", "*");
        age.add("66", ">=50", "*");
        age.add("70", ">=50", "*");

        DefaultHierarchy gender = Hierarchy.create();
        gender.add("male", "*");
        gender.add("female", "*");

        // Only excerpts for readability
        DefaultHierarchy zipcode = Hierarchy.create();
        zipcode.add("81667", "8166*", "816**", "81***", "8****", "*****");
        zipcode.add("81675", "8167*", "816**", "81***", "8****", "*****");
        zipcode.add("81925", "8192*", "819**", "81***", "8****", "*****");
        zipcode.add("81931", "8193*", "819**", "81***", "8****", "*****");

        data.getDefinition().setAttributeType("age", age);
        data.getDefinition().setAttributeType("gender", gender);
        data.getDefinition().setAttributeType("zipcode", zipcode);
        data.getDefinition().setMinimumGeneralization("gender", 1);
        data.getDefinition().setMaximumGeneralization("age", 0);

        // Create an instance of the anonymizer
        ARXAnonymizer anonymizer = new ARXAnonymizer();
        ARXConfiguration config = ARXConfiguration.create();
        config.addPrivacyModel(new AverageReidentificationRisk(0.5d));
        config.setSuppressionLimit(1d);

        // Anonymize
        ARXResult result = anonymizer.anonymize(data, config);

        // Convert output to input
        Data outputAsInput = Data.create(result.getOutput().iterator());
        DataHandle handle = outputAsInput.getHandle();
        handle.getDefinition().setAttributeType("age", AttributeType.QUASI_IDENTIFYING_ATTRIBUTE);
        handle.getDefinition().setAttributeType("gender", AttributeType.QUASI_IDENTIFYING_ATTRIBUTE);
        handle.getDefinition().setAttributeType("zipcode", AttributeType.QUASI_IDENTIFYING_ATTRIBUTE);

        System.out.println(" - Data:");
        print(handle);

        // For each attribute combination sorted by risk ascending
        ARXPopulationModel populationmodel = ARXPopulationModel.create(Region.USA);
        RiskEstimateBuilder builder = handle.getRiskEstimator(populationmodel);
        RiskModelAttributes riskmodel = builder.getAttributeRisks();
        for (QuasiIdentifierRisk risk : riskmodel.getAttributeRisks()) {

            // Specify
            handle.getDefinition().setAttributeType("age", AttributeType.INSENSITIVE_ATTRIBUTE);
            handle.getDefinition().setAttributeType("gender", AttributeType.INSENSITIVE_ATTRIBUTE);
            handle.getDefinition().setAttributeType("zipcode", AttributeType.INSENSITIVE_ATTRIBUTE);
            for (String qi : risk.getIdentifier()) {
                handle.getDefinition().setAttributeType(qi, AttributeType.QUASI_IDENTIFYING_ATTRIBUTE);
            }

            // Print
            System.out.println("\n - Stats for QI: " + risk.getIdentifier());
            analyzeData(handle);
        }
    }

    /**
     * Perform risk analysis
     * @param handle
     */
    private static void analyzeData(DataHandle handle) {

        ARXPopulationModel populationmodel = ARXPopulationModel.create(Region.USA);
        RiskEstimateBuilder builder = handle.getRiskEstimator(populationmodel);
        RiskModelHistogram classes = builder.getEquivalenceClassModel();
        System.out.println("   * Equivalence classes:");
        System.out.println("     - Average size: " + classes.getAvgClassSize());
        System.out.println("     - Num classes : " + classes.getNumClasses());
        System.out.println("     - Records : " + classes.getNumRecords());
    }
}


text:
require 'restclient'
require 'xmlsimple'

require File.join(File.dirname(__FILE__), 'boomi', 'boomi')


text: Add new


text:
package com.grumoon.androidultrapulltorefreshdemo.ui;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.grumoon.androidultrapulltorefreshdemo.R;
import com.grumoon.androidultrapulltorefreshdemo.util.Constants;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * A simple {@link Fragment} subclass.
 */
public class AutoRefreshFragment extends Fragment {

    //下拉次数
    private int ptrTimes;

    private PtrClassicFrameLayout ptr;

    private ImageView ivImage;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_auto_refresh, container, false);
        initView(v);
        return v;
    }

    private void initView(View v) {

        ivImage = (ImageView) v.findViewById(R.id.iv_main);

        ptr = (PtrClassicFrameLayout) v.findViewById(R.id.ptr_main);

        ptr.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(final PtrFrameLayout ptrFrameLayout) {

                ImageLoader.getInstance().displayImage(Constants.VERTICAL_IMAGE_URLS[ptrTimes % Constants.VERTICAL_IMAGE_URLS.length], ivImage, new ImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String imageUri, View view) {

                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                        ptr.refreshComplete();
                    }

                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        ptr.refreshComplete();
                    }

                    @Override
                    public void onLoadingCancelled(String imageUri, View view) {
                        ptr.refreshComplete();
                    }
                });

                ptrTimes++;
            }
        });

        /**
         * 自动刷新
         */
        ptr.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptr.autoRefresh();
            }
        }, 100);
    }

}


text:
<?php

namespace AppBundle\Services;

use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use AppBundle\Entity\Client;
use AppBundle\Entity\Adresses;

class EXCELService {

    protected $phpexcel;

    public function __construct($phpexcel) {

        $this->phpexcel = $phpexcel;
    }

    public function excel_to_array($input_filename) {
        $phpExcelObject = $this->phpexcel->createPHPExcelObject($input_filename);
        $data = $phpExcelObject->getActiveSheet()->toArray();
        //cration tab header en minuscule
        foreach ($data[0] as $key => $value) {
            $data[0][$key] = strtolower($value);
        }
        $headers = array_values($data[0]);
        //delete header from data;
        unset($data[0]);

        //parcours de data et injection d'id correspondant pour chaque colone
        foreach ($data as $key => $value) {
            $data[$key] = array_combine($headers, $value);
        }
        return $data;
    }

    public function array_to_excel($array, $output_filename) {

        $phpExcelObject = $this->phpexcel->createPHPExcelObject();

        $phpExcelObject->getProperties()->setCreator("hassine")
                ->setTitle("Office 2005 XLSX Test Document")
                ->setSubject("Office 2005 XLSX Test Document")
                ->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.");

        $sheet = $phpExcelObject->setActiveSheetIndex(0);
        //generation alphapets tab;
        $alphabets = range('A', 'Z');
        //generation tableau des keys des entètes de fichier excel
        $keys_header = array_keys($array[0]);

        //creation header fichier excel:
        foreach ($keys_header as $key => $value) {
            $sheet->setCellValue($alphabets[$key] . '1', strtoupper($value));
        }

        //creation core fichier excel
        foreach ($array as $keyligne => $ligne) {
            foreach ($keys_header as $keycolone => $colone) {
                $sheet->setCellValue($alphabets[$keycolone] . ($keyligne + 2), $ligne[$colone]);
            }
        }

        $phpExcelObject->getActiveSheet()->setTitle('Simple');
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $phpExcelObject->setActiveSheetIndex(0);

        // create the writer
        $writer = $this->phpexcel->createWriter($phpExcelObject, 'Excel5');

        // create the response
        $response = $this->phpexcel->createStreamedResponse($writer);

        // adding headers
        $dispositionHeader = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $output_filename);
        $response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
        $response->headers->set('Pragma', 'public');
        $response->headers->set('Cache-Control', 'maxage=1');
        $response->headers->set('Content-Disposition', $dispositionHeader);

        return $response;
    }

     public function clients_excel_to_array($input_filename) {
        $phpExcelObject = $this->phpexcel->createPHPExcelObject($input_filename);
        $data = $phpExcelObject->getActiveSheet()->toArray();

        //cration tab header en minuscule
        foreach ($data[0] as $key => $value) {
            $data[0][$key] = strtolower($value);
        }
        $headers = array_values($data[0]);

        //delete header from data;
        unset($data[0]);

        //parcours de data et injection d'id correspondant pour chaque colone
        foreach ($data as $key => $value) {
            $data[$key] = array_combine($headers, $value);
        }
        return $data;
    }

     public function clients_array_to_excel($array, $output_filename) {

        $phpExcelObject = $this->phpexcel->createPHPExcelObject();

        $phpExcelObject->getProperties()->setCreator("hassine")
                ->setTitle("Office 2005 XLSX Test Document")
                ->setSubject("Office 2005 XLSX Test Document")
                ->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.");

        $sheet = $phpExcelObject->setActiveSheetIndex(0);
        //generation alphapets tab;
        $alphabets = range('A', 'Z');
        //generation tableau des keys des entètes de fichier excel
        $keys_header = array_keys($array[0]);

        //creation header fichier excel:
        foreach ($keys_header as $key => $value) {
            $sheet->setCellValue($alphabets[$key] . '1', strtoupper($value));
        }
        //creation core fichier excel
        foreach ($array as $keyligne => $ligne) {
            foreach ($keys_header as $keycolone => $colone) {
                if($colone=='adresses'){
                    $contentColone=$ligne[$colone];
                    if(is_array($contentColone)){
                       $souslignes=  implode(";", $contentColone);
                       $sheet->setCellValue($alphabets[$keycolone] . ($keyligne + 2), $souslignes);
                    }else{
                      $sheet->setCellValue($alphabets[$keycolone] . ($keyligne + 2), 'pas adresses');
                    }
                }else{
                    $sheet->setCellValue($alphabets[$keycolone] . ($keyligne + 2), $ligne[$colone]);
                }
            }
        }

        $phpExcelObject->getActiveSheet()->setTitle('Simple');
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $phpExcelObject->setActiveSheetIndex(0);

        // create the writer
        $writer = $this->phpexcel->createWriter($phpExcelObject, 'Excel5');

        // create the response
        $response = $this->phpexcel->createStreamedResponse($writer);

        // adding headers
        $dispositionHeader = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $output_filename);
        $response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
        $response->headers->set('Pragma', 'public');
        $response->headers->set('Cache-Control', 'maxage=1');
        $response->headers->set('Content-Disposition', $dispositionHeader);

        return $response;
    }

    public function processDataExportClients($data){
            $tabs=array();
            foreach($data as $key=>$ligne){
                $tabs[$key]['id']=$ligne->getId();
                $tabs[$key]['nom']=$ligne->getNom();
                $tabs[$key]['prenom']=$ligne->getPrenom();
                $tabs[$key]['email']=$ligne->getEmail();
                $tabs[$key]['sexe']=$ligne->getSexe();
                $adresses=$ligne->getAdresses();
                if(sizeof($adresses) > 0){
                    foreach ($adresses as $adresse){
                       $tabs[$key]['adresses'][]=$adresse->getAdresse();
                    }
                }else{
                    $tabs[$key]['adresses']=array();
                }
            }
            return $tabs;
    }

    public function processDataImportClients($lignes,$em){
        foreach ($lignes as $col) {
                //client traitement
                $client = $em->getRepository('AppBundle:Client')->find($col['id']);
                if (!$client) {
                    $client = new Client();
                    $client->setNom($col['nom']);
                    $client->setPrenom($col['prenom']);
                    $client->setEmail($col['email']);
                    $client->setSexe($col['sexe']);
                    $em->persist($client);
                } else {
                    $client->setNom($col['nom']);
                    $client->setPrenom($col['prenom']);
                    $client->setEmail($col['email']);
                    $client->setSexe($col['sexe']);
                }
                // adresses traitement
                if($col['adresses']!=NULL){
                        $adresses=explode(",",$col['adresses']);
                        foreach ($adresses as $adr){
                            $adresseBase = $em->getRepository('AppBundle:Adresses')->findOneBy(array('adresse'=>$adr,"client"=>$client));
                            //var_dump($adresseBase);die;
                            if(!$adresseBase){
                                $adresse=new Adresses();
                                $adresse->setAdresse($adr);
                                $adresse->setCp(78150);
                                $adresse->setVille("Le Chesnay");
                                $adresse->setPays("France");
                                $adresse->setClient($client);
                                $em->persist($adresse);
                            }else{
                                $adresseBase->setAdresse($adr);
                                $adresseBase->setCp(78150);
                                $adresseBase->setVille("Le Chesnay");
                                $adresseBase->setPays("France");
                                $adresseBase->setClient($client);
                            }
                        }
                }
                $em->flush();
        }
    }

}


text:
// Portions copyright Hiroshi Ito. Licensed under Apache 2.0 license

package com.gs.fw.common.mithra.attribute;

import com.gs.fw.common.mithra.MithraDataObject;
import com.gs.fw.common.mithra.attribute.calculator.procedure.BigDecimalProcedure;
import com.gs.fw.common.mithra.attribute.calculator.procedure.DoubleProcedure;
import com.gs.fw.common.mithra.attribute.calculator.procedure.FloatProcedure;
import com.gs.fw.common.mithra.attribute.calculator.procedure.IntegerProcedure;
import com.gs.fw.common.mithra.attribute.calculator.procedure.LongProcedure;
import com.gs.fw.common.mithra.cache.offheap.OffHeapExtractor;
import com.gs.fw.common.mithra.cache.offheap.OffHeapIntExtractorWithOffset;
import com.gs.fw.common.mithra.databasetype.DatabaseType;
import com.gs.fw.common.mithra.extractor.asm.ExtractorWriter;
import com.gs.fw.common.mithra.finder.All;
import com.gs.fw.common.mithra.finder.AtomicSelfNotEqualityOperation;
import com.gs.fw.common.mithra.finder.None;
import com.gs.fw.common.mithra.finder.Operation;
import com.gs.fw.common.mithra.finder.RelatedFinder;
import com.gs.fw.common.mithra.finder.SqlQuery;
import com.gs.fw.common.mithra.finder.integer.IntegerEqOperation;
import com.gs.fw.common.mithra.finder.integer.IntegerGreaterThanEqualsOperation;
import com.gs.fw.common.mithra.finder.integer.IntegerGreaterThanOperation;
import com.gs.fw.common.mithra.finder.integer.IntegerInOperation;
import com.gs.fw.common.mithra.finder.integer.IntegerLessThanEqualsOperation;
import com.gs.fw.common.mithra.finder.integer.IntegerLessThanOperation;
import com.gs.fw.common.mithra.finder.integer.IntegerNotEqOperation;
import com.gs.fw.common.mithra.finder.integer.IntegerNotInOperation;
import com.gs.fw.common.mithra.tempobject.TupleTempContext;
import com.gs.fw.common.mithra.util.ColumnInfo;
import com.gs.fw.common.mithra.util.fileparser.BitsInBytes;
import com.gs.fw.common.mithra.util.fileparser.ColumnarInStream;
import com.gs.fw.common.mithra.util.fileparser.ColumnarOutStream;
import org.eclipse.collections.api.set.primitive.IntSet;
import org.slf4j.Logger;

import java.io.IOException;
import java.io.ObjectStreamException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

public abstract class SingleColumnIntegerAttribute<T> extends IntegerAttribute<T> implements VersionAttribute<T>, SequenceAttribute<T>
{
    private static final ExtractorWriter extractorWriter = ExtractorWriter.intExtractorWriter();

    private transient String columnName;
    private transient String uniqueAlias;

    private static final long serialVersionUID = 3146117102692991067L;

    protected SingleColumnIntegerAttribute(String columnName, String uniqueAlias, String attributeName,
            String busClassNameWithDots, String busClassName, boolean isNullablePrimitive,
            boolean hasBusDate, RelatedFinder relatedFinder, Map<String, Object> properties,
            boolean isTransactional, boolean isOptimistic, boolean isIdentity)
    {
        this.columnName = columnName;
        this.uniqueAlias = uniqueAlias;
        this.isIdentity = isIdentity;
        this.setAll(attributeName, busClassNameWithDots, busClassName, isNullablePrimitive, relatedFinder, properties, isTransactional);
    }

    protected SingleColumnIntegerAttribute() {}

    public void setSqlParameters(PreparedStatement pps, Object mithraDataObject, int pos, TimeZone databaseTimeZone, DatabaseType databaseType)
            throws SQLException
    {
        if (this.isAttributeNull((T) mithraDataObject))
        {
            pps.setNull(pos, java.sql.Types.INTEGER);
        }
        else
        {
            pps.setInt(pos, this.intValueOf((T) mithraDataObject));
        }
    }

    public void setColumnName(String columnName)
    {
        this.columnName = columnName;
    }

    public boolean isSourceAttribute()
    {
        return this.columnName == null;
    }

    public String getColumnName()
    {
        return this.columnName;
    }

    public Operation eq(int other)
    {
        return new IntegerEqOperation(this, other);
    }

    public Operation eq(long other)
    {
        if (other > Integer.MAX_VALUE || other < Integer.MIN_VALUE)
        {
            return new None(this);
        }
        return new IntegerEqOperation(this, (int) other);
    }

    public Operation notEq(int other)
    {
        return new IntegerNotEqOperation(this, other);
    }

    /**
     * @deprecated  GS Collections variant of public APIs will be decommissioned in Mar 2019.
     * Use Eclipse Collections variant of the same API instead.
     **/
    @Deprecated
    @Override
    public Operation in(com.gs.collections.api.set.primitive.IntSet intSet)
    {
        Operation op;
        switch (intSet.size())
        {
            case 0:
                op = new None(this);
                break;
            case 1:
                op = this.eq(intSet.intIterator().next());
                break;
            default:
                op = new IntegerInOperation(this, intSet);
                break;
        }

        return op;
    }

    @Override
    public Operation in(IntSet intSet)
    {
        Operation op;
        switch (intSet.size())
        {
            case 0:
                op = new None(this);
                break;
            case 1:
                op = this.eq(intSet.intIterator().next());
                break;
            default:
                op = new IntegerInOperation(this, intSet);
                break;
        }

        return op;
    }

    /**
     * @deprecated  GS Collections variant of public APIs will be decommissioned in Mar 2019.
     * Use Eclipse Collections variant of the same API instead.
     **/
    @Deprecated
    @Override
    public Operation notIn(com.gs.collections.api.set.primitive.IntSet intSet)
    {
        Operation op;
        switch (intSet.size())
        {
            case 0:
                op = new All(this);
                break;
            case 1:
                op = this.notEq(intSet.intIterator().next());
                break;
            default:
                op = new IntegerNotInOperation(this, intSet);
                break;
        }

        return op;
    }

    @Override
    public Operation notIn(IntSet intSet)
    {
        Operation op;
        switch (intSet.size())
        {
            case 0:
                op = new All(this);
                break;
            case 1:
                op = this.notEq(intSet.intIterator().next());
                break;
            default:
                op = new IntegerNotInOperation(this, intSet);
                break;
        }

        return op;
    }

    public Operation greaterThan(int target)
    {
        return new IntegerGreaterThanOperation(this, target);
    }

    public Operation greaterThanEquals(int target)
    {
        return new IntegerGreaterThanEqualsOperation(this, target);
    }

    public Operation lessThan(int target)
    {
        return new IntegerLessThanOperation(this, target);
    }

    public Operation lessThanEquals(int target)
    {
        return new IntegerLessThanEqualsOperation(this, target);
    }

    public Operation eq(IntegerAttribute other)
    {
        return this.joinEqWithSourceAndAsOfCheck(other);
    }

    public Operation joinEq(IntegerAttribute other)
    {
        return this.joinEqWithSourceAndAsOfCheck(other);
    }

    public Operation filterEq(IntegerAttribute other)
    {
        return this.filterEqWithCheck(other);
    }

    public Operation notEq(IntegerAttribute other)
    {
        if (this.getOwnerPortal().equals(other.getOwnerPortal()))
        {
            return new AtomicSelfNotEqualityOperation(this, other);
        }
        throw new RuntimeException("Non-equality join is not yet supported");
    }

    public String getFullyQualifiedLeftHandExpression(SqlQuery query)
    {
        String result = this.getColumnName();
        String databaseAlias = query.getDatabaseAlias(this.getOwnerPortal());
        if (databaseAlias != null)
        {
            if (this.uniqueAlias != null)
            {
                result = databaseAlias + this.uniqueAlias + "." + result;
            }
            else
            {
                result = databaseAlias + "." + result;
            }
        }
        return result;
    }

    public void setVersionAttributeSqlParameters(PreparedStatement pps, MithraDataObject mdo, int pos, TimeZone databaseTimeZone) throws SQLException
    {
        pps.setInt(pos, this.intValueOf((T) mdo) - 1);
    }

    public void forEach(final IntegerProcedure proc, T o, Object context)
    {
        if (!checkForNull(proc, o, context))
        {
            proc.execute(this.intValueOf(o), context);
        }
    }

    public void forEach(final DoubleProcedure proc, T o, Object context)
    {
        if (!checkForNull(proc, o, context))
        {
            proc.execute(this.intValueOf(o), context);
        }
    }

    public void forEach(final LongProcedure proc, T o, Object context)
    {
        if (!checkForNull(proc, o, context))
        {
            proc.execute(this.intValueOf(o), context);
        }
    }

    public void forEach(final FloatProcedure proc, T o, Object context)
    {
        if (!checkForNull(proc, o, context))
        {
            proc.execute(this.intValueOf(o), context);
        }
    }

    public void forEach(final BigDecimalProcedure proc, T o, Object context)
    {
        if (!checkForNull(proc, o, context))
        {
            proc.execute(BigDecimal.valueOf(this.intValueOf(o)), context);
        }
    }

    protected Object writeReplace() throws ObjectStreamException
    {
        return this.getSerializationReplacement();
    }

    public void appendColumnDefinition(StringBuilder sb, DatabaseType dt, Logger sqlLogger, boolean mustBeIndexable)
    {
        sb.append(this.columnName).append(' ').append("integer");
        if (this.isIdentity)
        {
            sb.append(' ').append(dt.getIdentityTableCreationStatement());
        }
        appendNullable(sb, dt);
    }

    public boolean verifyColumn(ColumnInfo info)
    {
        if (info.isNullable() != this.isNullable()) return false;
        return info.getType() == Types.INTEGER;
    }

    public SingleColumnAttribute createTupleAttribute(int pos, TupleTempContext tupleTempContext)
    {
        return new SingleColumnTupleIntegerAttribute(pos, this.isNullable(), tupleTempContext);
    }

    public static SingleColumnIntegerAttribute generate(String columnName, String uniqueAlias, String attributeName,
            String busClassNameWithDots, String busClassName, boolean isNullablePrimitive,
            boolean hasBusDate, RelatedFinder relatedFinder, Map<String, Object> properties,
            boolean isTransactional, boolean isOptimistic,
            boolean isIdentity, int offHeapFieldOffset, int offHeapNullBitsOffset, int offHeapNullBitsPosition, boolean hasSequence, boolean hasShadowAttribute)
    {
        SingleColumnIntegerAttribute e = generateInternal(columnName, uniqueAlias, attributeName, busClassNameWithDots, busClassName,
                isNullablePrimitive, hasBusDate, relatedFinder, properties, isTransactional, isOptimistic,
                isIdentity, offHeapFieldOffset, offHeapNullBitsOffset, offHeapNullBitsPosition, hasSequence, false);
        if (hasShadowAttribute)
        {
            SingleColumnIntegerAttribute shadow = generateInternal(columnName, uniqueAlias, attributeName, busClassNameWithDots, busClassName,
                    isNullablePrimitive, hasBusDate, relatedFinder, properties, isTransactional, isOptimistic,
                    isIdentity, offHeapFieldOffset, offHeapNullBitsOffset, offHeapNullBitsPosition, hasSequence, true);
            e.setShadowAttribute(shadow);
        }
        return e;
    }

    private static SingleColumnIntegerAttribute generateInternal(String columnName, String uniqueAlias, String attributeName,
            String busClassNameWithDots, String busClassName, boolean isNullablePrimitive, boolean hasBusDate,
            RelatedFinder relatedFinder, Map<String, Object> properties, boolean isTransactional, boolean isOptimistic,
            boolean isIdentity, int offHeapFieldOffset, int offHeapNullBitsOffset, int offHeapNullBitsPosition, boolean hasSequence, boolean hasShadowAttribute)
    {
        SingleColumnIntegerAttribute e;
        try
        {
            e = (SingleColumnIntegerAttribute) extractorWriter.createClass(attributeName, isNullablePrimitive, hasBusDate, busClassNameWithDots,
                    busClassName, isOptimistic, offHeapFieldOffset, offHeapNullBitsOffset, offHeapNullBitsPosition,
                    "com/gs/fw/common/mithra/attribute/SingleColumnIntegerAttribute", hasSequence, hasShadowAttribute).newInstance();
        }
        catch (Exception excp)
        {
            throw new RuntimeException("could not create class for "+attributeName+" in "+busClassName, excp);
        }
        e.columnName = columnName;
        e.uniqueAlias = uniqueAlias;
        e.isIdentity = isIdentity;
        e.setAll(attributeName, busClassNameWithDots, busClassName, isNullablePrimitive, relatedFinder, properties, isTransactional);
        e.setOffHeapOffsets(offHeapFieldOffset, offHeapNullBitsOffset, offHeapNullBitsPosition);
        return e;
    }

    public Object readResultSet(ResultSet rs, int pos, DatabaseType databaseType, TimeZone timeZone) throws SQLException
    {
        int result = rs.getInt(pos);
        if (rs.wasNull()) return null;
        return result;
    }

    public void writeValueToStream(T object, OutputStreamFormatter formatter, OutputStream os) throws IOException
    {
        formatter.write(this.intValueOf(object), os);
    }

    @Override
    public OffHeapExtractor zCreateOffHeapExtractor()
    {
        return new OffHeapIntExtractorWithOffset(this.offHeapFieldOffset, this.offHeapNullBitsOffset, this.offHeapNullBitsPosition);
    }

    @Override
    public void zDecodeColumnarData(List data, ColumnarInStream in) throws IOException
    {
        BitsInBytes nulls = in.decodeColumnarNull(this, data);
        IntegerAttribute intAttr = (IntegerAttribute) this;
        for(int p = 0; p < 32; p+=8)
        {
            for (int i = 0; i < data.size(); i++)
            {
                if (nulls == null || !nulls.get(i))
                {
                    intAttr.setIntValue(data.get(i), intAttr.intValueOf(data.get(i)) | ((in.readWithException() << p)));
                }
            }
        }
    }

    @Override
    public void zEncodeColumnarData(List data, ColumnarOutStream out) throws IOException
    {
        BitsInBytes nulls = out.encodeColumnarNull(data, this);
        IntegerAttribute intAttr = (IntegerAttribute) this;
        for(int p = 0; p < 32; p+=8)
        {
            for (int i = 0; i < data.size(); i++)
            {
                if (nulls == null || !nulls.get(i))
                {
                    int v = intAttr.intValueOf(data.get(i));
                    out.write((byte) ((v >>> p) & 0xFF));
                }
            }
        }
    }

    @Override
    public Object zDecodeColumnarData(ColumnarInStream in, int count) throws IOException
    {
        throw new RuntimeException("not implemented");
    }

    @Override
    public void zWritePlainTextFromColumnar(Object columnData, int row, ColumnarOutStream out) throws IOException
    {
        throw new RuntimeException("not implemented");
    }
}


text:
package fi.tp.experimental.pokerhands

trait GenericPokerHandComparatorTest {

  private val RUN_TESTS_WITH_ALL_PERMUTATIONS = true // set to true to run tests with all permutations of the hands

  def runTestsForHands(compareFunction: (PokerHand, PokerHand) => Int)
                      (hand1: PokerHand, hand2: PokerHand, expectedResult: Char, comment: String = "") = {
    if (RUN_TESTS_WITH_ALL_PERMUTATIONS) {
      testAllPermutations(compareFunction)(hand1, hand2, expectedResult, comment)
    } else {
      testBothWays(compareFunction)(hand1, hand2, expectedResult, comment)
    }
  }

  def testAllPermutations(compareFunction: (PokerHand, PokerHand) => Int)
                         (hand1: PokerHand, hand2: PokerHand, expectedResult: Char, comment: String = "") = {

    val permutationsOfHand1 : List[PokerHand] = permutate(hand1)
    val permutationsOfHand2 : List[PokerHand] = permutate(hand2)

    permutationsOfHand1.foreach(
      hand1 => permutationsOfHand2.foreach(
        hand2 => testBothWays(compareFunction)(hand1, hand2, expectedResult, comment)))
  }

  def testBothWays(compareFunction: (PokerHand, PokerHand) => Int)
                  (hand1: PokerHand, hand2: PokerHand, expectedResult: Char, comment: String = "") = {

    val comparisonValue1 = compareFunction(hand1, hand2)
    val comparisonValue2 = compareFunction(hand2, hand1)

    expectedResult match {
      case '>' => {
        assert(comparisonValue1 > 0, comment)
        assert(comparisonValue2 < 0, comment)
      }
      case '<' => {
        assert(comparisonValue1 < 0, comment)
        assert(comparisonValue2 > 0, comment)
      }
      case '=' => {
        assert(comparisonValue1 == 0, comment)
        assert(comparisonValue2 == 0, comment)
      }
    }
  }

  def permutateOtherCardsOfHand(allCards: List[Card], cardsToExclude: List[Card]): List[PokerHand] = {

    // if there's only one card to pick, just return the hand
    val allowedCards = allCards.filter(card => !cardsToExclude.contains(card))
    if (allowedCards.size == 1) {
      List(new PokerHand(allowedCards.head :: cardsToExclude))
    }
    // otherwise permute the rest recursively
    else  {
      allowedCards.flatMap(card => permutateOtherCardsOfHand(allCards, card :: cardsToExclude))
    }
  }

  def permutate(hand: PokerHand): List[PokerHand] = {
    hand.cards.flatMap(card => permutateOtherCardsOfHand(hand.cards, List(card)))
  }

}


text:
package org.apache.camel.component.salesforce.api.dto.approval;

import java.io.IOException;
import java.util.Iterator;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.camel.component.salesforce.api.dto.approval.ApprovalResult.Result;
import org.apache.camel.component.salesforce.api.utils.JsonUtils;
import org.junit.jupiter.api.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsCollectionContaining.hasItems;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class ApprovalResultTest {

    @Test
    public void shouldDeserializeFromJson() throws JsonProcessingException, IOException {
        final String json = "["//
                            + "{"//
                            + "\"actorIds\":[\"0050Y000000u5NOQAY\"],"//
                            + "\"entityId\":\"0010Y000005BYrZQAW\","//
                            + "\"errors\":null,"//
                            + "\"instanceId\":\"04g0Y000000PL53QAG\","//
                            + "\"instanceStatus\":\"Pending\","//
                            + "\"newWorkitemIds\":[\"04i0Y000000L0fkQAC\"],"//
                            + "\"success\":true"//
                            + "}"//
                            + "]";

        final ObjectMapper mapper = JsonUtils.createObjectMapper();

        final ApprovalResult results = mapper.readerFor(ApprovalResult.class).readValue(json);

        assertResponseReadCorrectly(results);
    }

    private static void assertResponseReadCorrectly(final ApprovalResult results) {
        final Iterator<Result> resultsIterator = results.iterator();
        assertTrue(resultsIterator.hasNext(), "Should deserialize one approval result result");

        final ApprovalResult.Result result = resultsIterator.next();

        assertThat("Should deserialize actorIds", result.getActorIds(), hasItems("0050Y000000u5NOQAY"));
        assertEquals("0010Y000005BYrZQAW", result.getEntityId(), "Should deserialize entityId");
        assertEquals("04g0Y000000PL53QAG", result.getInstanceId(), "Should deserialize instanceId");
        assertEquals("Pending", result.getInstanceStatus(), "Should deserialize instanceStatus");
        assertThat("Should deserialize newWorkitemIds", result.getNewWorkitemIds(), hasItems("04i0Y000000L0fkQAC"));
        assertTrue(result.isSuccess(), "Should deserialize success");

        assertFalse(resultsIterator.hasNext(), "Should be no more results");
    }
}


text:
let _ = require('lodash/fp')
let moment = require('moment')
let JWT = require('./JWT')

// SP
// let getModel = async (payload) => _.pick(['user', 'customer'], await Hydrate.userAccount(payload.user))
// let permissionsForUser = (id, customer) => _.find(customer.users, u => u.user.toString() === id).permissions
// let skipConcurrentLogins = async (req) =>
//   _.get('customer.data.accountType', req) === 'WhiteLabel'
//   || await sails.mongols.CustomerAccount.findOne({ _id: { $in: req.customer.ancestors }, 'data.accountType': 'WhiteLabel' })
//   ||  _.includes('concurrentLogin', permissionsForUser(req.customer, req.user.id))
// let getMostRecentLogin = async (user) => _.first((await user.activityLogs({ type: 'login' }, null, { limit: 1, sort: { timestamp: -1 } })).results)
// require('sp-jwt').isAuthenticated(getModel, getMostRecentLogin, skipConcurrentLogins)

// GQ
// require('sp-jwt').isAuthenticated(
//   async (payload) => ({ user: await sails.Models.User.findOne({ id: payload.user }) }),
//   _.get('lastLogin')
// )

// JWT iat is in seconds, so drop ms and accept 1s margin of error
let dropMS = timestamp => moment((Math.floor(timestamp / 1000) - 1) * 1000).valueOf()

module.exports = (getModel, getMostRecentLogin, skipConcurrentLogins = _.stubFalse) => async function (req, res, next) {
  try {
    // Add JWT payload to req
    let token = JWT.getToken(req)
    await JWT.setTokenPayload(req, token)
    let payload = req.tokenPayload

    // Add req.user, etc
    _.convert({ immutable: false }).extend(req, await getModel(payload))

    // Check Concurrent Login
    let isNotImpersonation = _.isEmpty(payload.impersonateStack)
    if (isNotImpersonation && !(await skipConcurrentLogins(req))) {
      var tokenIssued = moment(JWT.decode(token).iat * 1000).valueOf()
      if (tokenIssued < dropMS(await getMostRecentLogin(req.user))) throw new Error('concurrent login')
    }

    // Refresh token
    // Need to omit `exp` and `iss` as of version 6 because they conflict with expires in and issuer passed in JWT
    res.set('Renewed-Token', JWT.issue(_.omit(['exp', 'iss'], payload)))

    next()
  } catch (e) {
    res.status(401).send({ message: e.message || e })
  }
}


text:
require 'rails_helper'

RSpec.describe 'Admin deletes a friend record', type: :feature, js: :true do

  let(:community_admin) { create(:user, :community_admin, community: community) }
  let(:community) { create :community }
  let!(:keeper) { create(:friend, first_name: 'Persistent', last_name: 'Record', community: community) }
  let(:deleteable) { create(:friend, first_name: 'Deleteable', last_name: 'Record', community: community) }

  before do
    # (Re)create deleteable record since scenario deleted it
    deleteable

    login_as(community_admin)
  end

  describe 'when I delete a Friend record' do
    scenario 'I visit the community admin page' do
      visit community_admin_friends_path(community)
      expect(page).to have_content('Deleteable')
      expect(page).to have_content('Persistent')

      within("tr#friend-#{deleteable.id}") do
        # Delete is in Bootstrap dropdown so open that first
        find('button').click
        click_link 'Delete'
      end

      expect(page).to have_content('Friend record destroyed')
      expect(page).to_not have_content('Deleteable')
      expect(page).to have_content('Persistent')
    end
  end
end


text:
namespace System.Configuration {
    using System.Configuration.Internal;
    using System.Collections;
    using System.Collections.Specialized;
    using System.Configuration;
    using System.Globalization;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Security.Permissions;
    using System.Security;
    using System.Text;
    using System.Xml;

    // An impersonation context that does nothing
    // Used in cases where the Host does not require impersonation.
    class EmptyImpersonationContext : IDisposable {
        static volatile IDisposable s_emptyImpersonationContext;

        static internal IDisposable GetStaticInstance() {
            if (s_emptyImpersonationContext == null) {
                s_emptyImpersonationContext = new EmptyImpersonationContext();
            }

            return s_emptyImpersonationContext;
        }

        public void Dispose() {}
    }
}


text:
/* Standard C Headers */

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

/* Thread pool header file */

#include "threadpool.h"
#include "utils.h"

/******************************************************************************/
void routine (void) {
  printf ("**** Hello World ****\n");
  fflush (stdout);
}

/******************************************************************************/

int main (int argc, char **argv) {
  pthread_pool_t *thread_pool = pthread_pool_init(10);

  /* Initialize a thred pool of size 10 */

  printf ("\x1B[32m %s \x1B[0m%s", "[MAIN]", "Start processing\n");

  /* Leave some time for the threadpool to finish its initialization */
  sleep (1);

  /* Feed the queue with 20 jobs */
  for (int i = 0; i < 20; ++i)
    pthread_pool_exec (thread_pool, routine, NULL);

  /* Shutdown the queue */
  pthread_pool_exec
    (thread_pool, pthread_pool_destroy, (void *) thread_pool);

  printf ("About to sleep\n");
  sleep (10);
  printf ("End of main()\n");

  return EXIT_SUCCESS;
}


text:
extern crate iron;

use iron::{Handler, IronResult, BeforeMiddleware, Request, Response, Chain};

pub struct SelectiveMiddleWare {
    chain: Chain,
}

impl SelectiveMiddleWare {
    /// Create a new SelectiveMiddleWare instance with the given BeforeMiddleware.
    pub fn new<H: Handler, M: BeforeMiddleware>(handler: H, m: Vec<M>) -> Self {

        let mut chain = Chain::new(handler);
        for item in m.into_iter() {
            chain.link_before(item);
        }

        SelectiveMiddleWare {
            chain: chain
        }
    }
}

impl Handler for SelectiveMiddleWare {
    fn handle(&self, req: &mut Request) -> IronResult<Response> {
        self.chain.handle(req)
    }
}

#[macro_export]
macro_rules! with_middleware {
    ($handler:ident, before=[$($y:ident),+] ) => {
        {
            use selective_middleware::SelectiveMiddleWare;
            let before = vec!($( $y  ),*);

            SelectiveMiddleWare::new($handler, before)
        }
    };
    ($handler:ident, [$($y:ident),+] ) => {
        with_middleware!($handler, before=[$( $y  ),*])
    }
}


text:
<!--
 Copyright 2016 Packt Publishing

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<div>
    <form name="form">
        <input type="file" ngf-select ng-model="file" name="file" ngf-accept="'*/*'" required>
        <button type="submit" ng-click="submit()">submit</button>
    </form>
</div>


text:
using System;
using System.IO;
using System.Xml;

namespace Hydra.Framework.XmlSerialization.Common
{
    /// <summary>
    /// Implements an <see cref="XmlTextReader"/> that turns the
    /// first letter of incoming elements and attributes into uppercase.
    /// </summary>
    /// <remarks>
    /// To be used in conjunction with <see cref="XmlFirstLowerWriter"/> for
    /// serialization.
    /// </remarks>
    public class XmlFirstUpperReader
        : XmlTextReader
    {
        #region Constructors
        //
        //**********************************************************************
        /// <summary>
        /// See <see cref="XmlTextReader"/> constructor overloads.
        /// </summary>
        //**********************************************************************
        //
        public XmlFirstUpperReader(Stream input) : base(input) { }

        /// <summary>
        /// See <see cref="XmlTextReader"/> constructor overloads.
        /// </summary>
        public XmlFirstUpperReader(TextReader input) : base(input) { }

        //
        //**********************************************************************
        /// <summary>
        /// See <see cref="XmlTextReader"/> constructor overloads.
        /// </summary>
        //**********************************************************************
        //
        public XmlFirstUpperReader(string url) : base(url) { }

        /// <summary>
        /// See <see cref="XmlTextReader"/> constructor overloads.
        /// </summary>
        public XmlFirstUpperReader(Stream input, XmlNameTable nt) : base(input, nt) { }

        //
        //**********************************************************************
        /// <summary>
        /// See <see cref="XmlTextReader"/> constructor overloads.
        /// </summary>
        //**********************************************************************
        //
        public XmlFirstUpperReader(TextReader input, XmlNameTable nt) : base(input, nt) { }

        /// <summary>
        /// See <see cref="XmlTextReader"/> constructor overloads.
        /// </summary>
        public XmlFirstUpperReader(string url, Stream input) : base(url, input) { }
        //
        //**********************************************************************
        /// <summary>
        /// See <see cref="XmlTextReader"/> constructor overloads.
        /// </summary>
        //**********************************************************************
        //
        public XmlFirstUpperReader(string url, TextReader input) : base(url, input) { }

        /// <summary>
        /// See <see cref="XmlTextReader"/> constructor overloads.
        /// </summary>
        public XmlFirstUpperReader(string url, XmlNameTable nt) : base(url, nt) { }

        //
        //**********************************************************************
        /// <summary>
        /// See <see cref="XmlTextReader"/> constructor overloads.
        /// </summary>
        //**********************************************************************
        //
        public XmlFirstUpperReader(Stream xmlFragment, XmlNodeType fragType, XmlParserContext context) : base(xmlFragment, fragType, context) { }

        /// <summary>
        /// See <see cref="XmlTextReader"/> constructor overloads.
        /// </summary>
        public XmlFirstUpperReader(string url, Stream input, XmlNameTable nt) : base(url, input, nt) { }

        //
        //**********************************************************************
        /// <summary>
        /// See <see cref="XmlTextReader"/> constructor overloads.
        /// </summary>
        //**********************************************************************
        //
        public XmlFirstUpperReader(string url, TextReader input, XmlNameTable nt) : base(url, input, nt) { }

        /// <summary>
        /// See <see cref="XmlTextReader"/> constructor overloads.
        /// </summary>
        public XmlFirstUpperReader(string xmlFragment, XmlNodeType fragType, XmlParserContext context) : base(xmlFragment, fragType, context) { }
        #endregion

        #region Private methods

        private string MakeFirstUpper(string name)
        {
            //
            // Don't process empty strings.
            //
            if (name.Length == 0) return name;
            // If the first is already upper, don't process.
            if (Char.IsUpper(name[0])) return name;
            //
            // If there's just one char, make it lower directly.
            //
            if (name.Length == 1) return name.ToUpper(System.Globalization.CultureInfo.CurrentCulture);
            // Finally, modify and create a string.
            Char[] letters = name.ToCharArray();
            letters[0] = Char.ToUpper(letters[0], System.Globalization.CultureInfo.CurrentUICulture);
            return NameTable.Add(new string(letters));
        }

        #endregion Private methods

        #region Properties
        /// <summary>
        /// Gets the <see cref="System.String"/> with the specified name.
        /// </summary>
        /// <value></value>
        public override string this[string name, string namespaceURI]
        {
            get
            {
                return base[
                    NameTable.Add(XmlFirstLowerWriter.MakeFirstLower(name)), namespaceURI];
            }
        }

        /// <summary>
        /// Gets the <see cref="System.String"/> with the specified name.
        /// </summary>
        /// <value></value>
        public override string this[string name]
        {
            get { return this[name, String.Empty]; }
        }

        /// <summary>
        /// Gets the local name of the current node.
        /// </summary>
        /// <value></value>
        /// <returns>The name of the current node with the prefix removed. For example, LocalName is book for the element <bk:book>.For node types that do not have a name (like Text, Comment, and so on), this property returns String.Empty.</returns>
        public override string LocalName
        {
            get
            {
                //
                // Capitalize elements and attributes.
                //
                if (base.NodeType == XmlNodeType.Element ||
                    base.NodeType == XmlNodeType.EndElement ||
                    base.NodeType == XmlNodeType.Attribute)
                {
                    return base.NamespaceURI == XmlNamespaces.XmlNs ?
                        //
                        // Except if the attribute is a namespace declaration
                        //
                        base.LocalName : MakeFirstUpper(base.LocalName);
                }
                return base.LocalName;
            }
        }

        /// <summary>
        /// Gets the qualified name of the current node.
        /// </summary>
        /// <value></value>
        /// <returns>The qualified name of the current node. For example, Name is bk:book for the element <bk:book>.The name returned is dependent on the <see cref="P:System.Xml.XmlTextReader.NodeType"/> of the node. The following node types return the listed values. All other node types return an empty string.Node Type Name AttributeThe name of the attribute. DocumentTypeThe document type name. ElementThe tag name. EntityReferenceThe name of the entity referenced. ProcessingInstructionThe target of the processing instruction. XmlDeclarationThe literal string xml. </returns>
        public override string Name
        {
            get
            {
                //
                // Again, if this is a NS declaration, pass as-is.
                //
                if (base.NamespaceURI == XmlNamespaces.XmlNs)
                    return base.Name;
                //
                // If there's no prefix, capitalize it directly.
                //
                if (base.Name.IndexOf(":") == -1)
                    return MakeFirstUpper(base.Name);
                else
                {
                    //
                    // Turn local name into upper, not the prefix.
                    //
                    string name = base.Name.Substring(0, base.Name.IndexOf(":") + 1);
                    name += MakeFirstUpper(base.Name.Substring(base.Name.IndexOf(":") + 1));
                    return NameTable.Add(name);
                }
            }
        }

        #endregion Properties

        #region Methods

        //
        //**********************************************************************
        /// <summary>See <see cref="XmlReader.MoveToAttribute(string, string)"/></summary>
        //**********************************************************************
        //
        public override bool MoveToAttribute(string name, string ns)
        {
            return base.MoveToAttribute(
                NameTable.Add(XmlFirstLowerWriter.MakeFirstLower(name)), ns);
        }

        #endregion Methods
    }
}


text:
class GenericProvider

  def numerize(str, ignore: [], bias: :none)
    preprocess(str, ignore)
    numerize_numerals(str, ignore, bias)
    numerize_fractions(str, ignore, bias)
    numerize_ordinals(str, ignore, bias)
    numerize_big_prefixes(str, ignore, bias)
    postprocess(str, ignore)
  end

  private

  def preprocess(str, ignore)
    raise 'must be implemented in subclass'
  end
  def numerize_numerals(str, ignore, bias)
    raise 'must be implemented in subclass'
  end
  def numerize_fractions(str, ignore, bias)
    raise 'must be implemented in subclass'
  end
  def numerize_ordinals(str, ignore, bias)
    raise 'must be implemented in subclass'
  end
  def numerize_big_prefixes(str, ignore, bias)
    raise 'must be implemented in subclass'
  end
  def postprocess(str, ignore)
    raise 'must be implemented in subclass'
  end

  # Turns list of words into a unionized list, ignoring words specified in
  # arguments or that meet the conditions of the yield block
  def regexify(words, ignore:[])
    if block_given?
      return Regexp.union(words.reject { |x| ignore.include?(x) || yield(x) })
    else
      return Regexp.union(words.reject { |x| ignore.include?(x) })
    end
  end

end