text:
<!DOCTYPE html>

<TITLE>Manpage of PERLMPEIX</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">

linux manpages

{"type":"documentation"}

PERLMPEIX

Section: Perl Programmers Reference Guide (1)
Updated: 2009-02-12
Index
Return to Main Contents

NAME

README.mpeix - Perl/iX for HP e3000 MPE

SYNOPSIS

   http://www.bixby.org/mark/perlix.html
   http://jazz.external.hp.com/src/hp_freeware/perl/
   Perl language for MPE
   Last updated January 12, 2006 @ 2100 UTC

NOTE

This is a podified version of the above-mentioned web page,
podified by Jarkko Hietaniemi 2001-Jan-01.

Binary distribution from HP

The simplest way to obtain Perl for the MPE/iX is to go either of
these URLs and follow the instructions within.

http://jazz.external.hp.com/src/hp_freeware/perl/
http://www.bixby.org/mark/perlix.html

Use which ever one is more recent.

What's New in Perl for MPE/iX

January 12, 2006

*

Updated for perl-5.8.8 and perl-5.9.3 by Ken Hirsch.

Simplified the build process by using the MPEAUTOCONF
functionality in Mark Klein's ld.

If you build this from scratch, make sure you have a version
of ld which supports it.  In the shell, type

  ld --help
    and look for AUTOCONF or MPEAUTOCONF near the bottom

  or do this:
  ld --help 2>&1 | grep AUTOCONF

If you see don't see AUTOCONF or MPEAUTOCONF, make sure you get a new
version.

You also do not have to use mpeix/relink after building, so the
recommend sequence is:

  ./Configure -de

      # or ./Configure -de -Dusedevel
      # if you're building a development version

  make
  make test
     # if you run this in a job, do "make test_notty"

  make install

Be prepared for a wait. These take much longer on MPE/iX than on a Unix
system, because of a slow forking, mostly.  On a lightly-loaded HP3000
Series 979 running MPE/iX 7.5:

    Configure: 1 hour
    make:      1 hour 15 minutes
    make test  1 hour 45 minutes

Various socket problems were fixed in mpeix.c.

Mark Klein provided a fixed sigsetjmp (that works with dynamic
libraries) in mpeix_setjmp.c

June 1, 2000

*

Rebuilt to be compatible with mod_perl.  If you plan on using
mod_perl, you MUST download and install this version of Perl/iX!

*

uselargefiles=``undef'': not available in MPE for POSIX files yet.

*

Now bundled with various add-on packages:

*

libnet (as seen on CPAN)

*

libwww-perl (LWP) which lets Perl programs behave like web browsers:

    1. #!/PERL/PUB/perl
    2. use LWP::Simple;
    3. $doc = get('http://www.bixby.org/mark/perlix.html');  # reads the
       web page into variable $doc

(http://www.bixby.org/mark/perlix.html)

*

mod_perl (just the perl portion; the actual DSO will be released
soon with Apache/iX 1.3.12 from bixby.org).  This module allows you to
write high performance persistent Perl CGI scripts and all sorts of
cool things. (http://perl.apache.org/)

and much much more hiding under /PERL/PUB/.cpan/

*

The CPAN module now works for automatic downloading and
installing of add-on packages:

    1. export FTP_PASSIVE=1
    2. perl -MCPAN -e shell
    3. Ignore any terminal I/O related complaints!

(http://theoryx5.uwinnipeg.ca/CPAN/data/perl/CPAN.html)

May 20, 2000

*

Updated to version 5.6.0.  Builds straight out of the box on MPE/iX.

*

Perl's getpwnam() function which had regressed to being
unimplemented on MPE is now implemented once again.

September 17, 1999

*

Migrated from cccd.edu to bixby.org.

Welcome to Perl/iX

This is the official home page for the HP e3000 MPE/iX
( http://www.hp.com/go/e3000 ) port of the Perl scripting
language ( http://www.perl.com/ ) which gives you all of the power of C,
awk, sed, and sh in a single language. Check here for the latest news,
implemented functionality, known bugs, to-do list, etc. Status reports
about major milestones will also be posted to the HP3000-L mailing list
( http://www.lsoft.com/scripts/wl.exe?SL1=HP3000-L&H=RAVEN.UTC.EDU ) and
its associated gatewayed newsgroup comp.sys.hp.mpe.

I'm doing this port because I can't live without Perl on the Unix
machines that I administer, and I want to have the same power
available to me on MPE.

Please send your comments, questions, and bug reports directly to me,
Mark Bixby ( http://www.bixby.org/mark/ ). Or just post them to HP3000-L.

The platform I'm using to do this port is an HP 3000 957RX running
MPE/iX 6.0 and using the GNU gcc C compiler
( http://jazz.external.hp.com/src/gnu/gnuframe.html ).

The combined porting wisdom from all of my ports can be found in my
MPE/iX Porting Guide (http://www.bixby.org/mark/porting.html).

IMPORTANT NOTICE: Yes, I do work for the HP CSY R&D lab, but ALL of
the software you download from bixby.org is my personal freeware that
is NOT supported by HP.

System Requirements for Perl/iX

*

MPE/iX 5.5 or later. This version of Perl/iX does NOT run on
MPE/iX 5.0 or earlier, nor does it run on ``classic'' MPE/V machines.

*

If you wish to recompile Perl, you must install both GNUCORE and
GNUGCC from jazz (http://jazz.external.hp.com/src/gnu/gnuframe.html).

*

Perl/iX will be happier on MPE/iX 5.5 if you install the MPEKX40B
extended POSIX filename characters patch, but this is optional.

*

Patch LBCJXT6A is required on MPE/iX 5.5 machines in order to
prevent Perl/iX from dying with an unresolved external reference
to _getenv_libc.

*

If you will be compiling Perl/iX yourself, you will also need
Syslog/iX ( http://www.bixby.org/mark/syslogix.html ) and the
/BIND/PUB/include and /BIND/PUB/lib portions of BIND/iX
( http://www.bixby.org/mark/bindix.html ).

How to Obtain Perl/iX

1.

Download Perl using either FTP.ARPA.SYS or some other client

2.

Extract the installation script

3.

Edit the installation script

4.

Run the installation script

5.

Convert your *.a system archive libraries to *.sl shared libraries

Download Perl using FTP.ARPA.SYS from your HP 3000 (the preferred
method).....

    :HELLO MANAGER.SYS
    :XEQ FTP.ARPA.SYS
    open ftp.bixby.org
    anonymous
    your@email.address
    bytestream
    cd /pub/mpe
    get perl-5.6.0-mpe.tar.Z /tmp/perl.tar.Z;disc=2147483647
    exit

.....Or download using some other generic web or ftp client (the alternate
method)

Download the following files (make sure that you use ``binary mode'' or
whatever client feature that is 8-bit clean):

*

Perl from

    http://www.bixby.org/ftp/pub/mpe/perl-5.6.0-mpe.tar.Z

or

    ftp://ftp.bixby.org/pub/mpe/perl-5.6.0-mpe.tar.Z

*

Upload those files to your HP 3000 in an 8-bit clean bytestream manner to:

    /tmp/perl.tar.Z

*

Then extract the installation script (after both download methods)

    :CHDIR /tmp
    :XEQ TAR.HPBIN.SYS 'xvfopz /tmp/perl.tar.Z INSTALL'

*

Edit the installation script

Examine the accounting structure creation commands and modify if
necessary (adding additional capabilities, choosing a non-system
volume set, etc).

    :XEQ VI.HPBIN.SYS /tmp/INSTALL

*

Run the installation script.

The accounting structure will be created and then all files will be
extracted from the archive.

    :XEQ SH.HPBIN.SYS /tmp/INSTALL

*

Convert your *.a system archive libraries to *.sl shared libraries

You only have to do this ONCE on your MPE/iX 5.5 machine in order to
convert /lib/lib*.a and /usr/lib/lib*.a libraries to their *.sl
equivalents.  This step should not be necessary on MPE/iX 6.0 or later
machines because the 6.0 or later update process does it for you.

    :XEQ SH.HPBIN.SYS /PERL/PUB/LIBSHP3K

Perl/iX Distribution Contents Highlights

README

The file you're reading now.

INSTALL

Perl/iX Installation script.

LIBSHP3K

Script to convert *.a system archive libraries to *.sl shared libraries.

PERL

Perl NMPRG executable.  A version-numbered backup copy also
exists.  You might wish to ``ln -s /PERL/PUB/PERL /usr/local/bin/perl''.

.cpan/

Much add-on source code downloaded with the CPAN module.

lib/

Perl libraries, both core and add-on.

man/

Perl man page documentation.

public_html/feedback.cgi

Sample feedback CGI form written in Perl.

src/perl-5.6.0-mpe

Source code.

How to Compile Perl/iX

1.

cd src/perl-5.6.0-mpe

2.

Read the INSTALL file for the official instructions

3.

./Configure -d

4.

make

5.

./mpeix/relink

6.

make test (expect approximately 15 out of 11306 subtests to fail,
mostly due to MPE not supporting hard links, UDP socket problems,
and handling exit() return codes improperly)

7.

make install

8.

Optionally create symbolic links that point to the Perl
executable, i.e. ln -s /PERL/PUB/PERL /usr/local/bin/perl

The summary test results from ``cd t; ./perl -I../lib harness'':

  Failed Test  Status Wstat Total Fail  Failed  List of failed
  ---------------------------------------------------------------------------
  io/fs.t                      29    8  27.59%  2-5, 7-9, 11
  io/openpid.t                 10    1  10.00%  7
  lib/io_sock.t                14    1   7.14%  13
  lib/io_udp.t                  7    2  28.57%  3, 5
  lib/posix.t                  27    1   3.70%  12
  op/lex_assign.t             187    1   0.53%  13
  op/stat.t                    58    1   1.72%  3
  15 tests and 94 subtests skipped.
  Failed 7/236 test scripts, 97.03% okay. 15/11306 subtests failed, 99.87% okay.

Getting Started with Perl/iX

Create your Perl script files with ``#!/PERL/PUB/perl'' (or an
equivalent symbolic link) as the first line.  Use the chmod command to
make sure that your script has execute permission. Run your script!

Be sure to take a look at the CPAN module list
( http://www.cpan.org/CPAN.html ). A wide variety of free Perl software
is available.  You can automatically download these packages by using
the CPAN module ( http://theoryx5.uwinnipeg.ca/CPAN/data/perl/CPAN.html ).

MPE/iX Implementation Considerations

There some minor functionality issues to be aware of when comparing
Perl for Unix (Perl/UX) to Perl/iX:

*

MPE gcc/ld doesn't properly support linking NMPRG executables against
NMXL dynamic libraries, so you must manually run mpeix/relink after
each re-build of Perl.

*

Perl/iX File::Copy will use MPE's /bin/cp command to copy files by
name in order to preserve file attributes like file code.

*

MPE (and thus Perl/iX) lacks support for setgrent(), endgrent(),
setpwent(), endpwent().

*

MPE (and thus Perl/iX) lacks support for hard links.

*

MPE requires GETPRIVMODE() in order to bind() to ports less than 1024.
Perl/iX will call GETPRIVMODE() automatically on your behalf if you
attempt to bind() to these low-numbered ports.  Note that the Perl/iX
executable and the PERL account do not normally have CAP=PM, so if you
will be bind()-ing to these privileged ports, you will manually need
to add PM capability as appropriate.

*

MPE requires that you bind() to an IP address of zero.  Perl/iX
automatically replaces the IP address that you pass to bind() with
a zero.

*

MPE requires GETPRIVMODE() in order to setuid().  There are too many
calls to setuid() within Perl/iX, so I have not attempted an automatic
GETPRIVMODE() solution similar to bind().

Known Perl/iX Bugs Under Investigation

None.

Perl/iX To-Do List

*

Make setuid()/setgid() support work.

*

Make sure that fcntl() against a socket descriptor is redirected to sfcntl().

*

Add support for Berkeley DB once I've finished porting Berkeley DB.

*

Write an MPE XS extension library containing miscellaneous important
MPE functions like GETPRIVMODE(), GETUSERMODE(), and sfcntl().

Perl/iX Change History

May 6, 1999

*

Patch LBCJXT6A is required on MPE/iX 5.5 machines in order to prevent
Perl/iX from dying with an unresolved external reference to _getenv_libc.

April 7, 1999

*

Updated to version 5.005_03.

*

The official source distribution once again compiles ``straight out
of the box'' for MPE.

*

The current incarnation of the 5.5 POSIX filename extended
characters patch is now MPEKX40B.

*

The LIBSHP3K *.a -> *.sl library conversion script is now included
as /PERL/PUB/LIBSHP3K.

November 20, 1998

*

Updated to version 5.005_02.

*

Fixed a DynaLoader bug that was unable to load symbols from relative
path name libraries.

*

Fixed a .xs compilation bug where the mpeixish.sh include file wasn't
being installed into the proper directory.

*

All bugfixes will be submitted back to the official Perl developers.

*

The current incarnation of the POSIX filename extended characters
patch is now MPEKXJ3A.

August 14, 1998

*

The previous POSIX filename extended characters patch MPEKX44C has
been superseded by MPEKXB5A.

August 7, 1998

*

The previous POSIX filename extended characters patch MPEKX76A has
been superseded by MPEKX44C.

July 28, 1998

*

Updated to version 5.005_01.

July 23, 1998

*

Updated to version 5.005 (production release).  The public
freeware sources are now 100% MPE-ready ``straight out of the box''.

July 17, 1998

*

Updated to version 5.005b1 (public beta release).  The public
freeware sources are now 99.9% MPE-ready.  By installing and
testing this beta on your own HP3000, you will be helping to
insure that the final release of 5.005 will be 100% MPE-ready and
100% bug free.

*

My MPE binary release is now extracted using my standard INSTALL script.

July 15, 1998

*

Changed startperl to #!/PERL/PUB/perl so that Perl will recognize
scripts more easily and efficiently.

July 8, 1998

*

Updated to version 5.004_70 (internal developer release) which is now
MPE-ready.  The next public freeware release of Perl should compile
``straight out of the box'' on MPE.  Note that this version of Perl/iX
was strictly internal to me and never publicly released.  Note that
[21]BIND/iX is now required (well, the include files and libbind.a) if
you wish to compile Perl/iX.

November 6, 1997

*

Updated to version 5.004_04.  No changes in MPE-specific functionality.

October 16, 1997

*

Added Demos section to the Perl/iX home page so you can see some
sample Perl applications running on my 3000.

October 3, 1997

*

Added System Requirements section to the Perl/iX home page just so the
prerequisites stand out more. Various other home page tweaks.

October 2, 1997

*

Initial public release.

September 1997

*

Porting begins.

AUTHOR

Mark Bixby, http://www.bixby.org/mark/

Index

NAME

SYNOPSIS

NOTE

Binary distribution from HP

What's New in Perl for MPE/iX

Welcome to Perl/iX

System Requirements for Perl/iX

How to Obtain Perl/iX

Perl/iX Distribution Contents Highlights

How to Compile Perl/iX

Getting Started with Perl/iX

MPE/iX Implementation Considerations

Known Perl/iX Bugs Under Investigation

Perl/iX To-Do List

Perl/iX Change History

AUTHOR

This document was created by
man2html,
using the manual pages.

Time: 05:29:08 GMT, December 24, 2015


text:
import numpy as np
import pandas as pd
import itertools
import csv
import gensim
import re
import nltk.data
import tensorflow
from nltk.tokenize import WordPunctTokenizer
from collections import Counter
from keras.models import Sequential, Graph
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers import LSTM, Merge
from keras.layers.embeddings import Embedding
from keras.layers.convolutional import Convolution1D, MaxPooling1D
from IPython.display import SVG, display
from keras.utils.visualize_util import plot, to_graph

# from keras import backend as K

def clean_str(string):
    """
    Tokenization/string cleaning for all datasets except for SST.
    Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
    """
    string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
    string = re.sub(r"\'s", " \'s", string)
    string = re.sub(r"\'ve", " \'ve", string)
    string = re.sub(r"n\'t", " n\'t", string)
    string = re.sub(r"\'re", " \'re", string)
    string = re.sub(r"\'d", " \'d", string)
    string = re.sub(r"\'ll", " \'ll", string)
    string = re.sub(r",", " , ", string)
    string = re.sub(r"!", " ! ", string)
    string = re.sub(r"\(", " \( ", string)
    string = re.sub(r"\)", " \) ", string)
    string = re.sub(r"\?", " \? ", string)
    string = re.sub(r"\s{2,}", " ", string)
    return string.strip().lower()

def message_to_wordlist(message, lemmas_bool, remove_stopwords=False):
    # Function to convert a document to a sequence of words,
    # optionally removing stop words.  Returns a list of words.
    #
    # 1. Remove HTML
    #review_text = BeautifulSoup(review).get_text()
    #
    # 2. Remove messages numbers
    message_text = re.sub(">>\d+","", message)
    message_text = message_text.lower()
    message_text = re.sub(u"ё", 'e', message_text, re.UNICODE)
    message_text = clean_str(message_text)
    tokenizer = WordPunctTokenizer()
    # 3. Convert words to lower case and split them
    words = tokenizer.tokenize(message_text)
    lemmas = []
    # 4. Optionally remove stop words (false by default)
    if remove_stopwords:
        stops = set(stopwords.words("english"))
        words = [w for w in words if not w in stops]
    if lemmas_bool == 'l':
        for word in words:
            word_parsed = morph.parse(word)
            if len(word_parsed) > 0:
                lemmas.append(word_parsed[0].normal_form)
    elif lemmas_bool == 's':
        for word in words:
            word = stemmer.stem(word)
            if len(word) > 0:
                lemmas.append(word)
    else:
        lemmas = words
    # 5. Return a list of words
    return(lemmas)
    #return(words)

# Define a function to split a message into parsed sentences
def message_to_sentences( message, tokenizer, lemmas_bool, remove_stopwords=False):
    sentences = []
    # Function to split a message into parsed sentences. Returns a
    # list of sentences, where each sentence is a list of words
    #
    # 1. Use the NLTK tokenizer to split the paragraph into sentences
    if type(message) == str:
        message = message.decode('utf-8')
        raw_sentences = tokenizer.tokenize(message.strip())
        #
        # 2. Loop over each sentence
        for raw_sentence in raw_sentences:
            # If a sentence is empty, skip it
            if len(raw_sentence) > 0:
                # Otherwise, call message_to_wordlist to get a list of words
                sentences += message_to_wordlist( raw_sentence,lemmas_bool, remove_stopwords)
    return sentences

def pad_sentences(sentences, padding_word="<PAD/>"):
    """
    Pads all sentences to the same length. The length is defined by the longest sentence.
    Returns padded sentences.
    """
    sequence_length = max(len(x) for x in sentences)
    padded_sentences = []
    for i in range(len(sentences)):
        sentence = sentences[i]
        num_padding = sequence_length - len(sentence)
        new_sentence = sentence + [padding_word] * num_padding
        padded_sentences.append(new_sentence)
    return padded_sentences

def build_vocab(sentences):
    """
    Builds a vocabulary mapping from word to index based on the sentences.
    Returns vocabulary mapping and inverse vocabulary mapping.
    """
    # Build vocabulary
    word_counts = Counter(itertools.chain(*sentences))
    # Mapping from index to word
    vocabulary_inv = [x[0] for x in word_counts.most_common()]
    # Mapping from word to index
    vocabulary = {x: i for i, x in enumerate(vocabulary_inv)}
    return [vocabulary, vocabulary_inv]

def build_input_data(sentences, labels, vocabulary):
    """
    Maps sentencs and labels to vectors based on a vocabulary.
    """
    x = np.array([[vocabulary[word] for word in sentence] for sentence in sentences])
    new_labels = []
    for label in labels:
        if label == 1:
            new_labels.append([1,0])
        else:
            new_labels.append([0,1])
    labels = new_labels
    y = np.array(labels)
    return [x, y]

def load_data():
    messages = pd.read_csv( 'aggression.csv', header=0,
 delimiter="\t", quoting = csv.QUOTE_MINIMAL )
    tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
    labels = messages[:]['Aggression']
    messages = messages[:]['Text']
    messages = [message_to_sentences(message, tokenizer, '') for message in messages]
    pos_data = [nltk.pos_tag(message) for message in messages]
    tags = []
    for sent in pos_data:
        sent_tags = []
        for word in sent:
            sent_tags.append(word[1])
        tags.append(sent_tags)
    messages = pad_sentences(messages)  # turn to the same length
    tags = pad_sentences(tags)
    vocabulary, vocabulary_inv = build_vocab(messages)
    vocabulary_pos, vocabulary_inv_pos = build_vocab(tags)
    x_pos = np.array([[vocabulary_pos[word] for word in sentence] for sentence in tags])
    x, y = build_input_data(messages, labels, vocabulary)
    return [x, y, vocabulary, vocabulary_inv, vocabulary_pos, vocabulary_inv_pos, x_pos]

np.random.seed(2)

model_variation = 'CNN-non-static'  #  CNN-rand | CNN-non-static | CNN-static
print('Model variation is %s' % model_variation)

# Model Hyperparameters
sequence_length = 287
embedding_dim = 600
filter_sizes = (3, 4)
num_filters = 150
dropout_prob = (0.25, 0.5)
hidden_dims = 150

# Training parameters
batch_size = 32
num_epochs = 100
val_split = 0.1

# Word2Vec parameters, see train_word2vec
min_word_count = 4  # Minimum word count
context = 10        # Context window size

print("Loading data...")
x, y, vocabulary, vocabulary_inv, voc_pos, voc_inv_pos, x_pos = load_data()

if model_variation == 'CNN-non-static' or model_variation == 'CNN-static':
    embedding_model = gensim.models.Word2Vec.load('model')
    model_words = embedding_model.index2word
    embedding_weights = [np.array([embedding_model[w] if w in vocabulary and w in model_words\
                                                        else np.random.uniform(-0.25,0.25,600)\
                                                        for w in vocabulary_inv])]
    if model_variation=='CNN-static':
        x = embedding_weights[0][x]
elif model_variation=='CNN-rand':
    embedding_weights = None
else:
    raise ValueError('Unknown model variation')

shuffle_indices = np.random.permutation(np.arange(len(y)))
x_shuffled = x[shuffle_indices]
y_shuffled = y[shuffle_indices].argmax(axis=1)
x_pos = x_pos[shuffle_indices]

print("Vocabulary Size: {:d}".format(len(vocabulary)))

# Building model
# ==================================================
#
# graph subnet with one input and one output,
# convolutional layers concateneted in parallel
graph = Graph()
graph.add_input(name='input', input_shape=(sequence_length, embedding_dim))

for fsz in filter_sizes:
    conv = Convolution1D(nb_filter=num_filters,
                         filter_length=fsz,
                         border_mode='valid',
                         activation='relu',
                         subsample_length=1)
    pool = MaxPooling1D(pool_length=2)
    graph.add_node(conv, name='conv-%s' % fsz, input='input')
    graph.add_node(pool, name='maxpool-%s' % fsz, input='conv-%s' % fsz)
    graph.add_node(Flatten(), name='flatten-%s' % fsz, input='maxpool-%s' % fsz)

if len(filter_sizes)>1:
    graph.add_output(name='output',
                     inputs=['flatten-%s' % fsz for fsz in filter_sizes],
                     merge_mode='concat')
else:
    graph.add_output(name='output', input='flatten-%s' % filter_sizes[0])

# main sequential model
model = Sequential()
if not model_variation=='CNN-static':
    model.add(Embedding(len(vocabulary), embedding_dim, input_length=sequence_length,
                        weights=embedding_weights))
    # model.add(Embedding(len(vocabulary), 1, input_length=sequence_length)
model.add(Dropout(dropout_prob[0], input_shape=(sequence_length, embedding_dim)))
model.add(graph)

model.add(Dense(hidden_dims))
model.add(Dropout(dropout_prob[1]))
model.add(Activation('relu'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
# model.compile(loss='binary_crossentropy', optimizer='rmsprop', class_mode='binary')

model_b = Sequential()
model_b.add(Dense(287, init='uniform', input_shape=(sequence_length,)))
model_b.add(Dense(32, init='uniform'))
model_b.add(Activation('relu'))
model_b.add(Dense(2, init='uniform'))

model_b.compile(loss='binary_crossentropy', optimizer='rmsprop', class_mode='binary')

decoder = Sequential()
decoder.add(Merge([model, model_b], mode='concat'))
decoder.add(Dense(2, activation='softmax'))

decoder.compile(loss='binary_crossentropy', optimizer='rmsprop', class_mode='binary')

# Training model
# ==================================================
print ("Drawing graph")
graph = to_graph(decoder, show_shape=True)
graph.write_png("model.png")
print ("Training model")
decoder.fit([x_shuffled, x_pos], y_shuffled, batch_size=batch_size,
          nb_epoch=num_epochs, show_accuracy=True,
          validation_split=val_split, verbose=2)

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<link rel="stylesheet" type="text/css" href="../../../../../scineplex.css">
<title></title>
<link rel="stylesheet" href="../../../../../Active.css" type="text/css" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:" />

NAME

AFFILIATION

DESCRIPTION

CONFIGURATION

BUGS

AUTHOR

COPYRIGHT

NAME

Perl::Critic::Policy::ValuesAndExpressions::ProhibitCommaSeparatedStatements - Don't use the comma operator as a statement separator.

AFFILIATION

This Policy is part of the core Perl::Critic distribution.

DESCRIPTION

Perl's comma statement separator has really low precedence, which leads to code that looks like it's using the comma list element separator not actually doing so. Conway suggests that the statement separator not be used in order to prevent this situation.

The confusion that the statement separator causes is primarily due to the assignment operators having higher precedence.

For example, trying to combine two arrays into another like this won't work:

    @x = @y, @z;

because it is equivalent to

    @x = @y;
    @z;

Conversely, there are the built-in functions, like print, that normally force the rest of the statement into list context, but don't when called like a subroutine.

This is not likely to produce what is intended:

    print join q{, }, 2, 3, 5, 7, ": the single-digit primes.\n";

The obvious fix is to add parentheses. Placing them like

    print join( q{, }, 2, 3, 5, 7 ), ": the single-digit primes.\n";

will work, but

    print ( join q{, }, 2, 3, 5, 7 ), ": the single-digit primes.\n";

will not, because it is equivalent to

    print( join q{, }, 2, 3, 5, 7 );
    ": the single-digit primes.\n";

CONFIGURATION

This policy can be configured to allow the last statement in a map or grep block to be comma separated. This is done via the allow_last_statement_to_be_comma_separated_in_map_and_grep option like so:

    [ValuesAndExpressions::ProhibitCommaSeparatedStatements]
    allow_last_statement_to_be_comma_separated_in_map_and_grep = 1

With this option off (the default), the following code violates this policy.

    %hash = map {$_, 1} @list;

With this option on, this statement is allowed. Even if this option is off, using a fat comma => works, but that forces stringification on the first value, which may not be what you want.

BUGS

Needs to check for scalar( something, something ).

AUTHOR

Elliot Shank <perl@galumph.com>

COPYRIGHT

Copyright (c) 2007-2011 Elliot Shank.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. The full text of this license can be found in the LICENSE file included with this module.


text:
import React from 'react';

export default class FooterComponent extends React.Component {
  render() {
    return (

          this is index page

          this is index page

          this is index page

    );
  }
}


text:
#ifndef	__ASM_SH_GLOBALDATA_H_
#define __ASM_SH_GLOBALDATA_H_

/* Architecture-specific global data */
struct arch_global_data {
};

#include <asm-generic/global_data.h>

#define DECLARE_GLOBAL_DATA_PTR	register gd_t *gd asm ("r13")

#endif /* __ASM_SH_GLOBALDATA_H_ */


text:
class ChangeSubmittedToBoolean < ActiveRecord::Migration
  def self.up
    change_column :courses, :submitted, :boolean, default: false
  end

  def self.down
    change_column :courses, :submitted, :integer, default: false
  end
end


text:
package com.rubasace.spring.data.repository.mapping;

import com.rubasace.spring.data.repository.RowUnmapper;

import java.util.Map;

/**
 * No-operational implementation of {@link RowUnmapper} that just
 * throws {@link UnsupportedOperationException}.
 */
public class UnsupportedRowUnmapper<T> implements RowUnmapper<T> {

    public Map<String, Object> mapColumns(T o) {
        throw new UnsupportedOperationException(
                "This repository is read-only, it can't store or update entities");
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.utils.timezone
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('qna', '0002_auto_20160606_0130'),
    ]

    operations = [
        migrations.CreateModel(
            name='Answer',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, verbose_name='ID', serialize=False)),
                ('content', models.TextField()),
                ('created_date', models.DateTimeField(default=django.utils.timezone.now)),
                ('updated_date', models.DateTimeField(blank=True, null=True, default=django.utils.timezone.now)),
                ('approved', models.BooleanField(default=False)),
            ],
        ),
        migrations.AlterField(
            model_name='question',
            name='updated_date',
            field=models.DateTimeField(blank=True, null=True, default=django.utils.timezone.now),
        ),
        migrations.AddField(
            model_name='answer',
            name='question',
            field=models.ForeignKey(related_name='answer', to='qna.Question'),
        ),
        migrations.AddField(
            model_name='answer',
            name='user',
            field=models.ForeignKey(to=settings.AUTH_USER_MODEL),
        ),
    ]


text:
#ifndef __servmodel_h
#define __servmodel_h

#include <QStringList>

#include <servicemodel.h>

class McaActions;

class ServiceModel: public McaServiceModel
{
    Q_OBJECT

public:
    ServiceModel(QObject *parent = NULL);
    ~ServiceModel();

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role) const;

    void addService(QString name = QString());
    void removeService(QString name = QString());

    void clear();

    QString displayNameFromId(QString id);
    QString idFromDisplayName(QString name);

public slots:
    void performAction(QString action, QString uniqueid);
    void configure(QString serviceName);

private:
    QStringList m_names;
    QStringList m_categories;
    QStringList m_displayNames;
    QStringList m_requestedNames;
    McaActions *m_actions;
    int m_lastId;
};

#endif  // __servmodel_h


text:
Package.describe({
  name: 'mobile-experience',
  version: '1.0.1',
  // Brief, one-line summary of the package.
  summary: 'Packages for a great mobile user experience',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.imply([
    // Fastclick: remove the 300 ms click event lag in mobile browsers
    "fastclick",

    // A nicer appearance for the status bar in PhoneGap/Cordova apps
    "mobile-status-bar"
  ], "web.cordova");

  api.imply([
    // Show a nice splash image while your PhoneGap/Cordova app's UI is loading.
    // Doesn't do anything without Cordova, but we include it everywhere so you
    // don't need a ton of if statements around your LaunchScreen calls.
    "launch-screen"
  ]);
});


text:
bool gOutlineEnabled = false;

void (* glDrawElementsProcPtr) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices) = glDrawElements;
void (* glDrawArraysProcPtr) (GLenum mode, GLint first, GLsizei count) = glDrawArrays;
void (* glNormDrawElements) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices) = glDrawElements;
void (* glNormDrawArrays) (GLenum mode, GLint first, GLsizei count) = glDrawArrays;

/// A utility for the outline drawing routines
static U32 getIndex(GLenum type, const void *indices, U32 i)
{
   if(type == GL_UNSIGNED_BYTE)
      return ((U8 *) indices)[i];
   else if(type == GL_UNSIGNED_SHORT)
      return ((U16 *) indices)[i];
   else
      return ((U32 *) indices)[i];
}

void glOutlineDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices)
{
   if(mode == GL_POLYGON)
      mode = GL_LINE_LOOP;

   if(mode == GL_POINTS || mode == GL_LINE_STRIP || mode == GL_LINE_LOOP || mode == GL_LINES)
      glDrawElements( mode, count, type, indices );
   else
   {
      glBegin(GL_LINES);
      if(mode == GL_TRIANGLE_STRIP)
      {
         U32 i;
         for(i = 0; i < count - 1; i++)
         {
            glArrayElement(getIndex(type, indices, i));
            glArrayElement(getIndex(type, indices, i + 1));
            if(i + 2 != count)
            {
               glArrayElement(getIndex(type, indices, i));
               glArrayElement(getIndex(type, indices, i + 2));
            }
         }
      }
      else if(mode == GL_TRIANGLE_FAN)
      {
         for(U32 i = 1; i < count; i ++)
         {
            glArrayElement(getIndex(type, indices, 0));
            glArrayElement(getIndex(type, indices, i));
            if(i != count - 1)
            {
               glArrayElement(getIndex(type, indices, i));
               glArrayElement(getIndex(type, indices, i + 1));
            }
         }
      }
      else if(mode == GL_TRIANGLES)
      {
         for(U32 i = 3; i <= count; i += 3)
         {
            glArrayElement(getIndex(type, indices, i - 3));
            glArrayElement(getIndex(type, indices, i - 2));
            glArrayElement(getIndex(type, indices, i - 2));
            glArrayElement(getIndex(type, indices, i - 1));
            glArrayElement(getIndex(type, indices, i - 3));
            glArrayElement(getIndex(type, indices, i - 1));
         }
      }
      else if(mode == GL_QUADS)
      {
         for(U32 i = 4; i <= count; i += 4)
         {
            glArrayElement(getIndex(type, indices, i - 4));
            glArrayElement(getIndex(type, indices, i - 3));
            glArrayElement(getIndex(type, indices, i - 3));
            glArrayElement(getIndex(type, indices, i - 2));
            glArrayElement(getIndex(type, indices, i - 2));
            glArrayElement(getIndex(type, indices, i - 1));
            glArrayElement(getIndex(type, indices, i - 4));
            glArrayElement(getIndex(type, indices, i - 1));
         }
      }
      else if(mode == GL_QUAD_STRIP)
      {
         if(count < 4)
            return;
         glArrayElement(getIndex(type, indices, 0));
         glArrayElement(getIndex(type, indices, 1));
         for(U32 i = 4; i <= count; i += 2)
         {
            glArrayElement(getIndex(type, indices, i - 4));
            glArrayElement(getIndex(type, indices, i - 2));

            glArrayElement(getIndex(type, indices, i - 3));
            glArrayElement(getIndex(type, indices, i - 1));

            glArrayElement(getIndex(type, indices, i - 2));
            glArrayElement(getIndex(type, indices, i - 1));
         }
      }
      glEnd();
   }
}

void glOutlineDrawArrays(GLenum mode, GLint first, GLsizei count)
{
   if(mode == GL_POLYGON)
      mode = GL_LINE_LOOP;

   if(mode == GL_POINTS || mode == GL_LINE_STRIP || mode == GL_LINE_LOOP || mode == GL_LINES)
      glDrawArrays( mode, first, count );
   else
   {
      glBegin(GL_LINES);
      if(mode == GL_TRIANGLE_STRIP)
      {
         U32 i;
         for(i = 0; i < count - 1; i++)
         {
            glArrayElement(first + i);
            glArrayElement(first + i + 1);
            if(i + 2 != count)
            {
               glArrayElement(first + i);
               glArrayElement(first + i + 2);
            }
         }
      }
      else if(mode == GL_TRIANGLE_FAN)
      {
         for(U32 i = 1; i < count; i ++)
         {
            glArrayElement(first);
            glArrayElement(first + i);
            if(i != count - 1)
            {
               glArrayElement(first + i);
               glArrayElement(first + i + 1);
            }
         }
      }
      else if(mode == GL_TRIANGLES)
      {
         for(U32 i = 3; i <= count; i += 3)
         {
            glArrayElement(first + i - 3);
            glArrayElement(first + i - 2);
            glArrayElement(first + i - 2);
            glArrayElement(first + i - 1);
            glArrayElement(first + i - 3);
            glArrayElement(first + i - 1);
         }
      }
      else if(mode == GL_QUADS)
      {
         for(U32 i = 4; i <= count; i += 4)
         {
            glArrayElement(first + i - 4);
            glArrayElement(first + i - 3);
            glArrayElement(first + i - 3);
            glArrayElement(first + i - 2);
            glArrayElement(first + i - 2);
            glArrayElement(first + i - 1);
            glArrayElement(first + i - 4);
            glArrayElement(first + i - 1);
         }
      }
      else if(mode == GL_QUAD_STRIP)
      {
         if(count < 4)
            return;
         glArrayElement(first + 0);
         glArrayElement(first + 1);
         for(U32 i = 4; i <= count; i += 2)
         {
            glArrayElement(first + i - 4);
            glArrayElement(first + i - 2);

            glArrayElement(first + i - 3);
            glArrayElement(first + i - 1);

            glArrayElement(first + i - 2);
            glArrayElement(first + i - 1);
         }
      }
      glEnd();
   }
}

ConsoleFunction(GLEnableOutline,void,2,2,"GLEnableOutline( true | false ) - sets whether to render wireframe")
{
   gOutlineEnabled = dAtob(argv[1]);
   if(gOutlineEnabled)
   {
      glDrawElementsProcPtr = glOutlineDrawElements;
      glDrawArraysProcPtr = glOutlineDrawArrays;
      Con::printf("swapped to outline mode funcs");
   } else {
      glDrawElementsProcPtr = glDrawElements;
      glDrawArraysProcPtr = glDrawArrays;
      Con::printf("swapped to normal funcs");
   }
}
#endif


text:
// Copyright 2015 Google Inc. All Rights Reserved.
//
// 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.

package adwords.axis.v201506.basicoperations;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.v201506.cm.AdGroupCriterion;
import com.google.api.ads.adwords.axis.v201506.cm.AdGroupCriterionOperation;
import com.google.api.ads.adwords.axis.v201506.cm.AdGroupCriterionReturnValue;
import com.google.api.ads.adwords.axis.v201506.cm.AdGroupCriterionServiceInterface;
import com.google.api.ads.adwords.axis.v201506.cm.BiddableAdGroupCriterion;
import com.google.api.ads.adwords.axis.v201506.cm.BiddingStrategyConfiguration;
import com.google.api.ads.adwords.axis.v201506.cm.Bids;
import com.google.api.ads.adwords.axis.v201506.cm.CpcBid;
import com.google.api.ads.adwords.axis.v201506.cm.Criterion;
import com.google.api.ads.adwords.axis.v201506.cm.Money;
import com.google.api.ads.adwords.axis.v201506.cm.Operator;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.client.auth.oauth2.Credential;

/**
 * This example updates the bid of a keyword. To add a keyword, run
 * AddKeywords.java.
 *
 * <p>Credentials and properties in {@code fromFile()} are pulled from the
 * "ads.properties" file. See README for more info.
 */
public class UpdateKeyword {

  public static void main(String[] args) throws Exception {
    // Generate a refreshable OAuth2 credential.
    Credential oAuth2Credential = new OfflineCredentials.Builder()
        .forApi(Api.ADWORDS)
        .fromFile()
        .build()
        .generateCredential();

    // Construct an AdWordsSession.
    AdWordsSession session = new AdWordsSession.Builder()
        .fromFile()
        .withOAuth2Credential(oAuth2Credential)
        .build();

    long adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
    long keywordId = Long.parseLong("INSERT_KEYWORD_ID_HERE");

    AdWordsServices adWordsServices = new AdWordsServices();

    runExample(adWordsServices, session, adGroupId, keywordId);
  }

  public static void runExample(
      AdWordsServices adWordsServices, AdWordsSession session, Long adGroupId, Long keywordId)
      throws Exception {
    // Get the AdGroupCriterionService.
    AdGroupCriterionServiceInterface adGroupCriterionService =
        adWordsServices.get(session, AdGroupCriterionServiceInterface.class);

    // Create ad group criterion with updated bid.
    Criterion criterion = new Criterion();
    criterion.setId(keywordId);

    BiddableAdGroupCriterion biddableAdGroupCriterion = new BiddableAdGroupCriterion();
    biddableAdGroupCriterion.setAdGroupId(adGroupId);
    biddableAdGroupCriterion.setCriterion(criterion);

    // Create bids.
    BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();
    CpcBid bid = new CpcBid();
    bid.setBid(new Money(null, 10000000L));
    biddingStrategyConfiguration.setBids(new Bids[] {bid});
    biddableAdGroupCriterion.setBiddingStrategyConfiguration(biddingStrategyConfiguration);

    // Create operations.
    AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
    operation.setOperand(biddableAdGroupCriterion);
    operation.setOperator(Operator.SET);

    AdGroupCriterionOperation[] operations = new AdGroupCriterionOperation[] {operation};

    // Update ad group criteria.
    AdGroupCriterionReturnValue result = adGroupCriterionService.mutate(operations);

    // Display ad group criteria.
    for (AdGroupCriterion adGroupCriterionResult : result.getValue()) {
      if (adGroupCriterionResult instanceof BiddableAdGroupCriterion) {
        biddableAdGroupCriterion = (BiddableAdGroupCriterion) adGroupCriterionResult;
        System.out.printf("Ad group criterion with ad group ID %d, criterion ID %d, type "
            + "'%s', and bid %d was updated.%n", biddableAdGroupCriterion.getAdGroupId(),
            biddableAdGroupCriterion.getCriterion().getId(),
            biddableAdGroupCriterion.getCriterion().getCriterionType(),
            ((CpcBid) biddableAdGroupCriterion.getBiddingStrategyConfiguration()
                .getBids()[0]).getBid().getMicroAmount());
      }
    }
  }
}


text:
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.

using System;
using System.Runtime.CompilerServices;

[assembly: CLSCompliant(true)]

[assembly: InternalsVisibleTo("Narvalo.Facts")]


text:
package me.onenrico.holoblock.events;

import java.util.List;

import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.scheduler.BukkitRunnable;

import me.onenrico.holoblock.api.HoloBlockAPI;
import me.onenrico.holoblock.config.ConfigPlugin;
import me.onenrico.holoblock.database.Datamanager;
import me.onenrico.holoblock.main.Core;
import me.onenrico.holoblock.nms.sound.SoundManager;
import me.onenrico.holoblock.object.HoloData;
import me.onenrico.holoblock.object.Seriloc;
import me.onenrico.holoblock.utils.MessageUT;
import me.onenrico.holoblock.utils.ParticleUT;
import me.onenrico.holoblock.utils.PlaceholderUT;

public class BreakEvent implements Listener {

	@SuppressWarnings("deprecation")
	@EventHandler(priority = EventPriority.HIGHEST)
	public void playerBreak(final BlockBreakEvent event) {
		Player player = event.getPlayer();
		if (Core.getThis().w_hook.wg != null) {
			Block block = event.getBlock();
			Boolean override = Core.getThis().configplugin.getBool("worldguard-override", false);
			if (Core.getThis().w_hook.isAllowBuild(block.getLocation()).equals("true")) {
				event.setCancelled(false);
			} else if (Core.getThis().w_hook.isAllowBuild(block.getLocation()).equals("null")) {
				if (override) {
					MessageUT.plmessage(player, ConfigPlugin.locale.getValue("not_permitted"));
					SoundManager.playSound(player, "BLOCK_NOTE_PLING");
					event.setCancelled(true);
				}
			} else {
				if (override) {
					MessageUT.plmessage(player, ConfigPlugin.locale.getValue("not_permitted"));
					SoundManager.playSound(player, "BLOCK_NOTE_PLING");
					event.setCancelled(true);
				}
			}
		}
		if (event.isCancelled()) {
			event.setCancelled(true);
			return;
		}
		Location loc = event.getBlock().getLocation();
		if (loc.getBlock().getType().equals(Material.SKULL)) {
			String rawloc = Seriloc.Serialize(loc);
			HoloData data = Datamanager.getDataByLoc(rawloc);
			if (data == null) {
				return;
			}
			String playern = data.getOwner();
			if (playern == null) {
				return;
			}
			List<String> msg = ConfigPlugin.locale.getValue("not_permitted");
			List<String> msg2 = ConfigPlugin.locale.getValue("remove_holo");
			loc = Seriloc.centered(loc);
			if (!player.hasPermission("holoblock.admin")) {
				if (!player.getName().equals(playern)) {
					MessageUT.plmessage(player, msg, true);
					ParticleUT.send(player, "CLOUD", loc, 0.05f, 0.5f, 0.05f, 0.08f, 25, true);
					SoundManager.playSound(player, "ENTITY_BLAZE_DEATH", loc);
					event.setCancelled(true);
					return;
				}
			}
			event.setCancelled(true);
			event.getBlock().setType(Material.AIR);
			event.getBlock().getState().update(true);
			loc.getWorld().dropItemNaturally(loc.add(0, .5d, 0), Core.getAPI().getHoloItem());
			ParticleUT.send(player, "FLAME", loc, 0.01f, 1f, 0.01f, 0.08f, 25, true);
			SoundManager.playSound(player, "BLOCK_ANVIL_USE", loc);
			Location scopeloc = loc;
			OfflinePlayer ofc = Bukkit.getOfflinePlayer(data.getOwner());
			Datamanager.deleteHolo(data, new BukkitRunnable() {
				@Override
				public void run() {
					int maxholo = HoloBlockAPI.getMaxOwned(ofc, scopeloc.getWorld());
					int holocount = Datamanager.getDB().getOwned(data.getOwner());
					PlaceholderUT pu = new PlaceholderUT();
					pu.add("holocount", "" + holocount);
					pu.add("maxholo", "" + maxholo);
					MessageUT.plmessage(player, pu.t(msg2));
				}
			});
		}
	}
}


text:
#include "joynr/UdsClient.h"

#include <string>

#include <unistd.h>

#include <boost/filesystem.hpp>

#include "joynr/Util.h"

#include "UdsFrameBufferV1.h"
#include "UdsSendQueue.h"

namespace joynr
{

constexpr int UdsClient::_threadsPerConnection;

UdsClient::UdsClient(
        const UdsSettings& settings,
        const std::function<void(const exceptions::JoynrRuntimeException&)>& onFatalRuntimeError)
        : IUdsSender(),
          _fatalRuntimeErrorCallback{onFatalRuntimeError},
          _connectedCallback{[]() {}},
          _disconnectedCallback{[]() {}},
          _receivedCallback{[](smrf::ByteVector&&) {}},
          _address{settings.createClientMessagingAddress()},
          _connectSleepTime{settings.getConnectSleepTimeMs()},
          _sendQueue(
                  std::make_unique<UdsSendQueue<UdsFrameBufferV1>>(settings.getSendingQueueSize())),
          _readBuffer(std::make_unique<UdsFrameBufferV1>()),
          _endpoint(settings.getSocketPath()),
          _ioContext(_threadsPerConnection),
          _socket(_ioContext),
          _state{State::STOP},
          _asyncShutdownMutex(),
          _socketMutex(),
          _worker()
{
    try {
        _sendQueue->pushBack(UdsFrameBufferV1(_address));
    } catch (const std::exception& e) {
        doHandleFatalError("Failed to insert INIT message to queue.", e);
    }
}

UdsClient::~UdsClient()
{
    shutdown();
}

joynr::system::RoutingTypes::UdsClientAddress UdsClient::getAddress() const noexcept
{
    return _address;
}

void UdsClient::setConnectCallback(const Connected& callback)
{
    if (callback) {
        _connectedCallback = callback;
    }
}

void UdsClient::setDisconnectCallback(const Disconnected& callback)
{
    if (callback) {
        _disconnectedCallback = callback;
    }
}

void UdsClient::setReceiveCallback(const Received& callback)
{
    if (callback) {
        _receivedCallback = callback;
    }
}

void UdsClient::start()
{
    if (_worker.valid()) {
        JOYNR_LOG_ERROR(logger(), "{} alreay started.", _address.getId());
        return;
    }
    _state.store(State::START);
    _worker = std::async(&UdsClient::run, this);
}

void UdsClient::shutdown() noexcept
{
    std::lock_guard<std::mutex> lockStop(_asyncShutdownMutex);
    _state.store(State::STOP);
    try {
        _ioContext.stop();
        if (_worker.valid()) {
            _worker.get();
        }
    } catch (std::exception& e) {
        JOYNR_LOG_ERROR(logger(),
                        "{} caused unexpected error when stopping worker: {}",
                        _address.getId(),
                        e.what());
    } catch (...) {
        JOYNR_LOG_ERROR(logger(), "{} caused unknown error when stopping worker", _address.getId());
    }
}

void UdsClient::run()
{
    bool isRetry = false;
    while (State::START == _state.load()) {
        if (isRetry) {
            // Wait before retry connection so that worker does not block everything
            std::this_thread::sleep_for(_connectSleepTime);
            _ioContext.reset();
        }
        isRetry = true;
        std::unique_lock<std::mutex> socketLock(_socketMutex);
        _socket.async_connect(_endpoint, [this](boost::system::error_code failedToConnect) {
            if (failedToConnect) {
                JOYNR_LOG_ERROR(logger(),
                                "{} ({}) failed to connect. Retry in {:d}ms.",
                                _address.getId(),
                                _endpoint.path(),
                                _connectSleepTime.count());
                abortOnSocketConfigurationError();
            } else {
                if (State::START == _state.exchange(State::CONNECTED)) {
                    try {
                        _connectedCallback();
                    } catch (const std::exception& e) {
                        doHandleFatalError("Error from connect callback", e);
                    }
                    _ioContext.post([this]() {
                        // Send messages currently in the queue, which contains at least the initial
                        // message
                        doWrite();
                    });
                    doReadHeader();
                }
            }
        });
        socketLock.unlock();

        _ioContext.run();

        socketLock.lock();
        boost::system::error_code ignore;
        _socket.shutdown(boost::asio::socket_base::shutdown_both, ignore);
        _socket.close(ignore);
    }
    if (State::CONNECTED == _state.load()) {
        doHandleFatalError("State machine stopped unexpectedly");
    }
    try {
        _disconnectedCallback();
    } catch (const std::exception& e) {
        doHandleFatalError("Failed to process disconnection", e);
    }
}

void UdsClient::abortOnSocketConfigurationError() noexcept
{
    namespace fs = boost::filesystem;
    try {
        auto socketPath = fs::absolute(fs::path(_endpoint.path()));
        auto socketDir = socketPath.parent_path();

        if (0 != access(socketDir.string().c_str(), R_OK)) {
            doHandleFatalError("Socket path directory does not exist, or is not readable: " +
                               socketDir.string());
        } else if (fs::is_regular_file(socketPath) &&
                   (0 != access(socketPath.string().c_str(), R_OK | W_OK))) {
            doHandleFatalError("Socket path exists, but is not readable or not writable: " +
                               socketPath.string());
        }
    } catch (const fs::filesystem_error& e) {
        doHandleFatalError("Invalid socket path configuration.", e);
    } catch (const std::exception& e) {
        doHandleFatalError("Failed to process socket path configuration", e);
    }
}

void UdsClient::doReadHeader() noexcept
{
    std::unique_lock<std::mutex> socketLock(_socketMutex);
    boost::asio::async_read(_socket,
                            _readBuffer->header(),
                            [this](boost::system::error_code readFailure, std::size_t /*length*/) {
                                if (readFailure) {
                                    JOYNR_LOG_ERROR(logger(),
                                                    "{} failed to read header: {}",
                                                    _address.getId(),
                                                    readFailure.message());
                                } else {
                                    doReadBody();
                                }
                            });
}

void UdsClient::doReadBody() noexcept
{
    try {
        std::unique_lock<std::mutex> socketLock(_socketMutex);
        boost::asio::async_read(
                _socket,
                _readBuffer->body(),
                [this](boost::system::error_code readFailure, std::size_t /*length*/) {
                    if (readFailure) {
                        JOYNR_LOG_ERROR(logger(),
                                        "{} failed to read body: {}",
                                        _address.getId(),
                                        readFailure.message());
                    } else {
                        try {
                            _receivedCallback(_readBuffer->readMessage());
                            doReadHeader();
                        } catch (const std::exception& e) {
                            doHandleFatalError("Failed to process message-frame", e);
                        }
                    }
                });
    } catch (const std::exception& e) {
        doHandleFatalError("Failed to read message-frame", e);
    }
}

void UdsClient::send(const smrf::ByteArrayView& msg, const IUdsSender::SendFailed& callback)
{
    try {
        _ioContext.post([this, frame = UdsFrameBufferV1(msg), callback]() mutable {
            try {
                if (_sendQueue->pushBack(std::move(frame), callback)) {
                    doWrite();
                }
            } catch (const std::exception& e) {
                doHandleFatalError("Failed to queue message", e);
            }
        });
    } catch (const std::exception& e) {
        doHandleFatalError("Failed to create message frame", e);
    }
}

void UdsClient::doWrite() noexcept
{
    std::unique_lock<std::mutex> socketLock(_socketMutex);
    boost::asio::async_write(_socket,
                             _sendQueue->showFront(),
                             [this](boost::system::error_code writeFailed, std::size_t /*length*/) {
                                 if (_sendQueue->popFrontOnSuccess(writeFailed)) {
                                     doWrite();
                                 }
                             });
}

void UdsClient::doHandleFatalError(const std::string& errorMessage,
                                   const std::exception& error) noexcept
{
    doHandleFatalError(errorMessage + " - " + error.what());
}

void UdsClient::doHandleFatalError(const std::string& errorMessage) noexcept
{
    JOYNR_LOG_FATAL(logger(),
                    "{} fatal runtime error, stopping all communication permanently: {}",
                    _address.getId(),
                    errorMessage);
    if (!hasFatalErrorAlreadyBeenReported()) {
        try {
            if (_fatalRuntimeErrorCallback) {
                _fatalRuntimeErrorCallback(exceptions::JoynrRuntimeException(errorMessage));
            }
        } catch (std::exception& e) {
            JOYNR_LOG_ERROR(logger(),
                            "{} received unexpected exception when informing user about "
                            "internal fatal runtime error: {}",
                            _address.getId(),
                            e.what());
        } catch (...) {
            JOYNR_LOG_ERROR(logger(),
                            "{} received an unkown error when informing user about "
                            "internal fatal runtime error.",
                            _address.getId());
        }
        boost::system::error_code ignore;
        std::unique_lock<std::mutex> socketLock(_socketMutex);
        _socket.shutdown(boost::asio::socket_base::shutdown_both, ignore);
        _socket.close(ignore);
    }
}

bool UdsClient::hasFatalErrorAlreadyBeenReported() noexcept
{
    const auto previous = _state.exchange(State::FAILED);
    switch (previous) {
    case State::FAILED:
        // This call is a follow-up of previously reported error
        return true;
    case State::STOP:
        // In case of shutdown, don't report a connection problem as error
        return true;
    case State::CONNECTED:
    case State::START:
        break;
    }
    return false;
}

} // namespace joynr


text:
/**
 *
 * @author Fernando Gómez Herrera
 */

public class Perro extends Animal {

    public Perro(String comida, int hambre) {
        super(comida, hambre);
    }

    @Override
    public void hablar() {
        System.out.println("El perro ladra!! ggrrrrgrrgrr");
    }

    public void ladrar() {
        System.out.println("whoof whoof");
    }

    @Override
    public void dormir() {
        System.out.println("El perro está ");
        super.dormir();
    }

    @Override
    public String toString() {
        return "Un perro con estas características:\n" + super.toString();
    }
}


text:
package com.facebook.buck.io.watchman;

import com.facebook.buck.core.util.immutables.BuckStyleValue;
import java.nio.file.Path;

/** Buck sends this event for every file that was added, modified or deleted */
@BuckStyleValue
public abstract class WatchmanPathEvent implements WatchmanEvent {

  @Override
  public abstract Path getCellPath();

  /** The kind of event that occurred. */
  public abstract WatchmanEvent.Kind getKind();

  /**
   * Relative path of the actual file the event is about. The path is relative to the cell path
   * returned by {@link #getCellPath()}.
   */
  public abstract Path getPath();
}


text:
<?php
/* @var $this TicketTicketController */
/* @var $model TicketTicket */

$this->breadcrumbs=array(
	'Ticket Tickets'=>array('index'),
	'Manage',
);

$this->menu=array(
	array('label'=>'List TicketTicket', 'url'=>array('index')),
	array('label'=>'Create TicketTicket', 'url'=>array('create')),
);

Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
	$('.search-form').toggle();
	return false;
});
$('.search-form form').submit(function(){
	$('#ticket-ticket-grid').yiiGridView('update', {
		data: $(this).serialize()
	});
	return false;
});
");
?>

Manage Ticket Tickets

You may optionally enter a comparison operator (<, <=, >, >=, <>
or =) at the beginning of each of your search values to specify how the comparison should be done.

<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>

<?php $this->renderPartial('_search',array(
	'model'=>$model,
)); ?>

<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'ticket-ticket-grid',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'columns'=>array(
		'id',
		'subject',
		'description',
		'from_user_id',
		'responsible_user_id',
		'type_id',
		/*
		'status_id',
		*/
		array(
			'class'=>'CButtonColumn',
		),
	),
)); ?>


text:
	local suite = test.declare("vs2010_vc_vectorextensions")
	local m = premake.vstudio.vc2010

	local wks, prj

	function suite.setup()
		premake.action.set("vs2010")
		wks, prj = test.createWorkspace()
	end

	local function prepare()
		local cfg = test.getconfig(prj, "Debug")
		m.enableEnhancedInstructionSet(cfg)
	end

	function suite.instructionSet_onNotSet()
		test.isemptycapture()
	end

	function suite.instructionSet_onIA32_onVS2010()
		vectorextensions "IA32"
		prepare()
		test.isemptycapture()
	end

	function suite.instructionSet_onIA32()
		premake.action.set("vs2012")
		vectorextensions "IA32"
		prepare()
		test.capture [[
<EnableEnhancedInstructionSet>NoExtensions</EnableEnhancedInstructionSet>
		]]
	end

	function suite.instructionSet_onSSE()
		vectorextensions "SSE"
		prepare()
		test.capture [[
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
		]]
	end

	function suite.instructionSet_onSSE2()
		vectorextensions "SSE2"
		prepare()
		test.capture [[
<EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
		]]
	end

	function suite.instructionSet_onAVX()
		premake.action.set("vs2013")
		vectorextensions "AVX"
		prepare()
		test.capture [[
<EnableEnhancedInstructionSet>AdvancedVectorExtensions</EnableEnhancedInstructionSet>
		]]
	end

	function suite.instructionSet_onAVX_onVS2010()
		vectorextensions "AVX"
		prepare()
		test.isemptycapture()
	end

	function suite.instructionSet_onAVX2()
		premake.action.set("vs2013")
		vectorextensions "AVX2"
		prepare()
		test.capture [[
<EnableEnhancedInstructionSet>AdvancedVectorExtensions2</EnableEnhancedInstructionSet>
		]]
	end

	function suite.instructionSet_onAVX2_onVS2012()
		premake.action.set("vs2012")
		vectorextensions "AVX2"
		prepare()
		test.isemptycapture()
	end


text:
using PaderbornUniversity.SILab.Hip.DataStore.Model.Events;
using PaderbornUniversity.SILab.Hip.DataStore.Model.Rest;
using PaderbornUniversity.SILab.Hip.EventSourcing;
using PaderbornUniversity.SILab.Hip.EventSourcing.Events;
using PaderbornUniversity.SILab.Hip.EventSourcing.Migrations;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace PaderbornUniversity.SILab.Hip.DataStore.Migrations
{
    [StreamMigration(from: 9, to: 10)]
    public class Migration10PropertyChanged : IStreamMigration
    {
        private Dictionary<(ResourceType, int), object> argumentDictionary = new Dictionary<(ResourceType, int), object>();

        public async Task MigrateAsync(IStreamMigrationArgs e)
        {
            var events = e.GetExistingEvents();
            DateTimeOffset timestamp = new DateTimeOffset();
            while (await events.MoveNextAsync())
            {
                var currentEvent = events.Current;
                IEnumerable<PropertyChangedEvent> propEvents = new List<PropertyChangedEvent>();
                if (currentEvent is UserActivityBaseEvent userEvent)
                {
                    switch (currentEvent)
                    {
                        case ExhibitCreated ev:
                            var emptyExhibitArgs = new ExhibitArgs();
                            e.AppendEvent(new CreatedEvent(ev.GetEntityType().Name, ev.Id, ev.UserId)
                            {
                                Timestamp = ev.Timestamp
                            });
                            propEvents = EntityManager.CompareEntities(emptyExhibitArgs, ev.Properties, ev.GetEntityType(), ev.Id, ev.UserId);
                            argumentDictionary[(ev.GetEntityType(), ev.Id)] = ev.Properties;
                            timestamp = ev.Timestamp;
                            break;

                        case ExhibitPageCreated3 ev:
                            var emptyPageArgs = new ExhibitPageArgs2();
                            e.AppendEvent(new CreatedEvent(ev.GetEntityType().Name, ev.Id, ev.UserId)
                            {
                                Timestamp = ev.Timestamp
                            });
                            propEvents = EntityManager.CompareEntities(emptyPageArgs, ev.Properties, ev.GetEntityType(), ev.Id, ev.UserId);
                            argumentDictionary[(ev.GetEntityType(), ev.Id)] = ev.Properties;
                            timestamp = ev.Timestamp;
                            break;

                        case MediaCreated ev:
                            var emptyMediaArgs = new MediaArgs();
                            e.AppendEvent(new CreatedEvent(ev.GetEntityType().Name, ev.Id, ev.UserId)
                            {
                                Timestamp = ev.Timestamp
                            });
                            propEvents = EntityManager.CompareEntities(emptyMediaArgs, ev.Properties, ev.GetEntityType(), ev.Id, ev.UserId);
                            argumentDictionary[(ev.GetEntityType(), ev.Id)] = ev.Properties;
                            timestamp = ev.Timestamp;
                            break;

                        case RouteCreated ev:
                            var emptyRouteArgs = new RouteArgs();
                            e.AppendEvent(new CreatedEvent(ev.GetEntityType().Name, ev.Id, ev.UserId)
                            {
                                Timestamp = ev.Timestamp
                            });
                            propEvents = EntityManager.CompareEntities(emptyRouteArgs, ev.Properties, ev.GetEntityType(), ev.Id, ev.UserId);
                            argumentDictionary[(ev.GetEntityType(), ev.Id)] = ev.Properties;
                            timestamp = ev.Timestamp;
                            break;

                        case TagCreated ev:
                            var emptyTagArgs = new TagArgs();
                            e.AppendEvent(new CreatedEvent(ev.GetEntityType().Name, ev.Id, ev.UserId)
                            {
                                Timestamp = ev.Timestamp
                            });
                            propEvents = EntityManager.CompareEntities(emptyTagArgs, ev.Properties, ev.GetEntityType(), ev.Id, ev.UserId);
                            argumentDictionary[(ev.GetEntityType(), ev.Id)] = ev.Properties;
                            timestamp = ev.Timestamp;
                            break;

                        case ExhibitUpdated ev:
                            timestamp = ev.Timestamp;
                            var newArgs = ev.Properties;
                            var currentArgs = (ExhibitArgs)argumentDictionary[(ev.GetEntityType(), ev.Id)];
                            propEvents = EntityManager.CompareEntities(currentArgs, newArgs, ev.GetEntityType(), ev.Id, ev.UserId);
                            argumentDictionary[(ev.GetEntityType(), ev.Id)] = ev.Properties;
                            break;

                        case ExhibitPageUpdated3 ev:
                            timestamp = ev.Timestamp;
                            var newPageArgs = ev.Properties;
                            var currentPageArgs = (ExhibitPageArgs2)argumentDictionary[(ev.GetEntityType(), ev.Id)];
                            propEvents = EntityManager.CompareEntities(currentPageArgs, newPageArgs, ev.GetEntityType(), ev.Id, ev.UserId);
                            argumentDictionary[(ev.GetEntityType(), ev.Id)] = ev.Properties;
                            break;

                        case RouteUpdated ev:
                            timestamp = ev.Timestamp;
                            var newRouteArgs = ev.Properties;
                            var currentRouteArgs = (RouteArgs)argumentDictionary[(ev.GetEntityType(), ev.Id)];
                            propEvents = EntityManager.CompareEntities(currentRouteArgs, newRouteArgs, ev.GetEntityType(), ev.Id, ev.UserId);
                            argumentDictionary[(ev.GetEntityType(), ev.Id)] = ev.Properties;
                            break;

                        case TagUpdated ev:
                            timestamp = ev.Timestamp;
                            var newTagArgs = ev.Properties;
                            var currentTagArgs = (TagArgs)argumentDictionary[(ev.GetEntityType(), ev.Id)];
                            propEvents = EntityManager.CompareEntities(currentTagArgs, newTagArgs, ev.GetEntityType(), ev.Id, ev.UserId);
                            argumentDictionary[(ev.GetEntityType(), ev.Id)] = ev.Properties;
                            break;

                        case MediaUpdate ev:
                            timestamp = ev.Timestamp;
                            var newMediaArgs = ev.Properties;
                            var currentMediaArgs = (MediaArgs)argumentDictionary[(ev.GetEntityType(), ev.Id)];
                            propEvents = EntityManager.CompareEntities(currentMediaArgs, newMediaArgs, ev.GetEntityType(), ev.Id, ev.UserId);
                            argumentDictionary[(ev.GetEntityType(), ev.Id)] = ev.Properties;
                            break;

                        case IDeleteEvent ev:
                            e.AppendEvent(new DeletedEvent(ev.GetEntityType().Name, ev.Id, userEvent.UserId)
                            {
                                Timestamp = ev.Timestamp
                            });
                            break;

                        default:
                            //append all other events
                            e.AppendEvent(events.Current);
                            break;
                    }

                    foreach (var propEvent in propEvents)
                    {
                        propEvent.Timestamp = timestamp;
                        e.AppendEvent(propEvent);
                    }
                }
                else
                {
                    e.AppendEvent(events.Current);
                }

            }

        }
    }
}


text:
$("document").ready(function(){
$("#slideshow").cycle()
});


text:
var client;
var connected = false;
const ReconnectableWebSocket = require('reconnectable-websocket');
self.onClientMessage = function (data) {
  postMessage(data.data);
};

self.sendClientMessage = function (data) {
  if (connected) {
    client.send(JSON.stringify(data));
  }
};

onmessage = function (event) {
  const data = event.data;
  console.log('worker', data);
  if (data.type === 'connect') {
    client = new ReconnectableWebSocket(data.payload.url);
    client.open();
    console.log('websocket', client);
    connected = true;
    client.onmessage = self.onClientMessage;
    client.onopen = self.onClientMessage;
  } else if (data.type === 'test') {
    console.log('test');
  } else {
    self.sendClientMessage(data.payload);
  }
};


text:
import { denormalize, normalize, schema } from '../';

describe('normalize', () => {
  [42, null, undefined, '42', () => {}].forEach((input) => {
    test(`cannot normalize input that == ${input}`, () => {
      expect(() => normalize(input, new schema.Entity('test'))).toThrow();
    });
  });

  test('cannot normalize without a schema', () => {
    expect(() => normalize({})).toThrow();
  });

  test('cannot normalize with null input', () => {
    const mySchema = new schema.Entity('tacos');
    expect(() => normalize(null, mySchema)).toThrow(/null/);
  });

  test('normalizes entities', () => {
    const mySchema = new schema.Entity('tacos');

    expect(
      normalize(
        [
          { id: 1, type: 'foo' },
          { id: 2, type: 'bar' },
        ],
        [mySchema]
      )
    ).toMatchSnapshot();
  });

  test('normalizes entities with circular references', () => {
    const user = new schema.Entity('users');
    user.define({
      friends: [user],
    });

    const input = { id: 123, friends: [] };
    input.friends.push(input);

    expect(normalize(input, user)).toMatchSnapshot();
  });

  test('normalizes nested entities', () => {
    const user = new schema.Entity('users');
    const comment = new schema.Entity('comments', {
      user: user,
    });
    const article = new schema.Entity('articles', {
      author: user,
      comments: [comment],
    });

    const input = {
      id: '123',
      title: 'A Great Article',
      author: {
        id: '8472',
        name: 'Paul',
      },
      body: 'This article is great.',
      comments: [
        {
          id: 'comment-123-4738',
          comment: 'I like it!',
          user: {
            id: '10293',
            name: 'Jane',
          },
        },
      ],
    };
    expect(normalize(input, article)).toMatchSnapshot();
  });

  test('does not modify the original input', () => {
    const user = new schema.Entity('users');
    const article = new schema.Entity('articles', { author: user });
    const input = Object.freeze({
      id: '123',
      title: 'A Great Article',
      author: Object.freeze({
        id: '8472',
        name: 'Paul',
      }),
    });
    expect(() => normalize(input, article)).not.toThrow();
  });

  test('ignores null values', () => {
    const myEntity = new schema.Entity('myentities');
    expect(normalize([null], [myEntity])).toMatchSnapshot();
    expect(normalize([undefined], [myEntity])).toMatchSnapshot();
    expect(normalize([false], [myEntity])).toMatchSnapshot();
  });

  test('can use fully custom entity classes', () => {
    class MyEntity extends schema.Entity {
      schema = {
        children: [new schema.Entity('children')],
      };

      getId(entity, parent, key) {
        return entity.uuid;
      }

      normalize(input, parent, key, visit, addEntity, visitedEntities) {
        const entity = { ...input };
        Object.keys(this.schema).forEach((key) => {
          const schema = this.schema[key];
          entity[key] = visit(input[key], input, key, schema, addEntity, visitedEntities);
        });
        addEntity(this, entity, parent, key);
        return {
          uuid: this.getId(entity),
          schema: this.key,
        };
      }
    }

    const mySchema = new MyEntity('food');
    expect(
      normalize(
        {
          uuid: '1234',
          name: 'tacos',
          children: [{ id: 4, name: 'lettuce' }],
        },
        mySchema
      )
    ).toMatchSnapshot();
  });

  test('uses the non-normalized input when getting the ID for an entity', () => {
    const userEntity = new schema.Entity('users');
    const idAttributeFn = jest.fn((nonNormalized, parent, key) => nonNormalized.user.id);
    const recommendation = new schema.Entity(
      'recommendations',
      { user: userEntity },
      {
        idAttribute: idAttributeFn,
      }
    );
    expect(normalize({ user: { id: '456' } }, recommendation)).toMatchSnapshot();
    expect(idAttributeFn.mock.calls).toMatchSnapshot();
    expect(recommendation.idAttribute).toBe(idAttributeFn);
  });

  test('passes over pre-normalized values', () => {
    const userEntity = new schema.Entity('users');
    const articleEntity = new schema.Entity('articles', { author: userEntity });

    expect(normalize({ id: '123', title: 'normalizr is great!', author: 1 }, articleEntity)).toMatchSnapshot();
  });

  test('can normalize object without proper object prototype inheritance', () => {
    const test = { id: 1, elements: [] };
    test.elements.push(
      Object.assign(Object.create(null), {
        id: 18,
        name: 'test',
      })
    );

    const testEntity = new schema.Entity('test', {
      elements: [new schema.Entity('elements')],
    });

    expect(() => normalize(test, testEntity)).not.toThrow();
  });

  test('can normalize entity nested inside entity using property from parent', () => {
    const linkablesSchema = new schema.Entity('linkables');
    const mediaSchema = new schema.Entity('media');
    const listsSchema = new schema.Entity('lists');

    const schemaMap = {
      media: mediaSchema,
      lists: listsSchema,
    };

    linkablesSchema.define({
      data: (parent) => schemaMap[parent.schema_type],
    });

    const input = {
      id: 1,
      module_type: 'article',
      schema_type: 'media',
      data: {
        id: 2,
        url: 'catimage.jpg',
      },
    };

    expect(normalize(input, linkablesSchema)).toMatchSnapshot();
  });

  test('can normalize entity nested inside object using property from parent', () => {
    const mediaSchema = new schema.Entity('media');
    const listsSchema = new schema.Entity('lists');

    const schemaMap = {
      media: mediaSchema,
      lists: listsSchema,
    };

    const linkablesSchema = {
      data: (parent) => schemaMap[parent.schema_type],
    };

    const input = {
      id: 1,
      module_type: 'article',
      schema_type: 'media',
      data: {
        id: 2,
        url: 'catimage.jpg',
      },
    };

    expect(normalize(input, linkablesSchema)).toMatchSnapshot();
  });
});

describe('denormalize', () => {
  test('cannot denormalize without a schema', () => {
    expect(() => denormalize({})).toThrow();
  });

  test('returns the input if undefined', () => {
    expect(denormalize(undefined, {}, {})).toBeUndefined();
  });

  test('denormalizes entities', () => {
    const mySchema = new schema.Entity('tacos');
    const entities = {
      tacos: {
        1: { id: 1, type: 'foo' },
        2: { id: 2, type: 'bar' },
      },
    };
    expect(denormalize([1, 2], [mySchema], entities)).toMatchSnapshot();
  });

  test('denormalizes nested entities', () => {
    const user = new schema.Entity('users');
    const comment = new schema.Entity('comments', {
      user: user,
    });
    const article = new schema.Entity('articles', {
      author: user,
      comments: [comment],
    });

    const entities = {
      articles: {
        123: {
          author: '8472',
          body: 'This article is great.',
          comments: ['comment-123-4738'],
          id: '123',
          title: 'A Great Article',
        },
      },
      comments: {
        'comment-123-4738': {
          comment: 'I like it!',
          id: 'comment-123-4738',
          user: '10293',
        },
      },
      users: {
        10293: {
          id: '10293',
          name: 'Jane',
        },
        8472: {
          id: '8472',
          name: 'Paul',
        },
      },
    };
    expect(denormalize('123', article, entities)).toMatchSnapshot();
  });

  test('set to undefined if schema key is not in entities', () => {
    const user = new schema.Entity('users');
    const comment = new schema.Entity('comments', {
      user: user,
    });
    const article = new schema.Entity('articles', {
      author: user,
      comments: [comment],
    });

    const entities = {
      articles: {
        123: {
          id: '123',
          author: '8472',
          comments: ['1'],
        },
      },
      comments: {
        1: {
          user: '123',
        },
      },
    };
    expect(denormalize('123', article, entities)).toMatchSnapshot();
  });

  test('does not modify the original entities', () => {
    const user = new schema.Entity('users');
    const article = new schema.Entity('articles', { author: user });
    const entities = Object.freeze({
      articles: Object.freeze({
        123: Object.freeze({
          id: '123',
          title: 'A Great Article',
          author: '8472',
        }),
      }),
      users: Object.freeze({
        8472: Object.freeze({
          id: '8472',
          name: 'Paul',
        }),
      }),
    });
    expect(() => denormalize('123', article, entities)).not.toThrow();
  });

  test('denormalizes with function as idAttribute', () => {
    const normalizedData = {
      entities: {
        patrons: {
          1: { id: '1', guest: null, name: 'Esther' },
          2: { id: '2', guest: 'guest-2-1', name: 'Tom' },
        },
        guests: { 'guest-2-1': { guest_id: 1 } },
      },
      result: ['1', '2'],
    };

    const guestSchema = new schema.Entity(
      'guests',
      {},
      {
        idAttribute: (value, parent, key) => `${key}-${parent.id}-${value.guest_id}`,
      }
    );

    const patronsSchema = new schema.Entity('patrons', {
      guest: guestSchema,
    });

    expect(denormalize(normalizedData.result, [patronsSchema], normalizedData.entities)).toMatchSnapshot();
  });
});


text:
import os
import datetime
import subprocess

import flask
import pytz
import jinja2.utils

from common import config
from common.utils import cache
from common.time import nice_duration
from www import login

def error_page(message):
	return flask.render_template("error.html", message=message, session=login.load_session(include_url=False))

def timestamp(ts, cls='timestamp', tag='span'):
	"""
	Outputs a given time (either unix timestamp or datetime instance) as a human-readable time
	and includes tags so that common.js will convert the time on page-load to the user's
	timezone and preferred date/time format.
	"""
	if isinstance(ts, (int, float)):
		ts = datetime.datetime.fromtimestamp(ts, tz=pytz.utc)
	elif ts.tzinfo is None:
		ts = ts.replace(tzinfo=datetime.timezone.utc)
	ts = ts.astimezone(config.config['timezone'])
	if cls == 'timestamp-duration':
		text = nice_duration(datetime.datetime.now(config.config['timezone']) - ts, 2)
	else:
		text = ts.strftime("%A, %d %B, %Y %H:%M:%S %Z")
	return flask.Markup("<{tag} class=\"{cls}\" data-timestamp=\"{timestamp}\">{text}</{tag}>".format(
		text=text,
		timestamp=ts.timestamp(),
		tag=tag,
		cls=cls,
	))

@cache(period=None, params=[0])
def static_url(filename):
	baseurl = flask.url_for("static", filename=filename)
	revision = subprocess.check_output([
		'git', 'log', '-n', '1', '--pretty=format:%h', '--',
		os.path.join('www', 'static', filename)]).decode()
	return "{}?_={}".format(baseurl, revision)

# Add a "last" to get the previous value returned, to complement the existing
# "current" prop which gets the upcoming value.
class CyclerExt(jinja2.utils.Cycler):
	@property
	def last(self):
		# self.pos is always positive or zero, so this will wrap cleanly
		return self.items[self.pos - 1]


text:
var app = angular.module("browseApp.sidebar", []);

app.controller("sidebar",function($scope, $state, $stateParams, $http, locationTracker, usergroupProvider){

      $scope.$watch( function() {return locationTracker.getLocation();},
      function(loct)
      {
            $scope.sidebar_backtrack = loct['sidebar_backtrack'];
            $scope.sidebar_onCatlist = loct['sidebar_onCatlist'];
            $scope.sidebar_title = loct['sidebar_title'];
            $scope.sidebar_text = loct['sidebar_text'];
      }, true);

      $scope.$watch( function() {return usergroupProvider.getviewingGroup();},
      function(role)
      {
            $scope.sidebar_level = role['viewingLevel'];

      }, true);

      $scope.goToState = function(name)
      {
            $state.go(name);
      };

      $scope.reloadPage = function(){window.location.reload();};

      $scope.joinCategory = function()
      {

            $http.get("join/cat/" + $stateParams.catID)
            .success(function(response)
            {

            });
      }

});


text:
package report.donut.gherkin.model;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Tag {

    @SerializedName("line")
    @Expose
    private Integer line;
    @SerializedName("name")
    @Expose
    private String name;

    public Tag(String name, int line) {
        this.name = name;
        this.line = line;
    }

    public Integer getLine() {
        return line;
    }

    public void setLine(Integer line) {
        this.line = line;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}


text:
describe('PUT /projects/:projectId/teams/:teamId', function() {
  beforeEach(function *() {
    yield fixtures.load(['users', 'projects', 'teams']);
    this.project = fixtures.projects[0];
    this.team = fixtures.teams[0];
    this.owner = fixtures.users[0];
    this.user = fixtures.users[1];
    this.admin = fixtures.users[2];
    yield fixtures.teams[0].addUsers(fixtures.users[1]);
    yield fixtures.teams[1].addUsers(fixtures.users[2]);
    yield fixtures.projects[0].addTeams(fixtures.teams[0], { permission: 'write' });
    yield fixtures.projects[0].addTeams(fixtures.teams[1], { permission: 'admin' });
  });

  it('should return Unauthorized when user is unauthorized', function *() {
    try {
      yield route.put(`/projects/${this.project.id}/teams/${this.team.id}`);
    } catch (err) {
      expect(err).to.be.an.error(HTTP_ERROR.Unauthorized);
    }
  });

  it('should return NoPermission if user is not owner or admin', function *() {
    try {
      yield route.put(`/projects/${this.project.id}/teams/${this.team.id}`, null, {
        auth: [this.user.email, this.user.password]
      });
    } catch (err) {
      expect(err).to.be.an.error(HTTP_ERROR.NoPermission);
    }
  });

  it('should return NotFound if team is not exists', function *() {
    try {
      yield route.put(`/projects/${this.project.id}/teams/123`, {
        permission: 'read'
      }, {
        auth: [this.admin.email, this.admin.password]
      });
    } catch (err) {
      expect(err).to.be.an.error(HTTP_ERROR.NotFound);
    }
  });

  it('should update permission successfully if user is owner', function *() {
    yield route.put(`/projects/${this.project.id}/teams/${this.team.id}`, {
      permission: 'read'
    }, {
      auth: [this.owner.email, this.owner.password]
    });
  });

  it('should return InvalidParameter if permission is invalid', function *() {
    var url = `/projects/${this.project.id}/teams/${this.team.id}`;
    try {
      yield route.put(url, null, {
        auth: [this.admin.email, this.admin.password]
      });
    } catch (err) {
      expect(err).to.be.an.error(HTTP_ERROR.InvalidParameter);
    }
    try {
      yield route.put(url, {
        permission: 'invalid'
      }, {
        auth: [this.admin.email, this.admin.password]
      });
    } catch (err) {
      expect(err).to.be.an.error(HTTP_ERROR.InvalidParameter);
    }
  });

  it('should update permission successfully and return the previous permission', function *() {
    var result = yield route.put(`/projects/${this.project.id}/teams/${this.team.id}`, {
      permission: 'read'
    }, {
      auth: [this.admin.email, this.admin.password]
    });
    expect(result.permissions.previous).to.eql('write');
    expect(result.permissions.current).to.eql('read');
  });

  it('should return null if team has no permission to the project', function *() {
    var result;
    result = yield route.put(`/projects/${this.project.id}/teams/${this.team.id}`, {
      permission: null
    }, {
      auth: [this.admin.email, this.admin.password]
    });
    expect(result.permissions.current).to.eql(null);

    result = yield route.put(`/projects/${this.project.id}/teams/${this.team.id}`, {
      permission: 'read'
    }, {
      auth: [this.admin.email, this.admin.password]
    });
    expect(result.permissions.previous).to.eql(null);
  });
});


text:
System.register(["angular2/core"], function(exports_1, context_1) {
    "use strict";
    var __moduleName = context_1 && context_1.id;
    var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    };
    var __metadata = (this && this.__metadata) || function (k, v) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
    };
    var core_1;
    var InputComponent;
    return {
        setters:[
            function (core_1_1) {
                core_1 = core_1_1;
            }],
        execute: function() {
            InputComponent = (function () {
                function InputComponent() {
                }
                InputComponent = __decorate([
                    core_1.Component({
                        selector: 'input_rename_component',
                        template: "\n
\n            Input\n
\n    "
                    }),
                    __metadata('design:paramtypes', [])
                ], InputComponent);
                return InputComponent;
            }());
            exports_1("InputComponent", InputComponent);
        }
    }
});
//# sourceMappingURL=input_rename.component.js.map


text:
from honeybadger.fake_connection import send_notice

from testfixtures import log_capture
import json

@log_capture()
def test_send_notice_logging(l):
    config = {'api_key': 'aaa'}
    payload = json.dumps({'test': 'payload'})

    send_notice(config, payload)

    l.check(
        ('honeybadger.fake_connection', 'INFO', 'Development mode is enabled; this error will be reported if it occurs after you deploy your app.'),
        ('honeybadger.fake_connection', 'DEBUG', 'The config used is {} with payload {}'.format(config, payload)))


text:
.. _kernel-samples:

Various Kernel and Scheduler Samples
####################################

.. toctree::
   :maxdepth: 1
   :glob:

   **/*


text:
[![Software License][ico-license]](LICENSE.md)
[![Build Status][ico-travis]][link-travis]
[![Coverage Status][ico-coverall]][link-coveralls]

Magento 2 content under version control.

## Install

* Add the repository to the repositories section of your composer.json file
```
 "repositories": [
    {
        "type": "vcs",
        "url": "git@github.com:GordonLesti/ContentVersion.git"
    }
 ],
```
* Require the module & install
```
 composer require lesti/module-content-version:dev-master
```

## Change log

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

## Testing

``` bash
$ composer test
```

## Contributing

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CONDUCT](CONDUCT.md) for details.

## Security

If you discover any security related issues, please email info@gordonlesti.com instead of using the issue tracker.

## Credits

- [Gordon Lesti][link-author]
- [All Contributors][link-contributors]

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

[ico-license]: https://img.shields.io/github/license/GordonLesti/ContentVersion.svg?style=flat-square
[ico-travis]: https://img.shields.io/travis/GordonLesti/ContentVersion/master.svg?style=flat-square
[ico-coverall]: https://img.shields.io/coveralls/GordonLesti/ContentVersion.svg?style=flat-square

[link-travis]: https://travis-ci.org/GordonLesti/ContentVersion
[link-coveralls]: https://coveralls.io/github/GordonLesti/ContentVersion
[link-author]: https://gordonlesti.com/
[link-contributors]: ../../contributors