text:
#include <assert.h>
#include <limits.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <ctype.h>

#include "errors.h"
#include "ada_name.h"
#include "files.h"
#include "units.h"
#include "allocate.h"
#include "vendor.h"
#include "cpp.h"
#include "configure.h"

extern int auto_package;
extern int ada_version;

#undef NULL
#define NULL			0

#ifndef PATH_MAX
#define PATH_MAX		1024
#endif

#ifndef MAX
#define MAX_NEST		64
#endif

/* unit_t is not externally visible */

#define BITS_PER_INT	(sizeof(int) * BITS_PER_BYTE)
#define UNIT_SET_SIZE	((MAX_UNIQ_FNAMES + BITS_PER_INT - 1) / BITS_PER_INT)

typedef int unit_ref_t[UNIT_SET_SIZE];

typedef struct {
    unsigned	        initialized:1;

    unsigned	        unit_has_ellipsis:1;
    unsigned	        unit_has_const_string:1;
    unsigned            unit_has_unchecked_conversion:1;
    unsigned            unchecked_conversions_in_spec:1;
    unsigned            unit_with_c_pointers:1;
    unsigned	        unit_with_c_const_pointers:1;
    unsigned		unit_has_private_part:1;

    unsigned            header_comment_set:1;

    char * 		src_path;		/* C source file name */
    char *              h_src_path;
    char *              c_src_path;
    file_id_t           h_file_id;
    file_id_t           c_file_id;

    char *		unit_name;		/* Ada package name */
    char *		unit_path;		/* Output spec file name */
    char *		unit_body_path;	        /* Output body file name */

    unit_ref_t   	unit_ref;   /* implicit dependencies */
    unit_ref_t		from_body;  /* implicit references from body */
    unit_ref_t 	        direct_ref; /* explicit includes */

    comment_block_pt    header_comment;         /* comment at beginning */
    comment_block_pt    trailer_comment;        /* comment at unit end  */

} unit_t;

/* OUTPUT FILE DESCRIPTORS */
FILE * cur_unit_fd;     /* set to cur_spec_fd or cur_body_fd as appropriate */
FILE * cur_spec_fd;     /* current spec output file */
FILE * cur_body_fd;     /* current body output file */

char *predef_pkg = "C";   /* This may be overwritten by a command line switch*/

static unit_t *table[MAX_UNIQ_FNAMES];

static unit_n cur_unit;

/* <file_unit_map> keeps track of file-unit
 * (file_id_t -> unit_n) correspondences.
 * The initialization is a special signal that the whole table
 * hasn't been initialized.
 * <unit_count> is the number of active entries in <unit_map>.
 * These values are maintained in <file_unit>.
 */
static unit_n file_unit_map[MAX_UNIQ_FNAMES] = {-2};
static int    unit_count                     = 0;

static int nesting_table[MAX_NEST];
static int nest_level;

unit_n
current_unit(void)
{
    if (! auto_package) return 0;

    assert(cur_unit < unit_count);
    return cur_unit;
}

boolean
is_current_unit (unit_n unit)
{
    return (cur_unit == unit);
}

static void
set_reference(unit_ref_t ref, unit_n ord)
{
    int index;
    int bit;

    index = ord / BITS_PER_INT;
    assert(index < UNIT_SET_SIZE);

    bit = 1 << (ord % BITS_PER_INT);

    ref[index] |= bit;
}

static void
clear_reference(unit_ref_t ref, unit_n ord)
{
    int index;
    int bit;

    index = ord / BITS_PER_INT;
    assert(index < UNIT_SET_SIZE);

    bit = 1 << (ord % BITS_PER_INT);

    ref[index] &= ~bit;
}

static boolean
valid_unit( unit_n unit )
{
    return unit>=0 && unit<MAX_UNIQ_FNAMES && table[unit]!=NULL;
}

void
set_ellipsis(unit_n unit)
{
    assert(valid_unit(unit));
    table[unit]->unit_has_ellipsis = TRUE;
}

boolean
has_ellipsis(unit_n unit)
{
    assert(valid_unit(unit));
    return table[unit]->unit_has_ellipsis;
}

void
set_unit_has_private_part( unit_n unit )
{
    assert(valid_unit(unit));
    table[unit]->unit_has_private_part = TRUE;
}

boolean
unit_has_private_part( unit_n unit )
{
    assert(valid_unit(unit));
    return table[unit]->unit_has_private_part;
}

void
set_unchecked_conversion(unit_n unit, boolean in_spec)
{
    assert(valid_unit(unit));
    table[unit]->unit_has_unchecked_conversion  = TRUE;
    table[unit]->unchecked_conversions_in_spec  = in_spec;
}

boolean
has_unchecked_conversion(unit_n unit)
{
    assert(valid_unit(unit));
    return table[unit]->unit_has_unchecked_conversion;
}

boolean
unchecked_conversions_to_spec(unit_n unit)
{
    assert(valid_unit(unit));
    return table[unit]->unchecked_conversions_in_spec ||
	configured_source_flag( table[unit]->src_path,
			       "unchecked_conversions_to_spec",
			       FALSE );
}

void
with_c_pointers( unit_n unit )
{
    assert( valid_unit(unit) );
    table[unit]->unit_with_c_pointers = TRUE;
}

void
with_c_const_pointers( unit_n unit )
{
    assert( valid_unit(unit) );
    table[unit]->unit_with_c_const_pointers = TRUE;
}

boolean
has_c_pointers( unit_n unit )
{
    assert( valid_unit(unit) );
    return table[unit]->unit_with_c_pointers;
}

boolean
has_c_const_pointers( unit_n unit )
{
    assert( valid_unit(unit) );
    return table[unit]->unit_with_c_const_pointers;
}

static boolean
is_referenced(unit_ref_t ref, unit_n ord)
    /* Is ord in the set ref? */
{
    int index;
    int bit;

    index = ord / BITS_PER_INT;
    assert(index < UNIT_SET_SIZE);

    bit = 1 << (ord % BITS_PER_INT);

    return (ref[index] & bit) != 0;
}

static void
ref_merge(unit_ref_t r1, unit_ref_t r2)
    /* r1 := union(r1, r2) */
{
    int i;
    for (i = 0; i < UNIT_SET_SIZE; i++) {
	r1[i] |= r2[i];
    }
}

static void
merge_direct_refs(void)
    /*
     * Calculates the closure of unit references for all
     * units.
     * TBD: Why would be want to do this??
     */
{
    unit_n last = unit_count;
    unit_n i, j;

    if (! auto_package) return;

    for (i = 0; i < last; i++) {
	unit_t * unit_i;
	unit_t * ref_j;

	unit_i = table[i];
	assert(unit_i != NULL);
	for (j = 0; j < last; j++) {
	    if (j != i && is_referenced(unit_i->direct_ref, j)) {
		ref_j = table[j];
		assert(ref_j != NULL);
		ref_merge(unit_i->direct_ref, ref_j->direct_ref);
	    }
	}
	/* A unit shouldn't "with" itself */
	clear_reference(unit_i->direct_ref, i);
	clear_reference(unit_i->unit_ref,   i);
    }
}

void
unit_start_gen(void)
{
    cur_unit_fd = cur_spec_fd = cur_body_fd = stdout;
    merge_direct_refs();
}

static char*
gen_unit_name(path)
    char *path;
{
    char buf[PATH_MAX];
    char res[PATH_MAX];
    char *p;
    int  prefix_len;

    if ( (prefix_len = in_system_search_path(path)))  {

	p = buf;
	path += prefix_len;
    } else {
	if (ada_version < 1995){
	    char *last = path;
	    char *s;
	    for (s = path; *s; s++) {
		if (*s == '/') {
		    last = s;
		}
	    }
	    path = last;
	}
	p = buf;
    }

    for (; *path; path++) {
	switch (*path) {
	case '.':
	    if((path[1] == 'h') && (path[2] == '\0')) {
		/* convert "header.h" into "header", not "header_h" */
		goto after_loop;
	    } else if((path[1] == 'c') && (path[2] == '\0')) {
		goto after_loop;
	    } else {
		*p++ = '_';
	    }
	    break;
	case '/':
	    while (path[1] == '/')
		path++;
	    if (ada_version >= 1995)
		/* Convert directory structure into child packages */
		*p++ = '.';
	    else
		*p++ = '_';
	    break;
	default:
	    *p++ = *path;
	    break;
	}
    }
 after_loop:

    *p = 0;

    make_ada_identifier(buf, res);
    return new_string(res);
}

/* An external file may be used to map the names of units, instead
 * of using the names that c2ada would otherwise automatically generate.
 */

typedef struct _unit_map {

    char * include_name;
    char * package_name;
    char * spec_name;
    char * body_name;

    struct _unit_map *next;
} unit_map;

static char * bindings_dir(void);

static unit_map *
decode_unit_map(void)
{
    /*
     * Map file cbind.map used to map unit names
     * This file is expected to be broken into lines
     *
     *	include_file_name package_name spec_file_name body_file_name
     */

    char buf1[100], buf2[100], buf3[100], buf4[100], buf[100];
    FILE *f = fopen("cbind.map", "r");
    unit_map *first, *current;

    if (f != NULL) {
	first = NULL;
	while (!feof(f)) {
	    if (first == NULL) {
		first = current = allocate(sizeof(unit_map));
	    } else {
		current->next = allocate(sizeof(unit_map));
		current = current->next;
	    }
	    fscanf(f, "%s %s %s %s\n", buf1, buf2, buf3, buf4);
	    current->include_name = new_string(buf1);
	    current->package_name = new_string(buf2);
	    sprintf(buf, "%s/%s", bindings_dir(), buf3);
	    current->spec_name    = new_string(buf);
	    sprintf(buf, "%s/%s", bindings_dir(), buf4);
	    current->body_name    = new_string(buf);
	}
    }
    return first;
}

static void
dump_unit_map(unit_map *first)
    /* for debugging */
{
    printf("include name\tpackage name\tspec name\tbody name\n");
    printf("------------\t------------\t---------\t---------\n");
    while(first) {
	printf("%s\t%s\t%s\t%s\n", first->include_name,
	       first->package_name, first->spec_name, first->body_name);
	first = first->next;
    }
}

static unit_map *
find_unit(first, iname)
    unit_map *first;
    char *iname;
{
    while(first) {
	if(!compare_path(first->include_name, iname))
	    return first;
	first = first->next;
    }
    return NULL;
}

static void
initialize_unit(unit_n ord, file_id_t file)
{
    static boolean    first_time = TRUE;
    static unit_map * umap = NULL;

    char       buf[PATH_MAX];
    char       buf2[PATH_MAX];
    unit_t *   unit;
    char *     start_unit;

    extern int map_files;
    unit_map * this_unit;

    assert(table[ord] == NULL);

    if (first_time) {
	if (map_files) umap = decode_unit_map();
	first_time = FALSE;
    }

    unit = NEW(unit_t);

    unit->src_path = file_name_from_ord(ord);
    assert(unit->src_path != NULL);

    if ((this_unit = find_unit(umap, unit->src_path)) == NULL) {
	unit->unit_name = gen_unit_name(unit->src_path);
	assert(unit->unit_name != NULL);

	sprintf(buf, "%s/", bindings_dir());
	start_unit = &buf[strlen(buf)];
	strcat(buf, unit->unit_name);

	switch (ada_compiler) {
	case VADS:
	    strcpy(buf2, buf);
	    strcat(buf, ".a");
	    strcat(buf2, ".bdy.a");
	    break;

	case GNAT:
	    {
		char *p;
		char  c;

		for( p = start_unit; (c = *p) != '\0'; p++ ) {
		    if (c == '.') {
			if (p-start_unit >= 2) {
			    *p = '-';
			} else {
			    *p = '+';
			}
		    }
		}
		for (p = buf; (c=*p) ; p++) {
		    if  (isupper(c)) *p = tolower(c) ;
		}
		strcpy(buf2, buf);
		strcat(buf, ".ads");
		strcat(buf2, ".adb");
		break;
	    }
	    break;

	case Rational:
	    strcpy(buf2, buf);
	    strcat(buf, ".1.ada");
	    strcat(buf2, ".2.ada");
	    break;

	default:
	    strcpy(buf2, buf);
	    strcat(buf, ".ada");
	    strcat(buf2, ".body.ada");
	    break;
	}
	unit->unit_path = new_string(buf);
	unit->unit_body_path = new_string(buf2);
    } else {
	unit->unit_name      = this_unit->package_name;
	unit->unit_path      = this_unit->spec_name;
	unit->unit_body_path = this_unit->body_name;
    }

    unit->initialized = TRUE;

    table[ord] = unit;
}

static void
dump_unit(unit_n ord)
    /* print out information about a unit from the unit table */
    /* for debugging */
{
    unit_t *unit;

    unit = table[ord];
    assert(unit != NULL);

    printf("unit %d\n", ord);
    printf("\tsrc = %s\n", unit->src_path);
    printf("\tname = %s\n", unit->unit_name);
    printf("\tpath = %s\n", unit->unit_path);
    fflush(stdout);
}

void
unit_included(file_pos_t pos, int nest)
    /*
     * <pos> indicates a unit <ord> that was found in an #include
     * directive. <nest> indicates the depth of the include.
     * This routine uses the nesting table to keep track of what's
     * included in what.  An inclusion results in a "with" clause.
     */
{
    unit_t *unit;
    int ord;
    int uord;

    if (! auto_package) return;
    if (nest < 1) return;
    if (nest >= MAX_NEST) return;

    ord = pos_unit(pos);

    if (nest > nest_level) {

	uord = nesting_table[nest_level];
	unit = table[uord];
	assert(unit != NULL);
	set_reference(unit->direct_ref, ord);
/*	set_reference(unit->unit_ref, ord); */
    }

    nest_level = nest;
    nesting_table[nest] = ord;
}

void
init_unit(file_pos_t pos)
{
    unit_n    unit;
    file_id_t file;

    if (! auto_package) return;

    unit = pos_unit(pos);
    file = pos_file(pos);
    if (table[unit] == NULL) {
	initialize_unit(unit, file);
    }
    cur_unit = unit;
}

static char *
bindings_dir()
{
    static char * result;
    if (!result) {
	result = configured_output_dir();
	if (!result) result = "bindings";
    }
    return result;
}

boolean
set_unit(unit_n ord)
    /* returns TRUE only if output file can't be opened */
{
    unit_t *unit;
    static int first_time = 1;

    if (! auto_package) return 0;

    assert(ord >= 0);
    assert(ord < unit_count);

    unit = table[ord];
    assert(unit != NULL);

    if (first_time) {
	mkdir(bindings_dir(), 0777);
	first_time = 0;
    }

    cur_unit = ord;

    cur_spec_fd = fopen(unit->unit_path, "w");
    if (cur_spec_fd == NULL) {
	syserr(unit->unit_path, 0);
	return 1;
    }
    cur_body_fd = fopen(unit->unit_body_path, "w");
    if (cur_body_fd == NULL) {
	syserr(unit->unit_body_path, 0);
	return 1;
    }

    output_to_spec(); /* start out with spec in new unit */

    inform(0, 0, "Generating %s %s", unit->unit_path, unit->unit_body_path);
    return 0;
}

void
unit_completed()
{
    if (auto_package) {
	fclose(cur_spec_fd);
	fclose(cur_body_fd);
	cur_unit = MAX_UNIQ_FNAMES + 1;
    }
}

void
unit_dependency(unit_n ord, unit_n dep, boolean from_body)
    /* unit <ord> depends on unit <dep> */
{
    unit_t *ord_unit;
    unit_n  last;

    if (! auto_package) return;

    last = unit_count;

    assert(ord >= 0 && ord < last);
    assert(dep >= 0 && dep < last);

    ord_unit = table[ord];
    assert(ord_unit != NULL);

    set_reference(from_body? ord_unit->from_body : ord_unit->unit_ref,
		  dep);
}

char*
unit_name(unit_n ord)
{
    unit_t *unit;

    if (! auto_package) return "y";

    assert(ord < unit_count);

    unit = table[ord];
    assert(unit != NULL);

    assert(unit->unit_name != NULL);
    return unit->unit_name;
}

char*
cur_unit_name()
{
    return unit_name(current_unit());
}

char*
cur_unit_source()
{
    unit_t *unit;
    unit_n  ord;

    if (! auto_package) return NULL;

    ord = current_unit();

    unit = table[ord];
    assert(unit != NULL);

    assert(unit->src_path != NULL);
    return unit->src_path;
}

char*
cur_unit_path()
{
    unit_t *unit;
    int ord;

    if (! auto_package) return NULL;

    ord = current_unit();

    unit = table[ord];
    assert(unit != NULL);

    assert(unit->unit_path != NULL);
    return unit->unit_path;
}

static boolean program_has_const_string = FALSE;

void
set_cur_unit_has_const_string(void)
{
    unit_t *unit;
    unit_n  ord;

    if (auto_package) {
	ord = cur_unit;
	if (ord < unit_count) {
	    unit = table[ord];
	    assert(unit != NULL);
	    unit->unit_has_const_string = TRUE;
	}
    } else {
	program_has_const_string = TRUE;
    }
}

int
cur_unit_has_const_string(void)
{
    unit_t *unit;
    int ord;

    if (auto_package) {
	ord = current_unit();
	unit = table[ord];
	assert(unit != NULL);
	return unit->unit_has_const_string;
    } else {
	return program_has_const_string;
    }
}

static int is_child_of_predef;

void
set_cur_unit_is_child_of_predef()
{
    char *unit = cur_unit_name();
    int   i    = strlen(predef_pkg);
    /*
     * If we are not a child of the predefined package, "with" it,
     * so we get the built-in types
     */
    is_child_of_predef =
	((!strncmp(predef_pkg, unit, i)) && (unit[i] == '.'));
}

int
cur_unit_is_child_of_predef()
{
    return is_child_of_predef;
}

static unit_n
nth_element(unit_ref_t set1, unit_ref_t set2, int n)
    /* returns the <n>th element of (<set1>-<set2>) */
    /* set2 may be NULL */
{
    int    count;
    unit_n i;
    unit_n last = unit_count;

    for (count = 0, i = 0; i < last; i++) {
	if (is_referenced(set1,i) &&
	    !(set2 && is_referenced(set2,i))) {

	    if (count == n) {
		return i;
	    }
	    count++;
	}
    }
    return -1;
}

int
nth_ref_unit_ord(int n)
    /* Returns the <n>th dependency of the current unit, or -1. */
{
    unit_t *unit;

    if (!auto_package) return -1;
    unit = table[current_unit()];
    assert(unit != NULL);

    clear_reference(unit->unit_ref, current_unit());
    return nth_element(unit->unit_ref, 0, n);
}

int
nth_direct_ref_unit_ord(int n)
    /* Returns the <n>th "direct reference"  of the current unit, or -1 */
{
    unit_t *unit;

    if (!auto_package) return -1;
    unit = table[current_unit()];
    assert(unit != NULL);

    return nth_element(unit->direct_ref, 0, n);
}

int
nth_body_ref_unit_ord(int n)
{
    unit_t * unit;
    if (!auto_package) return -1;
    unit = table[current_unit()];
    assert(unit!=NULL);

    clear_reference(unit->from_body, current_unit());
    return nth_element(unit->from_body, unit->unit_ref, n);
}

/* Switch output to the current spec or body */

void
output_to_spec(void)
{
    extern void format_to_spec();

    cur_unit_fd = cur_spec_fd;
    format_to_spec();
}

void
output_to_body()
{
    extern void format_to_body();

    cur_unit_fd = cur_body_fd;
    format_to_body();
}

void
output_to(boolean to_spec)
{
    if (to_spec) {
	output_to_spec();
    } else {
	output_to_body();
    }
}

boolean
output_is_spec()
{
    return (cur_unit_fd == cur_spec_fd);
};

/* Set and get unit information fields */

comment_block_pt
cur_unit_header_comment( void )
{
    return table[cur_unit]->header_comment;
}

boolean
cur_unit_header_comment_set(void)
{
    return table[cur_unit]->header_comment_set;
}

void
set_cur_unit_header_comment( comment_block_pt comment )
{
    unit_t * cu = table[cur_unit];
    cu->header_comment = comment;
    cu->header_comment_set = TRUE;
}

comment_block_pt
cur_unit_trailer_comment( void )
{
    return table[cur_unit]->trailer_comment;
}

void
set_cur_unit_trailer_comment( comment_block_pt comment )
{
    table[cur_unit]->trailer_comment = comment;
}

file_id_t
file_partner(file_id_t file)
{
    char * file_id      = file_name_from_ord(file);
    char * partner_name = configured_source_partner(file_id);
    if (partner_name) {
	file_pos_t pos = add_file(partner_name);
	return pos_file(pos);
    } else {
	return -1;
    }
}

int
num_units()
{
    return unit_count;
}

unit_n
file_unit( file_id_t file )
{
    unit_n        result;
    file_id_t     partner;

    if (file_unit_map[0]== -2) {
	/* This is a special signal that <file_unit_map>
	 * hasn't been initialized */
	int i;
	for (i=0; i<MAX_UNIQ_FNAMES; i++) file_unit_map[i] = -1;
    }

    result = file_unit_map[file];
    if (result>=0) return result;

    result = unit_count++;
    file_unit_map[file] = result;
    partner = file_partner(file);
    if (partner >= 0) {
	file_unit_map[partner] = result;
    }
    return result;
}

unit_n
pos_unit(file_pos_t pos)
{
    unit_n result;
    if (auto_package) {
	result = file_unit( pos_file(pos) );
    } else {
	result = 0;
    }
    return result;
}

boolean
pos_in_current_unit(file_pos_t pos)
{
    return pos_unit(pos)==current_unit();
}


text:
package org.kie.remote.client.documentation.jms;

import static org.kie.services.client.serialization.SerializationConstants.DEPLOYMENT_ID_PROPERTY_NAME;
import static org.kie.services.client.serialization.SerializationConstants.SERIALIZATION_TYPE_PROPERTY_NAME;
import static org.kie.services.shared.ServicesVersion.VERSION;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.kie.api.command.Command;  // <1>
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.task.model.TaskSummary;
import org.kie.remote.client.api.RemoteRuntimeEngineFactory;  // <1>
import org.kie.remote.client.api.exception.MissingRequiredInfoException;
import org.kie.remote.client.api.exception.RemoteApiException;
import org.kie.remote.client.api.exception.RemoteCommunicationException;
import org.kie.remote.client.jaxb.ClientJaxbSerializationProvider;
import org.kie.remote.client.jaxb.JaxbCommandsRequest;
import org.kie.remote.client.jaxb.JaxbCommandsResponse;
import org.kie.remote.jaxb.gen.AuditCommand; // <1>
import org.kie.remote.jaxb.gen.GetTaskAssignedAsPotentialOwnerCommand;
import org.kie.remote.jaxb.gen.StartProcessCommand;
import org.kie.remote.jaxb.gen.TaskCommand;
import org.kie.services.client.serialization.JaxbSerializationProvider;
import org.kie.services.client.serialization.SerializationException;
import org.kie.services.client.serialization.SerializationProvider;
import org.kie.services.client.serialization.jaxb.impl.JaxbCommandResponse;
import org.kie.services.client.serialization.jaxb.rest.JaxbExceptionResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SendJmsExamples {

    protected static final Logger logger = LoggerFactory.getLogger(SendJmsExamples.class);

    public void sendCommandsViaJms( String user, String password, String connectionUser, String connectionPassword,
            String deploymentId, String processId, String hostName ) {

        /**
         * JMS setup
         */
        // Get JNDI context from server
        InitialContext context = RemoteRuntimeEngineFactory.getRemoteJbossInitialContext(hostName, connectionUser, connectionPassword);

        // Create JMS connection
        ConnectionFactory connectionFactory;
        try {
            connectionFactory = (ConnectionFactory) context.lookup("jms/RemoteConnectionFactory");
        } catch( NamingException ne ) {
            throw new RuntimeException("Unable to lookup JMS connection factory.", ne);
        }

        // Setup queues
        Queue sessionQueue, taskQueue, sendQueue, responseQueue;
        try {
            sendQueue = sessionQueue = (Queue) context.lookup("jms/queue/KIE.SESSION");
            taskQueue = (Queue) context.lookup("jms/queue/KIE.TASK");
            responseQueue = (Queue) context.lookup("jms/queue/KIE.RESPONSE");
        } catch( NamingException ne ) {
            throw new RuntimeException("Unable to lookup send or response queue", ne);
        }

        /**
         * Command preparation
         */
        StartProcessCommand startProcCmd = new StartProcessCommand();
        startProcCmd.setProcessId(processId);

        /**
         * Send command via JMS and receive response
         */
        SerializationProvider serializationProvider = ClientJaxbSerializationProvider.newInstance();
        ProcessInstance procInst = (ProcessInstance) sendJmsCommand(startProcCmd,
                connectionUser, connectionPassword,
                user, password, deploymentId, null,
                connectionFactory, sendQueue, responseQueue,
                serializationProvider, Collections.EMPTY_SET, JaxbSerializationProvider.JMS_SERIALIZATION_TYPE,
                5 * 1000);

        /**
         * Command preparation
         */
        GetTaskAssignedAsPotentialOwnerCommand gtaapoCmd = new GetTaskAssignedAsPotentialOwnerCommand();
        gtaapoCmd.setUserId(user);

        // Send command request
        Long processInstanceId = null; // needed if you're doing an operation on a PER_PROCESS_INSTANCE deployment

        /**
         * Send command via JMS and receive response
         */
        @SuppressWarnings("unchecked")
        List<TaskSummary> taskSumList = (List<TaskSummary>) sendJmsCommand(gtaapoCmd,
                connectionUser, connectionPassword,
                user, password, deploymentId, processInstanceId,
                connectionFactory, sendQueue, responseQueue,
                serializationProvider, Collections.EMPTY_SET, JaxbSerializationProvider.JMS_SERIALIZATION_TYPE,
                5 * 1000);

        long taskId = taskSumList.get(0).getId();
    }

    // @formatter:off
    public static Object sendJmsCommand( Command command,
            String connUser, String connPassword,
            String userName, String password, String deploymentId, Long processInstanceId,
            ConnectionFactory factory, Queue sendQueue, Queue responseQueue,
            SerializationProvider serializationProvider, Set<Class<?>> extraJaxbClasses, int serializationType,
            long timeoutInMillisecs ) {
    // @formatter:on

        if( deploymentId == null && !(command instanceof TaskCommand || command instanceof AuditCommand) ) {
            throw new MissingRequiredInfoException("A deployment id is required when sending commands involving the KieSession.");
        }
        JaxbCommandsRequest req; // <2>
        if( command instanceof AuditCommand ) {
            req = new JaxbCommandsRequest(command);
        } else {
            req = new JaxbCommandsRequest(deploymentId, command);
        }

        req.setProcessInstanceId(processInstanceId);
        req.setUser(userName);
        req.setVersion(VERSION);

        Connection connection = null;
        Session session = null;
        JaxbCommandsResponse cmdResponse = null;
        String corrId = UUID.randomUUID().toString();
        String selector = "JMSCorrelationID = '" + corrId + "'";
        try {

            // setup
            MessageProducer producer;
            MessageConsumer consumer;
            try {
                if( password != null ) {
                    connection = factory.createConnection(connUser, connPassword);
                } else {
                    connection = factory.createConnection();
                }
                session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

                producer = session.createProducer(sendQueue);
                consumer = session.createConsumer(responseQueue, selector);

                connection.start();
            } catch( JMSException jmse ) {
                throw new RemoteCommunicationException("Unable to setup a JMS connection.", jmse);
            }

            // Create msg
            TextMessage textMsg; // <3>
            try {

                // serialize request
                String xmlStr = serializationProvider.serialize(req); // <4>
                textMsg = session.createTextMessage(xmlStr);

                // set properties
                // 1. corr id
                textMsg.setJMSCorrelationID(corrId);
                // 2. serialization info
                textMsg.setIntProperty(SERIALIZATION_TYPE_PROPERTY_NAME, serializationType);
                if( extraJaxbClasses != null && !extraJaxbClasses.isEmpty() ) {
                    if( deploymentId == null ) {
                        throw new MissingRequiredInfoException(
                                "Deserialization of parameter classes requires a deployment id, which has not been configured.");
                    }
                    textMsg.setStringProperty(DEPLOYMENT_ID_PROPERTY_NAME, deploymentId);
                }
                // 3. user/pass for task operations
                boolean isTaskCommand = (command instanceof TaskCommand);
                if( isTaskCommand ) {
                    if( userName == null ) {
                        throw new RemoteCommunicationException(
                                "A user name is required when sending task operation requests via JMS");
                    }
                    if( password == null ) {
                        throw new RemoteCommunicationException(
                                "A password is required when sending task operation requests via JMS");
                    }
                    textMsg.setStringProperty("username", userName);
                    textMsg.setStringProperty("password", password);
                }
                // 4. process instance id
            } catch( JMSException jmse ) {
                throw new RemoteCommunicationException("Unable to create and fill a JMS message.", jmse);
            } catch( SerializationException se ) {
                throw new RemoteCommunicationException("Unable to deserialze JMS message.", se.getCause());
            }

            // send
            try {
                producer.send(textMsg);
            } catch( JMSException jmse ) {
                throw new RemoteCommunicationException("Unable to send a JMS message.", jmse);
            }

            // receive
            Message response;
            try {
                response = consumer.receive(timeoutInMillisecs);
            } catch( JMSException jmse ) {
                throw new RemoteCommunicationException("Unable to receive or retrieve the JMS response.", jmse);
            }

            if( response == null ) {
                logger.warn("Response is empty");
                return null;
            }
            // extract response
            assert response != null: "Response is empty.";
            try {
                String xmlStr = ((TextMessage) response).getText();
                cmdResponse = (JaxbCommandsResponse) serializationProvider.deserialize(xmlStr); // <4>
            } catch( JMSException jmse ) {
                throw new RemoteCommunicationException("Unable to extract " + JaxbCommandsResponse.class.getSimpleName()
                        + " instance from JMS response.", jmse);
            } catch( SerializationException se ) {
                throw new RemoteCommunicationException("Unable to extract " + JaxbCommandsResponse.class.getSimpleName()
                        + " instance from JMS response.", se.getCause());
            }
            assert cmdResponse != null: "Jaxb Cmd Response was null!";
        } finally {
            if( connection != null ) {
                try {
                    connection.close();
                    if( session != null ) {
                        session.close();
                    }
                } catch( JMSException jmse ) {
                    logger.warn("Unable to close connection or session!", jmse);
                }
            }
        }

        String version = cmdResponse.getVersion();
        if( version == null ) {
            version = "pre-6.0.3";
        }
        if( !version.equals(VERSION) ) {
            logger.info("Response received from server version [{}] while client is version [{}]! This may cause problems.",
                    version, VERSION);
        }

        List<JaxbCommandResponse<?>> responses = cmdResponse.getResponses();
        if( responses.size() > 0 ) {
            JaxbCommandResponse<?> response = responses.get(0);
            if( response instanceof JaxbExceptionResponse ) {
                JaxbExceptionResponse exceptionResponse = (JaxbExceptionResponse) response;
                throw new RemoteApiException(exceptionResponse.getMessage());
            } else {
                return response.getResult();
            }
        } else {
            assert responses.size() == 0: "There should only be 1 response, not " + responses.size() + ", returned by a command!";
            return null;
        }
    }
}
// END

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?><!--
  ~ Copyright (C) 2014 The Android Open Source Project.
  ~
  ~        yinglovezhuzhu@gmail.com
  ~
  ~ 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.
  -->

<PreferenceGroup xmlns:camera="http://schemas.android.com/apk/res/com.opensource.opencamera">
    <PreferenceGroup camera:title="@string/pref_camcorder_settings_category">
        <IconListPreference
            camera:defaultValue="@string/pref_video_quality_default"
            camera:entries="@array/pref_video_quality_entries"
            camera:entryValues="@array/pref_video_quality_entryvalues"
            camera:key="pref_video_quality_key"
            camera:largeIcons="@array/video_quality_icons"
            camera:title="@string/pref_video_quality_title" />
        <IconListPreference
            camera:defaultValue="@string/pref_camera_video_flashmode_default"
            camera:entries="@array/pref_camera_video_flashmode_entries"
            camera:entryValues="@array/pref_camera_video_flashmode_entryvalues"
            camera:icons="@array/pref_camera_video_flashmode_icons"
            camera:key="pref_camera_video_flashmode_key"
            camera:largeIcons="@array/video_flashmode_icons"
            camera:title="@string/pref_camera_flashmode_title" />
        <IconListPreference
            camera:defaultValue="@string/pref_camera_whitebalance_default"
            camera:entries="@array/pref_camera_whitebalance_entries"
            camera:entryValues="@array/pref_camera_whitebalance_entryvalues"
            camera:icons="@array/pref_camera_whitebalance_icons"
            camera:key="pref_camera_whitebalance_key"
            camera:largeIcons="@array/whitebalance_icons"
            camera:title="@string/pref_camera_whitebalance_title" />
        <ListPreference
            camera:defaultValue="@string/pref_camera_coloreffect_default"
            camera:entries="@array/pref_camera_coloreffect_entries"
            camera:entryValues="@array/pref_camera_coloreffect_entryvalues"
            camera:key="pref_camera_coloreffect_key"
            camera:title="@string/pref_camera_coloreffect_title" />
        <IconListPreference
            camera:defaultValue="@string/pref_camera_id_default"
            camera:key="pref_camera_id_key"
            camera:title="@string/pref_camera_id_title" />
    </PreferenceGroup>
</PreferenceGroup>


text:
interpolation
=============

A library for interpolation


text:
package com.hazelcast.spi.impl.eventservice.impl;

import com.hazelcast.nio.Address;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.BinaryInterface;
import com.hazelcast.spi.EventFilter;
import com.hazelcast.spi.EventRegistration;
import com.hazelcast.util.Preconditions;

import java.io.IOException;

// Even though this class is not used in client-member communication, we annotate it to be excluded from related tests, as it
// cannot implement IdentifiedDataSerializable (both EventRegistration and IdentifiedDataSerializable interfaces define a
// method {@code getId()} which differ in return type).
// Since this class is still DataSerializable it should not be moved/renamed in 3.9, otherwise upgradability will be compromised.
@BinaryInterface
public class Registration implements EventRegistration {

    private String id;
    private String serviceName;
    private String topic;
    private EventFilter filter;
    private Address subscriber;
    private transient boolean localOnly;
    private transient Object listener;

    public Registration() {
    }

    public Registration(String id, String serviceName, String topic,
                        EventFilter filter, Address subscriber, Object listener, boolean localOnly) {
        this.id = Preconditions.checkNotNull(id, "Registration ID cannot be null!");
        this.filter = filter;
        this.listener = listener;
        this.serviceName = serviceName;
        this.topic = topic;
        this.subscriber = subscriber;
        this.localOnly = localOnly;
    }

    public String getServiceName() {
        return serviceName;
    }

    public String getTopic() {
        return topic;
    }

    @Override
    public EventFilter getFilter() {
        return filter;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public Address getSubscriber() {
        return subscriber;
    }

    @Override
    public boolean isLocalOnly() {
        return localOnly;
    }

    public Object getListener() {
        return listener;
    }

    // Registration equals() and hashCode() relies on the ID field only,
    // because the registration ID is unique in the cluster
    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Registration)) {
            return false;
        }
        Registration that = (Registration) o;
        return id.equals(that.id);
    }

    @Override
    public int hashCode() {
        return id.hashCode();
    }

    @Override
    public void writeData(ObjectDataOutput out) throws IOException {
        out.writeUTF(id);
        out.writeUTF(serviceName);
        out.writeUTF(topic);
        subscriber.writeData(out);
        out.writeObject(filter);
    }

    @Override
    public void readData(ObjectDataInput in) throws IOException {
        id = in.readUTF();
        serviceName = in.readUTF();
        topic = in.readUTF();
        subscriber = new Address();
        subscriber.readData(in);
        filter = in.readObject();
    }

    @Override
    public String toString() {
        return "Registration{"
                + "filter=" + filter
                + ", id='" + id + '\''
                + ", serviceName='" + serviceName + '\''
                + ", subscriber=" + subscriber
                + ", listener=" + listener
                + '}';
    }
}


text:
<!doctype html>

<meta charset="utf-8">
<title>Crashkurs zur Erstellung von Barplots für Umfrage-Daten – Sebastian Sauer Blog</title>
<meta name="description" content="A blog about research methods, with a focus on data analysis and psychology.">
<meta name="keywords" content="stats, simulation, rstats, deutsch">

<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://sebastiansauer.github.io/images/">
<meta name="twitter:title" content="Crashkurs zur Erstellung von Barplots für Umfrage-Daten">
<meta name="twitter:description" content="A blog about research methods, with a focus on data analysis and psychology.">
<meta name="twitter:creator" content="@sauer_sebastian">

<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="Crashkurs zur Erstellung von Barplots für Umfrage-Daten">
<meta property="og:description" content="A blog about research methods, with a focus on data analysis and psychology.">
<meta property="og:url" content="https://sebastiansauer.github.io/Crashkurs_Barplots/">
<meta property="og:site_name" content="Sebastian Sauer Blog">

<link rel="canonical" href="https://sebastiansauer.github.io/Crashkurs_Barplots/">
<link href="https://sebastiansauer.github.io/feed.xml" type="application/atom+xml" rel="alternate" title="Sebastian Sauer Blog Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="https://sebastiansauer.github.io/assets/css/main.css">

<link href="//fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic" rel="stylesheet" type="text/css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="https://sebastiansauer.github.io/favicon.ico">

<link rel="shortcut icon" href="https://sebastiansauer.github.io/favicon.png">

<link rel="apple-touch-icon-precomposed" href="https://sebastiansauer.github.io/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://sebastiansauer.github.io/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="https://sebastiansauer.github.io/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://sebastiansauer.github.io/images/apple-touch-icon-144x144-precomposed.png">

	<button class="dl-trigger">Open Menu</button>

Home

			About

Sebastian Sauer

Professor at FOM University of Applied Sciences. Thinker on own peril.

Learn More

					 Email

					 Twitter

					 LinkedIn

					 GitHub

					 Stackexchange

			Posts

All Posts

All Tags

Crashkurs zur Erstellung von Barplots für Umfrage-Daten

<time datetime="2016-11-13T11:00:00-05:00">November 13, 2016</time>

Reading time ~15 minutes

Eine recht häufige Art von Daten in der Wirtschaft kommen von Umfragen in der Belegschaft. Diese Daten gilt es dann aufzubereiten und graphisch wiederzugeben. Dafür gibt dieser Post einige grundlegende Hinweise. Grundwissen mit R setzen wir voraus :-)

Eine ausführlichere Beschreibung hier sich z.B. hier.

Packages laden

Nicht vergessen: Ein Computerprogramm (z.B. ein R-Package) kann man nur dann laden, wenn man es vorher installier hat (aber es reicht, das Programm/R-Package einmal zu installieren).

Im Paket tidyverse sind eine Reihe von Paketen gebündelt, die wir brauchen z.B. zum Diagramme erstellen (ggplot2) oder um Daten zu verhackstücken (dplyr, tidyr).

library(tidyverse)

Daten einlesen

Jetzt lesen wir die Daten ein. In RStudio gibt es dafür z.B. den Button "Import Dataset"; der R-Commander hat einen ähnlichen Menüpunkt. Auch Excel-Dateien kann man so einlesen.

Hier laden wir mal beispielhaft einen Datensatz zu einer Online-Umfrage:

data <- read.csv("https://osf.io/meyhp/?action=download")

Der DOI für diesen Datensatz ist 10.17605/OSF.IO/4KGZH.

Der Datensatz besteht aus 10 Extraversions-Items (B5T nach Satow) sowie einigen Verhaltenskorrelaten (zumindest angenommenen). Uns interessieren also hier nur die 10 Extraversions-Items, die zusammen Extraversion als Persönlichkeitseigenschaft messen (sollen). Wir werden die Antworte der Befragten darstelle, aber uns hier keine Gedanken über Messqualität u.a. machen.

Die Umfrage kann hier eingesehen werden.

Schauen wir uns die Daten mal an:

glimpse(data)

## Observations: 501
## Variables: 27
## $ timestamp          <fctr> 11.03.2015 19:17:48, 11.03.2015 19:18:05, ...
## $ code               <fctr> HSC, ERB, ADP, KHB, PTG, ABL, ber, hph, IH...
## $ i01                <int> 3, 2, 3, 3, 4, 3, 4, 3, 4, 4, 3, 3, 4, 4, 3...
## $ i02                <int> 2, 3, 1, 2, 2, 3, 1, 2, 1, 1, 2, 1, 2, 2, 2...
## $ i03                <int> 3, 1, 1, 2, 1, 1, 1, 2, 1, 2, 1, 1, 1, 4, 1...
## $ i04r               <int> 2, 3, 1, 1, 1, 1, 2, 2, 1, 1, 2, 2, 3, 1, 2...
## $ i05                <int> 4, 3, 4, 3, 4, 2, 3, 2, 3, 3, 3, 2, 3, 3, 3...
## $ i06                <int> 1, 3, 4, 2, 2, 2, 2, 3, 1, 2, 2, 2, 2, 2, 2...
## $ i07                <int> 3, 2, 3, 3, 4, 4, 2, 3, 3, 3, 2, 4, 2, 3, 3...
## $ i08r               <int> 3, 2, 3, 2, 3, 2, 2, 3, 2, 2, 2, 3, 2, 2, 1...
## $ i09                <int> 3, 3, 3, 3, 3, 3, 3, 4, 4, 3, 4, 2, 4, 4, 4...
## $ i10                <int> 1, 1, 1, 2, 4, 3, 2, 1, 2, 3, 1, 3, 2, 3, 2...
## $ n_facebook_friends <int> 250, 106, 215, 200, 100, 376, 180, 432, 200...
## $ n_hangover         <dbl> 1, 0, 0, 15, 0, 1, 1, 2, 5, 0, 1, 2, 20, 2,...
## $ age                <int> 24, 35, 25, 39, 29, 33, 24, 28, 29, 38, 25,...
## $ sex                <fctr> Frau, Frau, Frau, Frau, Frau, Mann, Frau, ...
## $ extra_single_item  <int> 4, 3, 4, 3, 4, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4...
## $ time_conversation  <dbl> 10, 15, 15, 5, 5, 20, 2, 15, 10, 10, 1, 5, ...
## $ presentation       <fctr> nein, nein, nein, nein, nein, ja, ja, ja, ...
## $ n_party            <dbl> 20, 5, 3, 25, 4, 4, 3, 6, 12, 5, 10, 5, 10,...
## $ clients            <fctr> , , , , , , , , , , , , , , , , , , , , , ...
## $ extra_vignette     <fctr> , , , , , , , , , , , , , , , , , , , , , ...
## $ extra_description  <int> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,...
## $ prop_na_per_row    <dbl> 0.04347826, 0.04347826, 0.04347826, 0.04347...
## $ extra_mean         <dbl> 2.5, 2.3, 2.4, 2.3, 2.8, 2.4, 2.2, 2.5, 2.2...
## $ extra_median       <dbl> 3.0, 2.5, 3.0, 2.0, 3.0, 2.5, 2.0, 2.5, 2.0...
## $ n_clients          <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,...

Daten aufbereiten

Daten aufbereiten ist ein umfangreiches Geschäft; hier schneiden wir diese Angelegenheit nur kurz an.

Man sollte (u.a.):

fehlende Werte identifizieren, evtl. die Fälle löschen, imputieren oder … nix tun

möglich Fehleingaben identifizieren

Negativ gepolte Items unkodieren

Mittelwerte bilden

…

Statt dessen gehen wir davon aus, dass alles passt :-)

Eine ausführlichere Beschreibung der Aufbereitung dieser Daten findet sich hier.

Daten umstellen für das Plotten

Wir haben ein Diagramm vor Augen (s.u.), bei dem auf der X-Achse die Items stehen (1,2,…,n) und auf der Y-Achse die Anzahl der Kreuze nach Kategorien.

Viele Grafik-Funktionen sind nun so aufgebaut, dass auf der X-Achsen nur eine Variable steht. ggplot2, das wir hier verwenden, ist da keine Ausnahme. Wir müssen also die "breite" Tabelle (10 Spalten, pro Item eine) in eine "lange Spalte" umbauen: Eine Spalte heißt dann "Itemnummer" und die zweite "Wert des Items" oder so ähnlich.

Eine ausführliche Beschreibung findet sich z.B. hier.

Also, los geht's:

Zuerst wählen wir aus der Fülle der Daten, die Spalten, die uns interessieren: Die 10 Extraversions-Items, in diesem Fall.

data_items <- select(data, i01:i10)

Dann stellen wir die Daten von "breit" nach "lang" um, so dass die Items eine Variable bilden und damit für ggplot2 gut zu verarbeiten sind.

data_long <- gather(data_items, key = items, value = Antwort)

data_long$Antwort <- factor(data_long$Antwort)

Den Befehl mit factor brauchen wir für zum Diagramm erstellen im Folgenden. Dieser Befehl macht aus den Zahlen bei der Variable Antwort eine nominale Variable (in R: factor) mit Text-Werten "1", "2" und so weiter. Wozu brauchen wir das? Der Digrammbefehl unten kann nur mit nominalen Variablen Gruppierungen durchführen. Wir werden in dem Diagramm die Anzahl der Antworten darstellen - die Anzahl der Antworten nach Antwort-Gruppe (Gruppe mit Antwort "1" etc.).

Keine Sorge, wenn sich das reichlich ungewöhnlich anhört. Sie müssen es an dieser Stelle nicht erfinden :-)

Man gewöhnt sich daran einerseits; und andererseits ist es vielleicht auch so, dass diese Funktionen nicht perfekt sind, oder nicht aus unserer Sicht oder nur aus Sicht des Menschen, der die Funktion geschrieben hat. Jedenfalls brauchen wir hier eine factor Variable zur Gruppierung…

Damit haben wir es schon! Jetzt wird gemalt.

Erste Diagramme

Wir nutzen ggplot2, wie gesagt, und davon die Funktion qplot (q wie quick, nehme ich an.).

ggplot(data = data_long) +
  aes(x = items)  +
  geom_bar(aes(fill = Antwort), position = "fill")

Was macht dieser ggplot Befehl? Schauen wir es uns in Einzelnen an:

ggplot(data = ...): Wir sagen "Ich möchte gern die Funktion ggplot nutzen, um den Datensatz … zu plotten".

aes(...): Hier definieren wir die "aesthetics" des Diagramms, d.h. alles "Sichtbare". Wir ordnen in diesem Fall der X-Achse die Variable items zu. Per Standardeinstellung geht ggplot davon aus, dass sie die Häufigkeiten der X-Werte auf der Y-Achse haben wollen, wenn Sie nichts über die Y-Achse sagen. Jetzt haben wir ein Koordinatensystem definiert (das noch leer ist).

geom_bar(): "Hey R oder ggplot, jetzt male mal einen barplot in den ansonsten noch leeren plot".

aes(fill = Antwort): Genauer gesagt nutzen wir aes um einen sichtbaren Aspekte des Diagramms (wie die X-Achse) eine Variable des Datensatzes zuzuordnen. Jetzt sagen wir, dass die Füllung (im Balkendiagramm) durch die Werte von Antwort definiert sein sollen (also "1", "2" etc.).

position = "fill" sagt, dass die Gesamt-Höhe des Balken aufgeteilt werden soll mit den "Teil-Höhen" der Gruppen (Antwort-Kategorien 1 bis 4); wir hätten die Teil-Höhen auch nebeneinander stellen können.

Nas entfernen

Vielleicht ist es schöner, die NAs erst zu entfernen.

data_long <- na.omit(data_long)

Und dann noch mal plotten:

ggplot(data = data_long) +
  aes(x = items)  +
  geom_bar(aes(fill = Antwort), position = "fill")

Um 90° drehen

Dazu nehmen wir + coord_flip(), also "flippe das Koordinatensystem".

ggplot(data = data_long) +
  aes(x = items)  +
  geom_bar(aes(fill = Antwort), position = "fill") +
  coord_flip()

Text-Labels für die Items

Wir definieren die Texte ("Labels") für die Items:

item_labels <- c("Ich bin das erste Item",
                 "Das zweite Item",
                 "Item 3 sdjfkladsjk",
                 "Ich bin ein krasser Couch-Potato UMKODIERT",
"i5 asf", "i6 sdf", "adfjks", "sfjlkd", "sdfkjl", "sdfjkl")

Jetzt hängen wir die Labels an die Items im Diagramm:

ggplot(data = data_long) +
  aes(x = items)  +
  geom_bar(aes(fill = Antwort), position = "fill") +
  coord_flip() +
  scale_x_discrete(labels = item_labels)

Man kann auch einen Zeilenumbruch in den Item-Labels erzwingen… wobei das führt uns schon recht weit, aber gut, zum Abschluss :-)

item_labels <- c("Ich bin das erste Item",
                 "Das zweite Item",
                 "Item 3 sdjfkladsjk",
                 "Ich bin ein krasser \nCouch-Potato***mit Zeilenumbruch***",
"i5 asf", "i6 sdf", "adfjks", "sfjlkd", "sdfkjl", "sdfjkl")

Und wieder plotten:

ggplot(data = data_long) +
  aes(x = items)  +
  geom_bar(aes(fill = Antwort), position = "fill") +
  coord_flip() +
  scale_x_discrete(labels = item_labels, name = "Extraversionsitems") +
  scale_y_continuous(name = "Anteile")

Diagramm mit Häufigkeiten, nicht Anteilen

Ach so, schön wäre noch die echten Zahlen an der Y-Achse, nicht Anteile. Dafür müssen wir unseren Diagrammtyp ändern, bzw. die Art der Anordnung ändern. Mit position = "fill" wird der Anteil (also mit einer Summe von 100%) dargestellt. Wir können auch einfach die Zahlen/Häufigkeiten anzeigen, in dem wir die Kategorien "aufeinander stapeln"

ggplot(data = data_long) +
  aes(x = items)  +
  geom_bar(aes(fill = Antwort), position = "stack") +
  coord_flip() +
  scale_x_discrete(labels = item_labels)

Farbschema

Ja, die Wünsche hören nicht auf… Also, noch ein anderes Farbschema:

ggplot(data = data_long) +
  aes(x = items)  +
  geom_bar(aes(fill = Antwort), position = "stack") +
  coord_flip() +
  scale_x_discrete(labels = item_labels) +
  scale_fill_brewer(palette = 17)

Probieren Sie mal ein paar Brewer Farbpaletten aus.

Natürlich kann man noch viel mehr tun; schauen Sie sich z.B. dieses ausführlichere Posting an: https://sebastiansauer.github.io/plotting_surveys/.

        statssimulationrstatsdeutsch

 Like

 Tweet

 +1

      Read More

New bar stacking with ggplot 2.2.0

Recently, `ggplot2` 2.2.0 was released. Among other news, stacking bar plot was improved. Here is a short demonstration.Load libraries```...… Continue reading

Some thoughts (and simulation) on overfitting

        Published on November 12, 2016

Preparing and plotting survey results

        Published on November 10, 2016

    © 2016 Sebastian Sauer. Powered by Jekyll using the HPSTR Theme.


text:
package zhinan.liang.daos.Impl;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import javax.annotation.Resource;

/**
 * Created by liang on 2016/6/1.
 */

/**
 * 为了实现注解,需要这样做*/
public class MyHibernateDaoSupport extends HibernateDaoSupport {
    @Resource
    public void setSuperSessionFactory(SessionFactory sessionFactory){
        super.setSessionFactory(sessionFactory);
    }
}


text:
package org.projog.core.predicate.builtin.compare;

import org.projog.core.predicate.AbstractSingleResultPredicate;
import org.projog.core.term.Term;
import org.projog.core.term.TermComparator;

/* TEST
%FAIL b@=<a
%TRUE b@=<b
%TRUE b@=<c
%FAIL b@=<1
%TRUE b@=<b(a)
*/
/**
 * X@=<Y - term "less than or equal" test.
 *

 * Succeeds when the term argument X is less than or equal to the term argument Y.
 *

 */
public final class TermLessThanOrEqual extends AbstractSingleResultPredicate {
   @Override
   protected boolean evaluate(Term arg1, Term arg2) {
      return TermComparator.TERM_COMPARATOR.compare(arg1, arg2) < 1;
   }
}


text:
var baseCallback = require('../internal/baseCallback');

/**
 * This method is like `_.find` except that it returns the index of the first
 * element `predicate` returns truthy for, instead of the element itself.
 *
 * If a property name is provided for `predicate` the created `_.property`
 * style callback returns the property value of the given element.
 *
 * If a value is also provided for `thisArg` the created `_.matchesProperty`
 * style callback returns `true` for elements that have a matching property
 * value, else `false`.
 *
 * If an object is provided for `predicate` the created `_.matches` style
 * callback returns `true` for elements that have the properties of the given
 * object, else `false`.
 *
 * @static
 * @memberOf _
 * @category Array
 * @param {Array} array The array to search.
 * @param {Function|Object|string} [predicate=_.identity] The function invoked
 *  per iteration.
 * @param {*} [thisArg] The `this` binding of `predicate`.
 * @returns {number} Returns the index of the found element, else `-1`.
 * @example
 *
 * var users = [
 *   { 'user': 'barney',  'active': false },
 *   { 'user': 'fred',    'active': false },
 *   { 'user': 'pebbles', 'active': true }
 * ];
 *
 * _.findIndex(users, function(chr) {
 *   return chr.user == 'barney';
 * });
 * // => 0
 *
 * // using the `_.matches` callback shorthand
 * _.findIndex(users, { 'user': 'fred', 'active': false });
 * // => 1
 *
 * // using the `_.matchesProperty` callback shorthand
 * _.findIndex(users, 'active', false);
 * // => 0
 *
 * // using the `_.property` callback shorthand
 * _.findIndex(users, 'active');
 * // => 2
 */
function findIndex(array, predicate, thisArg) {
  var index = -1,
      length = array ? array.length : 0;

  predicate = baseCallback(predicate, thisArg, 3);
  while (++index < length) {
    if (predicate(array[index], index, array)) {
      return index;
    }
  }
  return -1;
}

module.exports = findIndex;


text:
/**
 *
 */
package org.apache.uima.lucas.indexer.mapping;

/**
 * A description of term covering
 */
public class TermCoverDescription implements Locateable {

	private String coverDefinitionFile;

	private String generateFieldNameMethod;

	private boolean ignoreCaseOfSelectedTerms;

	private String fieldName;

	private int line;

	private int column;

	/**
	 *
	 */
	public TermCoverDescription() {
		generateFieldNameMethod = TermCoverMapper.USE_SUBSET_NAME_APPEND;
		// Lets set the default value to true; this way, one can at least see
		// that there might be too many terms in a field. It's always hard so
		// see what's NOT there.
		ignoreCaseOfSelectedTerms = true;
	}

	/**
	 * @return the coverDefinitonFile
	 */
	public String getCoverDefinitionFile() {
		return coverDefinitionFile;
	}

	/**
	 * @param coverDefinitionFile
	 *            the coverDefinitionFile to set
	 */
	public void setCoverDefinitionFile(String coverDefinitionFile) {
		this.coverDefinitionFile = coverDefinitionFile;
	}

	/**
	 * @see #getGenerateFieldNameMethod()
	 * @param generateFieldNameMethod
	 */
	public void setGenerateFieldNameMethod(String generateFieldNameMethod) {
		this.generateFieldNameMethod = generateFieldNameMethod;

	}

	/**
	 * Returns a string identifying the method of dynamic field name generation.
	 * For valid values, please see below.
	 *
	 * @see TermCoverMapper#USE_SUBSET_NAME_APPEND
	 * @see TermCoverMapper#USE_SUBSET_NAME_PREPEND
	 * @see TermCoverMapper#USE_SUBSET_NAME_REPLACE
	 * @return the method for combination of the cover subset and the field name
	 *         defined in the mapping file (prepending, appending, replacing)
	 */
	public String getGenerateFieldNameMethod() {
		return generateFieldNameMethod;
	}

	/**
	 * @param b
	 */
	public void setIgnoreCaseOfSelectedTerms(boolean ignoreCase) {
		this.ignoreCaseOfSelectedTerms = ignoreCase;

	}

	/**
	 * @return the ignoreCase
	 */
	public boolean getIgnoreCaseOfSelectedTerms() {
		return ignoreCaseOfSelectedTerms;
	}

	/**
	 * @return the fieldName
	 */
	public String getFieldName() {
		return fieldName;
	}

	/**
	 * @param fieldName
	 *            the fieldName to set
	 */
	public void setFieldName(String fieldName) {
		this.fieldName = fieldName;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.apache.uima.lucas.indexer.mapping.Locateable#setLineNumber(int)
	 */
	public void setLineNumber(int lineNumber) {
		line = lineNumber;

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.apache.uima.lucas.indexer.mapping.Locateable#getLineNumber()
	 */
	public int getLineNumber() {
		return line;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.apache.uima.lucas.indexer.mapping.Locateable#setColumnNumber(int)
	 */
	public void setColumnNumber(int columnNumber) {
		column = columnNumber;

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.apache.uima.lucas.indexer.mapping.Locateable#getColumnNumber()
	 */
	public int getColumnNumber() {
		return column;
	}
}


text:
def pytest_generate_tests(metafunc):
    """
    Parameterize a fixture named 'dummy_list' with an empty list
    """
    if 'dummy_list' in metafunc.fixturenames:
        metafunc.parametrize("dummy_list", [[]])