text:
#include "surveyor.h"
#include "xsurveyor.h"

#include "../../nn.h"
#include "../../survey.h"

#include "../../aio/fsm.h"
#include "../../aio/timer.h"

#include "../../utils/err.h"
#include "../../utils/cont.h"
#include "../../utils/fast.h"
#include "../../utils/wire.h"
#include "../../utils/alloc.h"
#include "../../utils/random.h"
#include "../../utils/list.h"
#include "../../utils/attr.h"

#include <string.h>

#define NN_SURVEYOR_DEFAULT_DEADLINE 1000

#define NN_SURVEYOR_STATE_IDLE 1
#define NN_SURVEYOR_STATE_PASSIVE 2
#define NN_SURVEYOR_STATE_ACTIVE 3
#define NN_SURVEYOR_STATE_CANCELLING 4
#define NN_SURVEYOR_STATE_STOPPING_TIMER 5
#define NN_SURVEYOR_STATE_STOPPING 6

#define NN_SURVEYOR_ACTION_START 1
#define NN_SURVEYOR_ACTION_CANCEL 2

#define NN_SURVEYOR_SRC_DEADLINE_TIMER 1

#define NN_SURVEYOR_TIMEDOUT 1

struct nn_surveyor {

    /*  The underlying raw SP socket. */
    struct nn_xsurveyor xsurveyor;

    /*  The state machine. */
    struct nn_fsm fsm;
    int state;

    /*  Survey ID of the current survey. */
    uint32_t surveyid;

    /*  Timer for timing out the survey. */
    struct nn_timer timer;

    /*  When starting the survey, the message is temporarily stored here. */
    struct nn_msg tosend;

    /*  Protocol-specific socket options. */
    int deadline;

    /*  Flag if surveyor has timed out */
    int timedout;
};

/*  Private functions. */
static void nn_surveyor_init (struct nn_surveyor *self,
    const struct nn_sockbase_vfptr *vfptr, void *hint);
static void nn_surveyor_term (struct nn_surveyor *self);
static void nn_surveyor_handler (struct nn_fsm *self, int src, int type,
    void *srcptr);
static void nn_surveyor_shutdown (struct nn_fsm *self, int src, int type,
    void *srcptr);
static int nn_surveyor_inprogress (struct nn_surveyor *self);
static void nn_surveyor_resend (struct nn_surveyor *self);

/*  Implementation of nn_sockbase's virtual functions. */
static void nn_surveyor_stop (struct nn_sockbase *self);
static void nn_surveyor_destroy (struct nn_sockbase *self);
static int nn_surveyor_events (struct nn_sockbase *self);
static int nn_surveyor_send (struct nn_sockbase *self, struct nn_msg *msg);
static int nn_surveyor_recv (struct nn_sockbase *self, struct nn_msg *msg);
static int nn_surveyor_setopt (struct nn_sockbase *self, int level, int option,
    const void *optval, size_t optvallen);
static int nn_surveyor_getopt (struct nn_sockbase *self, int level, int option,
    void *optval, size_t *optvallen);
static const struct nn_sockbase_vfptr nn_surveyor_sockbase_vfptr = {
    nn_surveyor_stop,
    nn_surveyor_destroy,
    nn_xsurveyor_add,
    nn_xsurveyor_rm,
    nn_xsurveyor_in,
    nn_xsurveyor_out,
    nn_surveyor_events,
    nn_surveyor_send,
    nn_surveyor_recv,
    nn_surveyor_setopt,
    nn_surveyor_getopt
};

static void nn_surveyor_init (struct nn_surveyor *self,
    const struct nn_sockbase_vfptr *vfptr, void *hint)
{
    nn_xsurveyor_init (&self->xsurveyor, vfptr, hint);
    nn_fsm_init_root (&self->fsm, nn_surveyor_handler, nn_surveyor_shutdown,
        nn_sockbase_getctx (&self->xsurveyor.sockbase));
    self->state = NN_SURVEYOR_STATE_IDLE;

    /*  Start assigning survey IDs beginning with a random number. This way
        there should be no key clashes even if the executable is re-started. */
    nn_random_generate (&self->surveyid, sizeof (self->surveyid));

    nn_timer_init (&self->timer, NN_SURVEYOR_SRC_DEADLINE_TIMER, &self->fsm);
    nn_msg_init (&self->tosend, 0);
    self->deadline = NN_SURVEYOR_DEFAULT_DEADLINE;
    self->timedout = 0;

    /*  Start the state machine. */
    nn_fsm_start (&self->fsm);
}

static void nn_surveyor_term (struct nn_surveyor *self)
{
    nn_msg_term (&self->tosend);
    nn_timer_term (&self->timer);
    nn_fsm_term (&self->fsm);
    nn_xsurveyor_term (&self->xsurveyor);
}

void nn_surveyor_stop (struct nn_sockbase *self)
{
    struct nn_surveyor *surveyor;

    surveyor = nn_cont (self, struct nn_surveyor, xsurveyor.sockbase);

    nn_fsm_stop (&surveyor->fsm);
}

void nn_surveyor_destroy (struct nn_sockbase *self)
{
    struct nn_surveyor *surveyor;

    surveyor = nn_cont (self, struct nn_surveyor, xsurveyor.sockbase);

    nn_surveyor_term (surveyor);
    nn_free (surveyor);
}

static int nn_surveyor_inprogress (struct nn_surveyor *self)
{
    /*  Return 1 if there's a survey going on. 0 otherwise. */
    return self->state == NN_SURVEYOR_STATE_IDLE ||
        self->state == NN_SURVEYOR_STATE_PASSIVE ||
        self->state == NN_SURVEYOR_STATE_STOPPING ? 0 : 1;
}

static int nn_surveyor_events (struct nn_sockbase *self)
{
    int rc;
    struct nn_surveyor *surveyor;

    surveyor = nn_cont (self, struct nn_surveyor, xsurveyor.sockbase);

    /*  Determine the actual readability/writability of the socket. */
    rc = nn_xsurveyor_events (&surveyor->xsurveyor.sockbase);

    /*  If there's no survey going on we'll signal IN to interrupt polling
        when the survey expires. nn_recv() will return -EFSM afterwards. */
    if (!nn_surveyor_inprogress (surveyor))
        rc |= NN_SOCKBASE_EVENT_IN;

    return rc;
}

static int nn_surveyor_send (struct nn_sockbase *self, struct nn_msg *msg)
{
    struct nn_surveyor *surveyor;

    surveyor = nn_cont (self, struct nn_surveyor, xsurveyor.sockbase);

    /*  Generate new survey ID. */
    ++surveyor->surveyid;
    surveyor->surveyid |= 0x80000000;

    /*  Tag the survey body with survey ID. */
    nn_assert (nn_chunkref_size (&msg->sphdr) == 0);
    nn_chunkref_term (&msg->sphdr);
    nn_chunkref_init (&msg->sphdr, 4);
    nn_putl (nn_chunkref_data (&msg->sphdr), surveyor->surveyid);

    /*  Store the survey, so that it can be sent later on. */
    nn_msg_term (&surveyor->tosend);
    nn_msg_mv (&surveyor->tosend, msg);
    nn_msg_init (msg, 0);

    /*  Cancel any ongoing survey, if any. */
    if (nn_slow (nn_surveyor_inprogress (surveyor))) {

        /*  First check whether the survey can be sent at all. */
        if (!(nn_xsurveyor_events (&surveyor->xsurveyor.sockbase) &
              NN_SOCKBASE_EVENT_OUT))
            return -EAGAIN;

        /*  Cancel the current survey. */
        nn_fsm_action (&surveyor->fsm, NN_SURVEYOR_ACTION_CANCEL);

        return 0;
    }

    /*  Notify the state machine that the survey was started. */
    nn_fsm_action (&surveyor->fsm, NN_SURVEYOR_ACTION_START);

    return 0;
}

static int nn_surveyor_recv (struct nn_sockbase *self, struct nn_msg *msg)
{
    int rc;
    struct nn_surveyor *surveyor;
    uint32_t surveyid;

    surveyor = nn_cont (self, struct nn_surveyor, xsurveyor.sockbase);

    /*  If no survey is going on return EFSM error. */
    if (nn_slow (!nn_surveyor_inprogress (surveyor))) {
        if (surveyor->timedout == NN_SURVEYOR_TIMEDOUT) {
            surveyor->timedout = 0;
            return -ETIMEDOUT;
        } else
            return -EFSM;
    }

    while (1) {

        /*  Get next response. */
        rc = nn_xsurveyor_recv (&surveyor->xsurveyor.sockbase, msg);
        if (nn_slow (rc == -EAGAIN))
            return -EAGAIN;
        errnum_assert (rc == 0, -rc);

        /*  Get the survey ID. Ignore any stale responses. */
        /*  TODO: This should be done asynchronously! */
        if (nn_slow (nn_chunkref_size (&msg->sphdr) != sizeof (uint32_t)))
            continue;
        surveyid = nn_getl (nn_chunkref_data (&msg->sphdr));
        if (nn_slow (surveyid != surveyor->surveyid))
            continue;

        /*  Discard the header and return the message to the user. */
        nn_chunkref_term (&msg->sphdr);
        nn_chunkref_init (&msg->sphdr, 0);
        break;
    }

    return 0;
}

static int nn_surveyor_setopt (struct nn_sockbase *self, int level, int option,
    const void *optval, size_t optvallen)
{
    struct nn_surveyor *surveyor;

    surveyor = nn_cont (self, struct nn_surveyor, xsurveyor.sockbase);

    if (level != NN_SURVEYOR)
        return -ENOPROTOOPT;

    if (option == NN_SURVEYOR_DEADLINE) {
        if (nn_slow (optvallen != sizeof (int)))
            return -EINVAL;
        surveyor->deadline = *(int*) optval;
        return 0;
    }

    return -ENOPROTOOPT;
}

static int nn_surveyor_getopt (struct nn_sockbase *self, int level, int option,
    void *optval, size_t *optvallen)
{
    struct nn_surveyor *surveyor;

    surveyor = nn_cont (self, struct nn_surveyor, xsurveyor.sockbase);

    if (level != NN_SURVEYOR)
        return -ENOPROTOOPT;

    if (option == NN_SURVEYOR_DEADLINE) {
        if (nn_slow (*optvallen < sizeof (int)))
            return -EINVAL;
        *(int*) optval = surveyor->deadline;
        *optvallen = sizeof (int);
        return 0;
    }

    return -ENOPROTOOPT;
}

static void nn_surveyor_shutdown (struct nn_fsm *self, int src, int type,
    NN_UNUSED void *srcptr)
{
    struct nn_surveyor *surveyor;

    surveyor = nn_cont (self, struct nn_surveyor, fsm);

    if (nn_slow (src== NN_FSM_ACTION && type == NN_FSM_STOP)) {
        nn_timer_stop (&surveyor->timer);
        surveyor->state = NN_SURVEYOR_STATE_STOPPING;
    }
    if (nn_slow (surveyor->state == NN_SURVEYOR_STATE_STOPPING)) {
        if (!nn_timer_isidle (&surveyor->timer))
            return;
        surveyor->state = NN_SURVEYOR_STATE_IDLE;
        nn_fsm_stopped_noevent (&surveyor->fsm);
        nn_sockbase_stopped (&surveyor->xsurveyor.sockbase);
        return;
    }

    nn_fsm_bad_state(surveyor->state, src, type);
}

static void nn_surveyor_handler (struct nn_fsm *self, int src, int type,
    NN_UNUSED void *srcptr)
{
    struct nn_surveyor *surveyor;

    surveyor = nn_cont (self, struct nn_surveyor, fsm);

    switch (surveyor->state) {

/******************************************************************************/
/*  IDLE state.                                                               */
/*  The socket was created recently.                                          */
/******************************************************************************/
    case NN_SURVEYOR_STATE_IDLE:
        switch (src) {

        case NN_FSM_ACTION:
            switch (type) {
            case NN_FSM_START:
                surveyor->state = NN_SURVEYOR_STATE_PASSIVE;
                return;
            default:
                nn_fsm_bad_action (surveyor->state, src, type);
            }

        default:
            nn_fsm_bad_source (surveyor->state, src, type);
        }

/******************************************************************************/
/*  PASSIVE state.                                                            */
/*  There's no survey going on.                                               */
/******************************************************************************/
    case NN_SURVEYOR_STATE_PASSIVE:
        switch (src) {

        case NN_FSM_ACTION:
            switch (type) {
            case NN_SURVEYOR_ACTION_START:
                nn_surveyor_resend (surveyor);
                nn_timer_start (&surveyor->timer, surveyor->deadline);
                surveyor->state = NN_SURVEYOR_STATE_ACTIVE;
                return;

            default:
                nn_fsm_bad_action (surveyor->state, src, type);
            }

        default:
            nn_fsm_bad_source (surveyor->state, src, type);
        }

/******************************************************************************/
/*  ACTIVE state.                                                             */
/*  Survey was sent, waiting for responses.                                   */
/******************************************************************************/
    case NN_SURVEYOR_STATE_ACTIVE:
        switch (src) {

        case NN_FSM_ACTION:
            switch (type) {
            case NN_SURVEYOR_ACTION_CANCEL:
                nn_timer_stop (&surveyor->timer);
                surveyor->state = NN_SURVEYOR_STATE_CANCELLING;
                return;
            default:
                nn_fsm_bad_action (surveyor->state, src, type);
            }

        case NN_SURVEYOR_SRC_DEADLINE_TIMER:
            switch (type) {
            case NN_TIMER_TIMEOUT:
                nn_timer_stop (&surveyor->timer);
                surveyor->state = NN_SURVEYOR_STATE_STOPPING_TIMER;
                surveyor->timedout = NN_SURVEYOR_TIMEDOUT;
                return;
            default:
                nn_fsm_bad_action (surveyor->state, src, type);
            }

        default:
            nn_fsm_bad_source (surveyor->state, src, type);
        }

/******************************************************************************/
/*  CANCELLING state.                                                         */
/*  Survey was cancelled, but the old timer haven't stopped yet. The new      */
/*  survey thus haven't been sent and is stored in 'tosend'.                  */
/******************************************************************************/
    case NN_SURVEYOR_STATE_CANCELLING:
        switch (src) {

        case NN_FSM_ACTION:
            switch (type) {
            case NN_SURVEYOR_ACTION_CANCEL:
                return;
            default:
                nn_fsm_bad_action (surveyor->state, src, type);
            }

        case NN_SURVEYOR_SRC_DEADLINE_TIMER:
            switch (type) {
            case NN_TIMER_STOPPED:
                nn_surveyor_resend (surveyor);
                nn_timer_start (&surveyor->timer, surveyor->deadline);
                surveyor->state = NN_SURVEYOR_STATE_ACTIVE;
                return;
            default:
                nn_fsm_bad_action (surveyor->state, src, type);
            }

        default:
            nn_fsm_bad_source (surveyor->state, src, type);
        }

/******************************************************************************/
/*  STOPPING_TIMER state.                                                     */
/*  Survey timeout expired. Now we are stopping the timer.                    */
/******************************************************************************/
    case NN_SURVEYOR_STATE_STOPPING_TIMER:
        switch (src) {

        case NN_FSM_ACTION:
            switch (type) {
            case NN_SURVEYOR_ACTION_CANCEL:
                surveyor->state = NN_SURVEYOR_STATE_CANCELLING;
                return;
            default:
                nn_fsm_bad_action (surveyor->state, src, type);
            }

        case NN_SURVEYOR_SRC_DEADLINE_TIMER:
            switch (type) {
            case NN_TIMER_STOPPED:
                surveyor->state = NN_SURVEYOR_STATE_PASSIVE;
                return;
            default:
                nn_fsm_bad_action (surveyor->state, src, type);
            }

        default:
            nn_fsm_bad_source (surveyor->state, src, type);
        }

/******************************************************************************/
/*  Invalid state.                                                            */
/******************************************************************************/
    default:
        nn_fsm_bad_state (surveyor->state, src, type);
    }
}

static void nn_surveyor_resend (struct nn_surveyor *self)
{
    int rc;
    struct nn_msg msg;

    nn_msg_cp (&msg, &self->tosend);
    rc = nn_xsurveyor_send (&self->xsurveyor.sockbase, &msg);
    errnum_assert (rc == 0, -rc);
}

static int nn_surveyor_create (void *hint, struct nn_sockbase **sockbase)
{
    struct nn_surveyor *self;

    self = nn_alloc (sizeof (struct nn_surveyor), "socket (surveyor)");
    alloc_assert (self);
    nn_surveyor_init (self, &nn_surveyor_sockbase_vfptr, hint);
    *sockbase = &self->xsurveyor.sockbase;

    return 0;
}

static struct nn_socktype nn_surveyor_socktype_struct = {
    AF_SP,
    NN_SURVEYOR,
    0,
    nn_surveyor_create,
    nn_xsurveyor_ispeer,
    NN_LIST_ITEM_INITIALIZER
};

struct nn_socktype *nn_surveyor_socktype = &nn_surveyor_socktype_struct;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.bluelotussoftware</groupId>
        <artifactId>java-bootcamp-lessons</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <artifactId>lesson01</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>
    <properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
    <name>Lesson01</name>
</project>

redpajama_set_name: RedPajamaGithub


text:
import React from 'react'
import PropTypes from 'prop-types'
import getConfig from 'next/config'
import {flowRight} from 'lodash'
import {withRouter} from 'next/router'
import {translate} from 'react-i18next'

import withSession from '../../hoc/with-session'

import Container from '../../container'
import Link from '../../link'
import LanguageSelection from './language-selection'

const {publicRuntimeConfig: {
  PUBLIC_URL,
  PUBLICATION_BASE_URL
}} = getConfig()

class Header extends React.Component {
  static propTypes = {
    router: PropTypes.shape({
      pathname: PropTypes.string.isRequired
    }).isRequired,

    session: PropTypes.shape({
      user: PropTypes.shape({
        id: PropTypes.string.isRequired,
        first_name: PropTypes.string.isRequired,
        last_name: PropTypes.string.isRequired,
        avatar_thumbnail: PropTypes.string
      }),
      clear: PropTypes.func.isRequired
    }),

    i18n: PropTypes.shape({
      language: PropTypes.string.isRequired
    }).isRequired,
    t: PropTypes.func.isRequired
  }

  static defaultProps = {
    session: null
  }

  render() {
    const {router, session, t, i18n: {language}} = this.props

    const publicUrl = `${PUBLIC_URL}/${language}`

    const loginRedirect = `${publicUrl}/publication`
    const isPublication = router.pathname.startsWith('/publication')
    const logoutRedirect = isPublication ? `${PUBLIC_URL}/${language}` : PUBLIC_URL + router.asPath

    const logInUrl = `${PUBLICATION_BASE_URL}/login?redirect=${encodeURIComponent(loginRedirect)}`
    const logoutUrl = `${PUBLICATION_BASE_URL}/logout?redirect=${encodeURIComponent(logoutRedirect)}`

    return (

        <Container fluid>

            <Link prefetch href='/'>

            </Link>

                {session && session.user ? (
                  <Link prefetch href='/publication'>

                      {session.user.first_name} {session.user.last_name}

                  </Link>
                ) : (

                    {t('header.publish')}

                )}

                <LanguageSelection />

              {session && session.user && (

                    {t('header.logout')}

              )}

        </Container>

    )
  }
}

export default flowRight(
  translate(),
  withRouter,
  withSession
)(Header)


text:
<?php

namespace PhpCommonUtilities\VariableHandling;

class IsInteger implements VariableHandling {
    /**
     * Returns true if any of the given values are integers. Otherwise returns false.
     *
     * @param mixed ... values
     * @return bool
     */
    public static function any(){
        $are_any = false;
        $values = func_get_args();

        foreach($values as $value){
            if(is_integer($value)){
                $are_any = true;
                break;
            }
        }

        return $are_any;
    }

    /**
     * Returns true if none of the given values are integers. Otherwise returns false.
     *
     * @param mixed... values
     * @return bool
     */
    public static function none(){
        return !call_user_func_array(__CLASS__.'::any', func_get_args());
    }

    /**
     * Returns true if all of the given values are integers. Otherwise returns false.
     *
     * @return bool
     */
    public static function all(){
        $are_all = true;
        $values = func_get_args();

        foreach($values as $value){
            if(!is_integer($value)){
                $are_all = false;
                break;
            }
        }

        return $are_all;
    }

    /**
     * Returns true if the given value is an integer. Otherwise returns false.
     *
     * @param mixed $value
     * @return bool
     */
    public static function value($value){
        return is_integer($value);
    }
}


text:
package com.mentor.nucleus.bp.debug.test;
//=====================================================================
//
//File:      $RCSfile: VerifierTestSuiteI.java,v $
//Version:   $Revision: 1.5 $
//Modified:  $Date: 2013/01/10 22:42:04 $
//
//(c) Copyright 2004-2014 by Mentor Graphics Corp. 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.
//=====================================================================

import com.mentor.nucleus.bp.test.common.BaseTest;

public class VerifierTestSuiteI extends BaseTest {

	public VerifierTestSuiteI(String arg0) {
		super(null, arg0);
	}

	protected void setUp() throws Exception {
		super.setUp();
	}

	protected void tearDown() throws Exception {
		super.tearDown();
	}

	public void testVerifierTestSuite1() {
		assert(true);
	}

}


text:
namespace Poly
{
	CoreConfig gCoreConfig;
}


text:
from __future__ import unicode_literals

from django.apps import AppConfig

class AutolimsConfig(AppConfig):
    name = 'autolims'


text:
package com.sforce.ws.codegen.metadata;

import com.sforce.ws.codegen.ConnectionMetadataConstructor;

import java.util.List;

/**
 * @author btoal
 * @author hhildebrand
 * @author sweiss
 * @since 184
 */
public class OperationMetadata {
    private final String returnType;
    private final String operationName;
    private final String requestType;
    private final String responseType;
    private final String soapAction;
    private final String requestName;
    private final String responseName;
    private final String resultCall;
    private final List<ElementMetadata> elements;
    private final List<HeaderMetadata> headers;
    private final String returnTypeInterface;

    // SObject sObject, String s
    private final String argsWithClasses;
    // sObject, s
    private final String argsWithoutTypes;
    // ISObject sObject, String s
    private final String argsWithInterfaces;
    // (SObject)sObject, s
    private final String argsWithCasts;

    public OperationMetadata(final String returnType, final String operationName, final String requestType,
                             final String responseType, final String argsWithClasses, String argsWithoutTypes, String argsWithInterfaces, String argsWithCasts, final String soapAction, final String requestName, final String responseName, final String resultCall, final List<ElementMetadata> elements, final List<HeaderMetadata> headers, boolean isReturnTypeComplexType, String returnTypeInterface) {
        this.returnType = returnType;
        this.operationName = operationName;
        this.requestType = requestType;
        this.responseType = responseType;
        this.argsWithClasses = argsWithClasses;
        this.argsWithoutTypes = argsWithoutTypes;
        this.argsWithInterfaces = argsWithInterfaces;
        this.argsWithCasts = argsWithCasts;
        this.soapAction = soapAction;
        this.requestName = requestName;
        this.responseName = responseName;
        this.resultCall = resultCall;
        this.elements = elements;
        this.headers = headers;
        this.returnTypeInterface = returnTypeInterface;
    }

    public static OperationMetadata newInstance(final String returnType, final String operationName, final String requestType,
                                                final String responseType, final String argsWithClasses, String argsWithoutTypes, String argsWithInterfaces, String argsWithCasts, final String soapAction, final String requestName, final String responseName, final String resultCall, final List<ElementMetadata> elements, final List<HeaderMetadata> headers, boolean isReturnTypeComplexType, String returnTypeInterface) {
        return new OperationMetadata(returnType, operationName, requestType, responseType, argsWithClasses, argsWithoutTypes, argsWithInterfaces, argsWithCasts, soapAction, requestName, responseName, resultCall, elements, headers, isReturnTypeComplexType, returnTypeInterface);
    }

    public String getReturnType() {
        return returnType;
    }

    public String getOperationName() {
        return operationName;
    }

    public String getRequestType() {
        return requestType;
    }

    public String getResponseType() {
        return responseType;
    }

    public String getArgsWithClasses() {
        return argsWithClasses;
    }

    public String getArgsWithInterfaces() {
        return argsWithInterfaces;
    }

    public String getArgsWithCasts() {
        return argsWithCasts;
    }

    public List<ElementMetadata> getElements() {
        return elements;
    }

    public List<HeaderMetadata> getHeaders() {
        return headers;
    }

    public String getSoapAction() {
        return soapAction;
    }

    public String getRequestName() {
        return requestName;
    }

    public String getResponseName() {
        return responseName;
    }

    public String getResultCall() {
        return resultCall;
    }

    public String getArgsWithoutTypes() {
        return argsWithoutTypes;
    }

    public boolean getHasReturnType() {
        return !getReturnType().equals("void");
    }

    public String getReturnTypeInterface() {
        return returnTypeInterface;
    }
}


text:
<?php

namespace Pweb\CompteBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * StatutComRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class StatutComRepository extends EntityRepository
{
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getPages = undefined;

var _getIterator2 = require('babel-runtime/core-js/get-iterator');

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var getPages = exports.getPages = function () {
  var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(dir, _ref) {
    var dev = _ref.dev,
        isServer = _ref.isServer;
    var pageFiles;
    return _regenerator2.default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return getPagePaths(dir, { dev: dev, isServer: isServer });

          case 2:
            pageFiles = _context.sent;
            return _context.abrupt('return', getPageEntries(pageFiles, { isServer: isServer }));

          case 4:
          case 'end':
            return _context.stop();
        }
      }
    }, _callee, this);
  }));

  return function getPages(_x, _x2) {
    return _ref2.apply(this, arguments);
  };
}();

var getPagePaths = function () {
  var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(dir, _ref3) {
    var dev = _ref3.dev,
        isServer = _ref3.isServer;
    var pages;
    return _regenerator2.default.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            pages = void 0;

            if (!dev) {
              _context2.next = 7;
              break;
            }

            _context2.next = 4;
            return (0, _globPromise2.default)(isServer ? 'pages/+(_document|_error).+(js|jsx|ts|tsx)' : 'pages/_error.+(js|jsx|ts|tsx)', { cwd: dir });

          case 4:
            pages = _context2.sent;
            _context2.next = 10;
            break;

          case 7:
            _context2.next = 9;
            return (0, _globPromise2.default)(isServer ? 'pages/**/*.+(js|jsx|ts|tsx)' : 'pages/**/!(_document)*.+(js|jsx|ts|tsx)', { cwd: dir });

          case 9:
            pages = _context2.sent;

          case 10:
            return _context2.abrupt('return', pages);

          case 11:
          case 'end':
            return _context2.stop();
        }
      }
    }, _callee2, this);
  }));

  return function getPagePaths(_x3, _x4) {
    return _ref4.apply(this, arguments);
  };
}();

// Convert page path into single entry

exports.createEntry = createEntry;
exports.getPageEntries = getPageEntries;

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _globPromise = require('glob-promise');

var _globPromise2 = _interopRequireDefault(_globPromise);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var nextPagesDir = _path2.default.join(__dirname, '..', '..', '..', 'pages');

function createEntry(filePath, name) {
  var parsedPath = _path2.default.parse(filePath);
  var entryName = name || filePath;

  // This makes sure we compile `pages/blog/index.js` to `pages/blog.js`.
  // Excludes `pages/index.js` from this rule since we do want `/` to route to `pages/index.js`
  if (parsedPath.dir !== 'pages' && parsedPath.name === 'index') {
    entryName = parsedPath.dir + '.js';
  }

  // Makes sure supported extensions are stripped off. The outputted file should always be `.js`
  entryName = entryName.replace(/\.+(jsx|tsx|ts)/, '.js');

  return {
    name: _path2.default.join('bundles', entryName),
    files: [parsedPath.root ? filePath : './' + filePath] // The entry always has to be an array.
  };
}

// Convert page paths into entries
function getPageEntries(pagePaths, _ref5) {
  var isServer = _ref5.isServer;

  var entries = {};

  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = (0, _getIterator3.default)(pagePaths), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var filePath = _step.value;

      var entry = createEntry(filePath);
      entries[entry.name] = entry.files;
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator.return) {
        _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  var errorPagePath = _path2.default.join(nextPagesDir, '_error.js');
  var errorPageEntry = createEntry(errorPagePath, 'pages/_error.js'); // default error.js
  if (!entries[errorPageEntry.name]) {
    entries[errorPageEntry.name] = errorPageEntry.files;
  }

  if (isServer) {
    var documentPagePath = _path2.default.join(nextPagesDir, '_document.js');
    var documentPageEntry = createEntry(documentPagePath, 'pages/_document.js');
    if (!entries[documentPageEntry.name]) {
      entries[documentPageEntry.name] = documentPageEntry.files;
    }
  }

  return entries;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.mortbay.io.bio Class Hierarchy (Jetty Server Project 6.1.22 API)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../javadoc.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package org.mortbay.io.bio

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

org.mortbay.io.bio.StreamEndPoint (implements org.mortbay.io.EndPoint)

org.mortbay.io.bio.SocketEndPoint
org.mortbay.io.bio.StringEndPoint

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 1995-2009 Mort Bay Consulting. All Rights Reserved.


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Ext Direct Highcharts with dynamic update</title>
  <link rel="stylesheet" type="text/css" href="https://static.rasc.ch/ext-3.4.3/resources/css/ext-all.css" />
  <link rel="stylesheet" type="text/css" href="../examples.css" />

Ext Direct Highcharts with dynamic update

Source code: dynamic.js


text:
/* $Id: tif_dir.h,v 1.17 2005/07/06 11:23:55 dron Exp $ */

/*
 * Copyright (c) 1988-1997 Sam Leffler
 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
 *
 * Permission to use, copy, modify, distribute, and sell this software and
 * its documentation for any purpose is hereby granted without fee, provided
 * that (i) the above copyright notices and this permission notice appear in
 * all copies of the software and related documentation, and (ii) the names of
 * Sam Leffler and Silicon Graphics may not be used in any advertising or
 * publicity relating to the software without the specific, prior written
 * permission of Sam Leffler and Silicon Graphics.
 *
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
 *
 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
 * OF THIS SOFTWARE.
 */

#ifndef _TIFFDIR_
#define	_TIFFDIR_
/*
 * ``Library-private'' Directory-related Definitions.
 */

/*
 * Internal format of a TIFF directory entry.
 */
typedef	struct {
#define	FIELD_SETLONGS	4
	/* bit vector of fields that are set */
	unsigned long	td_fieldsset[FIELD_SETLONGS];

	uint32	td_imagewidth, td_imagelength, td_imagedepth;
	uint32	td_tilewidth, td_tilelength, td_tiledepth;
	uint32	td_subfiletype;
	uint16	td_bitspersample;
	uint16	td_sampleformat;
	uint16	td_compression;
	uint16	td_photometric;
	uint16	td_threshholding;
	uint16	td_fillorder;
	uint16	td_orientation;
	uint16	td_samplesperpixel;
	uint32	td_rowsperstrip;
	uint16	td_minsamplevalue, td_maxsamplevalue;
	double	td_sminsamplevalue, td_smaxsamplevalue;
	float	td_xresolution, td_yresolution;
	uint16	td_resolutionunit;
	uint16	td_planarconfig;
	float	td_xposition, td_yposition;
	uint16	td_pagenumber[2];
	uint16*	td_colormap[3];
	uint16	td_halftonehints[2];
	uint16	td_extrasamples;
	uint16*	td_sampleinfo;
	double	td_stonits;
	tstrip_t td_stripsperimage;
	tstrip_t td_nstrips;		/* size of offset & bytecount arrays */
	uint32*	td_stripoffset;
	uint32*	td_stripbytecount;
	int	td_stripbytecountsorted; /* is the bytecount array sorted ascending? */
	uint16	td_nsubifd;
	uint32*	td_subifd;
	/* YCbCr parameters */
	float*	td_ycbcrcoeffs;
	uint16	td_ycbcrsubsampling[2];
	uint16	td_ycbcrpositioning;
	/* Colorimetry parameters */
	float*	td_whitepoint;
	float*	td_refblackwhite;
	uint16*	td_transferfunction[3];
	/* CMYK parameters */
	uint16	td_inkset;
	uint16	td_ninks;
	uint16	td_dotrange[2];
	int	td_inknameslen;
	char*	td_inknames;
	/* ICC parameters */
	uint32	td_profileLength;
	void	*td_profileData;
	/* Adobe Photoshop tag handling */
	uint32	td_photoshopLength;
	void	*td_photoshopData;
	/* IPTC parameters */
	uint32	td_richtiffiptcLength;
	void	*td_richtiffiptcData;
	uint32	td_xmlpacketLength;
	void	*td_xmlpacketData;
	int     td_customValueCount;
        TIFFTagValue *td_customValues;
} TIFFDirectory;

/*
 * Field flags used to indicate fields that have
 * been set in a directory, and to reference fields
 * when manipulating a directory.
 */

/*
 * FIELD_IGNORE is used to signify tags that are to
 * be processed but otherwise ignored.  This permits
 * antiquated tags to be quietly read and discarded.
 * Note that a bit *is* allocated for ignored tags;
 * this is understood by the directory reading logic
 * which uses this fact to avoid special-case handling
 */
#define	FIELD_IGNORE			0

/* multi-item fields */
#define	FIELD_IMAGEDIMENSIONS		1
#define FIELD_TILEDIMENSIONS		2
#define	FIELD_RESOLUTION		3
#define	FIELD_POSITION			4

/* single-item fields */
#define	FIELD_SUBFILETYPE		5
#define	FIELD_BITSPERSAMPLE		6
#define	FIELD_COMPRESSION		7
#define	FIELD_PHOTOMETRIC		8
#define	FIELD_THRESHHOLDING		9
#define	FIELD_FILLORDER			10
/* unused - was FIELD_DOCUMENTNAME	11 */
/* unused - was FIELD_IMAGEDESCRIPTION	12 */
/* unused - was FIELD_MAKE		13 */
/* unused - was FIELD_MODEL		14 */
#define	FIELD_ORIENTATION		15
#define	FIELD_SAMPLESPERPIXEL		16
#define	FIELD_ROWSPERSTRIP		17
#define	FIELD_MINSAMPLEVALUE		18
#define	FIELD_MAXSAMPLEVALUE		19
#define	FIELD_PLANARCONFIG		20
/* unused - was FIELD_PAGENAME		21 */
#define	FIELD_RESOLUTIONUNIT		22
#define	FIELD_PAGENUMBER		23
#define	FIELD_STRIPBYTECOUNTS		24
#define	FIELD_STRIPOFFSETS		25
#define	FIELD_COLORMAP			26
/* unused - was FIELD_ARTIST		27 */
/* unused - was FIELD_DATETIME		28 */
/* unused - was FIELD_HOSTCOMPUTER	29 */
/* unused - was FIELD_SOFTWARE          30 */
#define	FIELD_EXTRASAMPLES		31
#define FIELD_SAMPLEFORMAT		32
#define	FIELD_SMINSAMPLEVALUE		33
#define	FIELD_SMAXSAMPLEVALUE		34
#define FIELD_IMAGEDEPTH		35
#define FIELD_TILEDEPTH			36
#define	FIELD_HALFTONEHINTS		37
#define FIELD_YCBCRCOEFFICIENTS		38
#define FIELD_YCBCRSUBSAMPLING		39
#define FIELD_YCBCRPOSITIONING		40
#define	FIELD_REFBLACKWHITE		41
#define	FIELD_WHITEPOINT		42
/* unused - was FIELD_PRIMARYCHROMAS	43 */
#define	FIELD_TRANSFERFUNCTION		44
#define	FIELD_INKSET			45
#define	FIELD_INKNAMES			46
#define	FIELD_DOTRANGE			47
/* unused - was FIELD_TARGETPRINTER	48 */
#define	FIELD_SUBIFD			49
#define	FIELD_NUMBEROFINKS		50
#define FIELD_ICCPROFILE		51
#define FIELD_PHOTOSHOP			52
#define FIELD_RICHTIFFIPTC		53
#define FIELD_STONITS			54
/* unused - was FIELD_IMAGEFULLWIDTH	55 */
/* unused - was FIELD_IMAGEFULLLENGTH	56 */
/* unused - was FIELD_TEXTUREFORMAT	57 */
/* unused - was FIELD_WRAPMODES		58 */
/* unused - was FIELD_FOVCOT		59 */
/* unused - was FIELD_MATRIX_WORLDTOSCREEN	60 */
/* unused - was FIELD_MATRIX_WORLDTOCAMERA	61 */
/* unused - was FIELD_COPYRIGHT		62 */
#define FIELD_XMLPACKET			63
/*      FIELD_CUSTOM (see tiffio.h)     65 */
/* end of support for well-known tags; codec-private tags follow */
#define	FIELD_CODEC			66	/* base of codec-private tags */

/*
 * Pseudo-tags don't normally need field bits since they
 * are not written to an output file (by definition).
 * The library also has express logic to always query a
 * codec for a pseudo-tag so allocating a field bit for
 * one is a waste.   If codec wants to promote the notion
 * of a pseudo-tag being ``set'' or ``unset'' then it can
 * do using internal state flags without polluting the
 * field bit space defined for real tags.
 */
#define	FIELD_PSEUDO			0

#define	FIELD_LAST			(32*FIELD_SETLONGS-1)

#define	TIFFExtractData(tif, type, v) \
    ((uint32) ((tif)->tif_header.tiff_magic == TIFF_BIGENDIAN ? \
        ((v) >> (tif)->tif_typeshift[type]) & (tif)->tif_typemask[type] : \
	(v) & (tif)->tif_typemask[type]))
#define	TIFFInsertData(tif, type, v) \
    ((uint32) ((tif)->tif_header.tiff_magic == TIFF_BIGENDIAN ? \
        ((v) & (tif)->tif_typemask[type]) << (tif)->tif_typeshift[type] : \
	(v) & (tif)->tif_typemask[type]))

#define BITn(n)				(((unsigned long)1L)<<((n)&0x1f))
#define BITFIELDn(tif, n)		((tif)->tif_dir.td_fieldsset[(n)/32])
#define TIFFFieldSet(tif, field)	(BITFIELDn(tif, field) & BITn(field))
#define TIFFSetFieldBit(tif, field)	(BITFIELDn(tif, field) |= BITn(field))
#define TIFFClrFieldBit(tif, field)	(BITFIELDn(tif, field) &= ~BITn(field))

#define	FieldSet(fields, f)		(fields[(f)/32] & BITn(f))
#define	ResetFieldBit(fields, f)	(fields[(f)/32] &= ~BITn(f))

#if defined(__cplusplus)
extern "C" {
#endif
extern	void _TIFFSetupFieldInfo(TIFF*);
extern	void _TIFFPrintFieldInfo(TIFF*, FILE*);
extern	TIFFDataType _TIFFSampleToTagType(TIFF*);
extern  const TIFFFieldInfo* _TIFFFindOrRegisterFieldInfo( TIFF *tif,
							   ttag_t tag,
							   TIFFDataType dt );
extern  TIFFFieldInfo* _TIFFCreateAnonFieldInfo( TIFF *tif, ttag_t tag,
                                                 TIFFDataType dt );

#define _TIFFMergeFieldInfo	    TIFFMergeFieldInfo
#define _TIFFFindFieldInfo	    TIFFFindFieldInfo
#define _TIFFFindFieldInfoByName    TIFFFindFieldInfoByName
#define _TIFFFieldWithTag	    TIFFFieldWithTag
#define _TIFFFieldWithName	    TIFFFieldWithName

#if defined(__cplusplus)
}
#endif
#endif /* _TIFFDIR_ */

/* vim: set ts=8 sts=8 sw=8 noet: */


text:
<!doctype HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Serialization - singleton</title>

Serialization

singleton

Motivation

Features

Class Interface

Requirements

Examples

Multi-Threading

Motivation

The serialization library relies on the existence of a number
of static variables and tables to store information related
to runtime types.  Examples are tables which relate exported
names to types and tables which relate base classes to derived
classes.  Construction, destruction and usage of these variables
requires consideration of the following issues:

Some static data variables and constants  entries refer to others.
  The sequence of initialization cannot be arbitrary but must be in proper
  sequence.

A number of static variables aren't referred explicitly and, without
  special precautions, will be stripped by most code optimizers

Many of these variables are created by templates and special care must
  be taken to be sure that they are instantiated

In a multi-threading system, its possible that these static variables
  will be accessed concurrently by separate threads.  This would create a
  race condition with unpredictabe behavior

This singleton class addresses all of the above issues.

Features

This singleton implementation has the following features:

    Any instance will be constructed before any attempt is made to access it.

    Any instance created with a template is guarenteed to be instantiated.

    Regardless of whether or not an instance has been explicitly
    referred to, it will not be stripped by the optimizer when the
    executable is built in release mode.

    All instances are constructed before
    main is called
    regardless of where they might be referenced within the program.
    In a multi-tasking system, this guarentees that there will be no
    race conditions during the construction of any instance.  No
    thread locking is required to guarentee this.

    The above implies that any const
    instances are thread-safe during the whole program.  Again, no
    thread locking is required.

    If a mutable instance is created, and such an instance is modified
    after main is called in a mult-threading system, there exists
    the possibility that a race condition will occur.  The serialization
    library takes care that in the few places where a mutable
    singleton is required, it is not altered after
    main is called.
    For a more general purpose usage, thread locking on this
    singleton could easily be implemented.  But as the serialization
    library didn't require it, it wasn't implemented.

Class Interface

namespace boost {
namespace serialization {

template <class T>
class singleton : public boost::noncopyable
{
public:
    static const T & get_const_instance();
    static T & get_mutable_instance();
    static bool is_destroyed();
};

} // namespace serialization
} // namespace boost

static const T & get_const_instance();

Retrieve a constant reference to the singleton for this type.

static T & get_mutable_instance();

Retrieve a mutable reference to the singleton for this type.

static bool is_destroyed();

Return true if the destructor on this singleton has been
called.  Otherwise, return false.

Requirements

In order to be used as

singleton<T>

, the type T must be default constructable.
It doesn't require static variables - though it may have them.
Since the library guarentees that only one instance of

singleton<T>

and all accesss is through the above static interface
functions, common member functions of T become
the functional equivalent of
static functions.

Examples

There are at least two different ways to use this class template.
Both are used in the serialization library.

The first way is illustrated by and excerpt from the file
extended_type_info.cpp.
which contains the following code:

typedef std::set<const extended_type_info *, key_compare> ktmap;
...
void
extended_type_info::key_register(const char *key) {
    ...
    result = singleton<ktmap>::get_mutable_instance().insert(this);
    ...
}

Just by referring to the singleton instance anywhere in the program
will guarentee that one and only one instance for the specified
type (ktmap in this example)
will exist throughout the program.  There is no need for anyother
declaration or definition.

A second way is to use

singleton<T>

as one of the base classes of the type.  This is illustrated by a simplified
excerpt from

extended_type_info_typeid.hpp

template<class T>
class extended_type_info_typeid :
    public detail::extended_type_info_typeid_0,
    public singleton<extended_type_info_typeid<const T> >
{
    friend class singleton<extended_type_info_typeid<const T> >;
private:
    // private constructor to inhibit any existence other than the
    // static one.  Note: not all compilers support this !!!
    extended_type_info_typeid() :
        detail::extended_type_info_typeid_0()
    {
        type_register(typeid(T));
    }
    ~extended_type_info_typeid(){}
    ...
};

This usage will permit a more natural syntax to be used:

extended_type_info_typeid<T>::get_const_instance()

Again, including one or more of the above statements anywhere
in the program will guarentee that one and only one instance
is created and referred to.

Multi-Threading

This singleton CAN be safely used in multi-threading applications if one
is careful follow a simple rule:

Do not call get_mutable_instance when more than one thread is running!
<'>
All singletons used in the serialization library follow this rule.
In order to help detect accidental violations of this rule there
exists an singleton lock/unlock functions.

void boost::serialization::singleton_module::lock();
void boost::serialization::singleton_module::unlock();
bool boost::serialization::singleton_module::is_locked();

In a program compiled for debug, any invocation of
get_mutable_instance()
while the library is in a "locked" state will trap in an assertion.
The singleton module lock state is initialized as "unlocked" to permit
alteration of static variables before
main is called.
The lock() and
unlock() are "global"
in they affect ALL the singletons defined by this template.
All serialization tests invoke lock()
at the start of the progam.  For programs compiled in release
mode these functions have no effect.

© Copyright Robert Ramey 2007.
Distributed under the Boost Software License, Version 1.0. (See
accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
require_relative "version_string"

class Chef
  CHEF_ROOT = File.expand_path("..", __dir__)
  VERSION = Chef::VersionString.new("17.0.242")
end

#
# NOTE: the Chef::Version class is defined in version_class.rb
#
# NOTE: DO NOT Use the Chef::Version class on Chef::VERSIONs.  The
#       Chef::Version class is for _cookbooks_ only, and cannot handle
#       pre-release versions like "10.14.0.rc.2".  Please use Rubygem's
#       Gem::Version class instead.
#


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@color/colorBackground"
    tools:context="jp.co.recruit.mtl.datetimepickerex.MainActivity">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal" android:layout_width="match_parent"
        android:layout_height="match_parent">

        <jp.co.recruit.mtl.datetimepickerex.DatePickerEx
            android:id="@+id/event_date_picker"
            android:layout_width="0dp"
            android:layout_height="200dp"
            android:layout_weight="1"
            android:calendarViewShown="false"
            android:datePickerMode="spinner"  />

        <jp.co.recruit.mtl.datetimepickerex.TimePickerEx
            android:id="@+id/event_time_picker"
            android:layout_width="0dp"
            android:layout_height="200dp"
            android:layout_weight="1"
            android:timePickerMode="spinner" />
    </LinearLayout>
</LinearLayout>


text:
use common::{EmailAddress, AddrError};

/// Performs a dead-simple parse of an email address.
pub fn parse(input: &str) -> Result<EmailAddress, AddrError> {
    if input.is_empty() {
        return Err(AddrError { msg: "empty string is not valid".to_string() });
    }
    let parts: Vec<&str> = input.rsplitn(2, '@').collect();

    if parts.len() < 2 {
        return Err(AddrError { msg: "missing '@' character".to_string() });
    }

    if parts[0].is_empty() {
        return Err(AddrError { msg: "empty string is not valid for local part".to_string() });
    }

    if parts[1].is_empty() {
        return Err(AddrError { msg: "empty string is not valid for domain part".to_string() });
    }

    Ok(EmailAddress {
        local: parts[1].to_string(),
        domain: parts[0].to_string()
    })
}

#[cfg(test)]
mod test {
    use super::*;
    use common::{EmailAddress};

    #[test]
    fn test_simple_parse() {
        assert!(parse("f@a").is_ok());
        assert!(parse("foo").is_err());
        assert_eq!(
                parse("someone@example.com").unwrap(),
                EmailAddress {
                    local: "someone".to_string(),
                    domain: "example.com".to_string()
                }
            );
    }
}


text:
({
	// displays the progress bar if the progress counter is > 0
	showProgress : function(component) {
		var spinner = component.find('spinner');
		var evt = spinner.get("e.toggle");
		evt.setParams({ isVisible : true });
		evt.fire();
	},

	// hides the progress bar if the progress counter is 0
	hideProgress : function (component) {
		var spinner = component.find('spinner');
		var evt = spinner.get("e.toggle");
		evt.setParams({ isVisible : false });
		evt.fire();
	},

	// sets up event handlers, skills checkboxes and recent jobs
	initialise : function (component) {
        var self=this;
		this.getSkills(component);
		this.getLatestJobs(component);
	},

	// clears the search terms and skills checkboxes and reverts the jobs list to the recent jobs view
	clearSearch : function(component) {
		$('[id^="skillcb_"]:checkbox:checked').removeAttr('checked');
		$('#searchterm').val('');
		this.getLatestJobs(component);
	},

	// executes a search based on the entered terms and selected skill sets
	doSearch : function(component) {
        console.log('In doSearch');
		this.showProgress(component);
		var term=$('#searchterm').val();
		var skills=[];
		$('[id^="skillcb_"]:checkbox:checked').each(function(i){
			skills.push($(this).val());
		});
        var skillsStr=skills.join();
		console.log('Term = ' + term);
		console.log('SkillsStr = ' + skillsStr);
        var action = component.get("c.SearchJobs");
		action.setParams({
			"searchStr": term,
            "skillsStr":skillsStr
		});

        var self = this;
        action.setCallback(this, function(response) {
            self.actionResponseHandler(response, self.renderJobs, component);
        });
    	$A.enqueueAction(action);
	},
    // get the latest jobs from the server
    getLatestJobs : function(component) {
        this.showProgress(component);
        var action = component.get("c.GetRecentJobs");
	    var self = this;
    	action.setCallback(this, function(response) {
            self.actionResponseHandler(response, self.renderJobs, component);
	    });
    	$A.enqueueAction(action);
    },

	// get the skills from the server
	getSkills : function (component) {
		this.showProgress(component);
        var action = component.get("c.GetSkills");
	    var self = this;
    	action.setCallback(this, function(response) {
            self.actionResponseHandler(response, self.renderSkills, component);
	    });
    	$A.enqueueAction(action);
	},
	renderJobs : function(wrappers, component) {
		$A.get("e.c:JobListEvent").
		        		setParams({jobWrappers: wrappers}).fire();

        if (0==wrappers.length)
		{
			alertify.error('No matching jobs found');
		}
	},
    renderSkills : function(skills, component) {
        component.set("v.skills", skills);
    },
	actionResponseHandler : function (response, cb, component) {
		var state = response.getState();
		if (state === "SUCCESS")
		{
			var retVal=response.getReturnValue();
			console.log('Result = ' + JSON.stringify(retVal));
            cb(retVal, component);
		}
		else if (state === "ERROR")
		{
			var errors = response.getError();
			if (errors)
			{
				$A.logf("Errors", errors);
				if (errors[0] && errors[0].message)
				{
					$A.error("Error message: " + errors[0].message);
				}
			}
			else
			{
				$A.error("Unknown error");
			}
		}
        this.hideProgress(component);
	},
	// stack trace function - simply execute console.log(getStackTrace()); or similar - tested in chrome
    getStackTrace : function() {
  		var obj = {};
  		if (typeof Error.captureStackTrace == 'function')
  		{
	  		Error.captureStackTrace(obj, getStackTrace);
  			return obj.stack;
  		}
  		else
  		{
  			return 'Stack trace not supported';
  		}
	},
    //
	// Test methods
	//
    runTests : function(component, event)
    {
        try
        {
	        QUnit.module('JobSearch');
	        this.testInitialise(component, event);
	        this.testClearSearch(component, event);
	        this.testDoSearch(component, event);
        }
        catch (e)
        {
            alert('Exception ' + e);
        }
    },
    testInitialise: function(component, event)
    {
        var self=this;
		QUnit.test( "Initialise", function( assert ) {
            // stub the methods that will be invoked
            var getSkillsStub = sinon.stub(self, 'getSkills');
            var getLatestJobsStub = sinon.stub(self, 'getLatestJobs');

            // execute the method under test
            self.initialise(component)

	 		// the methods should be executed exactly once
			assert.equal( getSkillsStub.callCount, 1, "getSkills called once");
			assert.equal( getLatestJobsStub.callCount, 1, "getLatestJobs called once");

            // remove the stubs and restore the original functions
			getSkillsStub.restore();
			getLatestJobsStub.restore();
		});
    },
    testClearSearch: function(component, event) {
        var self=this;
		QUnit.test( "Clear Search", function( assert ) {
            // stub the methods that will be invoked
            var getLatestJobsStub = sinon.stub(self, 'getLatestJobs');
			$('#searchterm').val('Unit Test');

            // execute the method under test
            self.clearSearch(component)

	 		// the methods should be executed exactly once
			assert.equal( getLatestJobsStub.callCount, 1, "getLatestJobs called once");

            // the search term should be cleared
            assert.equal( $('#searchterm').val(), '', "Search term cleared")

            // remove the stubs and restore the original functions
			getLatestJobsStub.restore();
		});
    },
    testDoSearch: function(component, event) {
        var self=this;
		QUnit.test( "Do Search", function( assert ) {
			// set up some skills
			var skills=
				[
					{ Name : 'Skill1' },
	                { Name : 'Skill2' }
				];
//			self.renderSkills(skills, self.component);

            // stub the methods that will be invoked
            var enqueueActionStub = sinon.stub($A, 'enqueueAction');

			$('#searchterm').val('Unit Test');
			$('#searchterm').val('Unit Test');
			$('[id^="skillcb_Skill1"]').prop('checked', true);

            // execute the method under test
            self.doSearch(component)

	 		// the methods should be executed exactly once
			assert.equal( enqueueActionStub.callCount, 1, "enqueueAction called once");

            // remove the stubs and restore the original functions
			enqueueActionStub.restore();
		});

    }

})


text:
EntityParentHandlerSystem::EntityParentHandlerSystem() :
	EntitySystem( SystemType::TransformParentHandlerSystem, 2,
	ComponentType::ComponentTypeIdx::EntityParent,
	ComponentType::ComponentTypeIdx::Transform)
{
}

void EntityParentHandlerSystem::processEntities( const vector<Entity*>& p_entities )
{
	float dt = m_world->getDelta();
	for(unsigned int i=0; i<p_entities.size(); i++ )
	{
		EntityParent* nodeData = static_cast<EntityParent*>(
			p_entities[i]->getComponent( ComponentType::ComponentTypeIdx::EntityParent ) );

		Transform* transform = static_cast<Transform*>(
			p_entities[i]->getComponent( ComponentType::ComponentTypeIdx::Transform ) );

		Entity* parent = m_world->getEntity(nodeData->getParentEntityId());
		if (parent!=NULL)
		{
			Transform* parentTransform = static_cast<Transform*>(
				parent->getComponent( ComponentType::ComponentTypeIdx::Transform ) );
			// Set transform based on parent
			transform->setMatrix(nodeData->getLocalTransform()*parentTransform->getMatrix());
		}
		else // delete if no parent
		{
			m_world->deleteEntity(p_entities[i]);
		}
	}
}


text:
package com.siyeh.ig.bugs;

import com.intellij.psi.*;
import com.intellij.psi.util.ConstantExpressionUtil;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.psiutils.TypeUtils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

public class ResultSetIndexZeroInspection extends BaseInspection {

    @NotNull
    public String getID(){
        return "UseOfIndexZeroInJDBCResultSet";
    }

    @NotNull
    public String getDisplayName() {
        return InspectionGadgetsBundle.message(
                "use.0index.in.jdbc.resultset.display.name");
    }

    @NotNull
    public String buildErrorString(Object... infos) {
        return InspectionGadgetsBundle.message(
                "use.0index.in.jdbc.resultset.problem.descriptor");
    }

    public BaseInspectionVisitor buildVisitor() {
        return new ResultSetIndexZeroVisitor();
    }

    private static class ResultSetIndexZeroVisitor
            extends BaseInspectionVisitor {

        @Override public void visitMethodCallExpression(
                @NotNull PsiMethodCallExpression expression) {
            super.visitMethodCallExpression(expression);
            final PsiReferenceExpression methodExpression =
                    expression.getMethodExpression();
            @NonNls final String methodName =
                    methodExpression.getReferenceName();
            if(methodName == null){
                return;
            }
            if (!methodName.startsWith("get") &&
                    !methodName.startsWith("update") ) {
                return;
            }
            final PsiExpressionList argumentList = expression.getArgumentList();
            final PsiExpression[] arguments = argumentList.getExpressions();
            if(arguments.length== 0){
                return;
            }
            final PsiExpression argument = arguments[0];
            if (!TypeUtils.expressionHasType(PsiKeyword.INT, argument)) {
                return;
            }
            if(!PsiUtil.isConstantExpression(argument)) {
                return;
            }
            final Integer val =
                    (Integer) ConstantExpressionUtil.computeCastTo(argument,
                            PsiType.INT);
            if(val == null || val.intValue() != 0) {
                return;
            }
            final PsiExpression qualifier =
                    methodExpression.getQualifierExpression();
            if (!TypeUtils.expressionHasTypeOrSubtype(qualifier,
		            "java.sql.ResultSet")) {
                return;
            }
            registerError(argument);
        }
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__float_zero_81a.cpp
Label Definition File: CWE369_Divide_by_Zero__float.label.xml
Template File: sources-sinks-81a.tmpl.cpp
*/
/*
 * @description
 * CWE: 369 Divide by Zero
 * BadSource: zero Fixed value of zero
 * GoodSource: A hardcoded non-zero number (two)
 * Sinks:
 *    GoodSink: Check value of or near zero before dividing
 *    BadSink : Divide a constant by data
 * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
 *
 * */

#include "std_testcase.h"
#include "CWE369_Divide_by_Zero__float_zero_81.h"

namespace CWE369_Divide_by_Zero__float_zero_81
{

#ifndef OMITBAD

void bad()
{
    float data;
    /* Initialize data */
    data = 0.0F;
    /* POTENTIAL FLAW: Set data to zero */
    data = 0.0F;
    const CWE369_Divide_by_Zero__float_zero_81_base& baseObject = CWE369_Divide_by_Zero__float_zero_81_bad();
    baseObject.action(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
    float data;
    /* Initialize data */
    data = 0.0F;
    /* FIX: Use a hardcoded number that won't a divide by zero */
    data = 2.0F;
    const CWE369_Divide_by_Zero__float_zero_81_base& baseObject = CWE369_Divide_by_Zero__float_zero_81_goodG2B();
    baseObject.action(data);
}

/* goodB2G uses the BadSource with the GoodSink */
static void goodB2G()
{
    float data;
    /* Initialize data */
    data = 0.0F;
    /* POTENTIAL FLAW: Set data to zero */
    data = 0.0F;
    const CWE369_Divide_by_Zero__float_zero_81_base& baseObject = CWE369_Divide_by_Zero__float_zero_81_goodB2G();
    baseObject.action(data);
}

void good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

using namespace CWE369_Divide_by_Zero__float_zero_81; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
import Ember from 'ember';

export default Ember.TextField.extend({
  didInsertElement: function() {
    this.$().focus();
  },

  focusOut: function() {
    alert('out!');
  }
});


text:
require 'one_gadget/gadget'
# https://gitlab.com/david942j/libcdb/blob/master/libc/libc6-i386_2.21-0ubuntu5_amd64/lib32/libc-2.21.so
#
# Intel 80386
#
# GNU C Library (Ubuntu GLIBC 2.21-0ubuntu5) stable release version 2.21, by Roland McGrath et al.
# Copyright (C) 2015 Free Software Foundation, Inc.
# This is free software; see the source for copying conditions.
# There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
# Compiled by GNU CC version 4.9.3.
# Available extensions:
# 	crypt add-on version 2.1 by Michael Glad and others
# 	GNU Libidn by Simon Josefsson
# 	Native POSIX Threads Library by Ulrich Drepper et al
# 	BIND-8.2.3-T5B
# libc ABIs: UNIQUE IFUNC
# For bug reporting instructions, please see:
# <https://bugs.launchpad.net/ubuntu/+source/glibc/+bugs>.

build_id = File.basename(__FILE__, '.rb').split('-').last
OneGadget::Gadget.add(build_id, 240566,
                      constraints: ["ebx is the GOT address of libc", "[esp+0x28] == NULL"],
                      effect: "execve(\"/bin/sh\", esp+0x28, environ)")
OneGadget::Gadget.add(build_id, 240568,
                      constraints: ["ebx is the GOT address of libc", "[esp+0x2c] == NULL"],
                      effect: "execve(\"/bin/sh\", esp+0x2c, environ)")
OneGadget::Gadget.add(build_id, 240572,
                      constraints: ["ebx is the GOT address of libc", "[esp+0x30] == NULL"],
                      effect: "execve(\"/bin/sh\", esp+0x30, environ)")
OneGadget::Gadget.add(build_id, 240579,
                      constraints: ["ebx is the GOT address of libc", "[esp+0x34] == NULL"],
                      effect: "execve(\"/bin/sh\", esp+0x34, environ)")
OneGadget::Gadget.add(build_id, 240614,
                      constraints: ["ebx is the GOT address of libc", "[eax] == NULL || eax == NULL", "[[esp]] == NULL || [esp] == NULL"],
                      effect: "execve(\"/bin/sh\", eax, [esp])")
OneGadget::Gadget.add(build_id, 240615,
                      constraints: ["ebx is the GOT address of libc", "[[esp]] == NULL || [esp] == NULL", "[[esp+0x4]] == NULL || [esp+0x4] == NULL"],
                      effect: "execve(\"/bin/sh\", [esp], [esp+0x4])")
OneGadget::Gadget.add(build_id, 400356,
                      constraints: ["ebx is the GOT address of libc", "eax == NULL"],
                      effect: "execl(\"/bin/sh\", eax)")
OneGadget::Gadget.add(build_id, 400357,
                      constraints: ["ebx is the GOT address of libc", "[esp] == NULL"],
                      effect: "execl(\"/bin/sh\", [esp])")


text:
This is brand-new software. I've tested it minimally before pushing to Github. Do not
expect signatures and layout to be consistent until this note disappears.

## Requirements

Linux >= 2.6.24 with:

    CONFIG_NAMESPACES=y
    CONFIG_UTS_NS=y
    CONFIG_IPC_NS=y
    CONFIG_PID_NS=y
    CONFIG_NET_NS=y (eventually)

Root or CAP_SYS_ADMIN privileges. Using setcap on a binary may not be safe on a multi-user
system since input checking isn't very thorough.

## Build

    make
    make test
    make clean
    make binaries

## Example

If busybox is installed, this should work

    sudo ./nschroot /bin /busybox ls /

    mkdir -p /tmp/root
    cp -a /bin/busybox /tmp/root
    touch /tmp/root/foobar
    go build -o nschroot nschroot.go && sudo ./nschroot /tmp/root /busybox ls

To use the 'cgroup' utility to put a process into a cgroup:

    sudo ./cgroup -name awesome -program /usr/bin/touch -env bar=baz -- /tmp/foo

## TODO

* 'contain' utility that executes inside a namespaced/cgrouped container
* capabilities helpers
* veth setup

## History

* 2013-03-25: 'nschroot' and 'cgroup' are working
* 2013-02-19: nschroot seems to work fine as root. Cgroups aren't there yet, but I should have a workable API soon.

## Author

Al Tobey <tobert@gmail.com> @AlTobey

## License

Copyright 2013 Albert P Tobey.  All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.


text:
/*
 * Electric Fence - Red-Zone memory allocator.
 * Bruce Perens, 1988, 1993
 *
 * This is a special version of malloc() and company for debugging software
 * that is suspected of overrunning or underrunning the boundaries of a
 * malloc buffer, or touching free memory.
 *
 * It arranges for each malloc buffer to be followed (or preceded)
 * in the address space by an inaccessable virtual memory page,
 * and for free memory to be inaccessable. If software touches the
 * inaccessable page, it will get an immediate segmentation
 * fault. It is then trivial to uncover the offending code using a debugger.
 *
 * An advantage of this product over most malloc debuggers is that this one
 * detects reading out of bounds as well as writing, and this one stops on
 * the exact instruction that causes the error, rather than waiting until the
 * next boundary check.
 *
 * There is one product that debugs malloc buffer overruns
 * better than Electric Fence: "Purify" from Purify Systems, and that's only
 * a small part of what Purify does. I'm not affiliated with Purify, I just
 * respect a job well done.
 *
 * This version of malloc() should not be linked into production software,
 * since it tremendously increases the time and memory overhead of malloc().
 * Each malloc buffer will consume a minimum of two virtual memory pages,
 * this is 16 kilobytes on many systems. On some systems it will be necessary
 * to increase the amount of swap space in order to debug large programs that
 * perform lots of allocation, because of the per-buffer overhead.
 */
#include "efence.h"
#include <stdlib.h>
#include <unistd.h>
#include <memory.h>
#include <string.h>
#include <pthread.h>
#include <stdio.h>
#include <stdint.h>

extern C_LINKAGE void * ef_malloc(size_t size);
extern C_LINKAGE void ef_free(void * address);
extern C_LINKAGE void * ef_memalign(size_t alignment, size_t userSize);
extern C_LINKAGE void * ef_calloc(size_t nelem, size_t elsize);
extern C_LINKAGE void * ef_valloc (size_t size);
extern C_LINKAGE void * ef_realloc(void * oldBuffer, size_t newSize);
extern C_LINKAGE void ef_init(void);

#ifdef	malloc
#undef	malloc
#endif

#ifdef	calloc
#undef	calloc
#endif

static const char	version[] = "\n  Electric Fence 2.1"
 " Copyright (C) 1987-1998 Bruce Perens.\n";

/*
 * MEMORY_CREATION_SIZE is the amount of memory to get from the operating
 * system at one time. We'll break that memory down into smaller pieces for
 * malloc buffers. One megabyte is probably a good value.
 */
#define			MEMORY_CREATION_SIZE	10* 1024 * 1024

/*
 * Enum Mode indicates the status of a malloc buffer.
 */
enum _Mode {
	NOT_IN_USE = 0,	/* Available to represent a malloc buffer. */
	FREE,		/* A free buffer. */
	ALLOCATED,	/* A buffer that is in use. */
	PROTECTED,	/* A freed buffer that can not be allocated again. */
	INTERNAL_USE	/* A buffer used internally by malloc(). */
};
typedef enum _Mode	Mode;

/*
 * Struct Slot contains all of the information about a malloc buffer except
 * for the contents of its memory.
 */
struct _Slot {
	void *		userAddress;
	void *		internalAddress;
	size_t		userSize;
	size_t		internalSize;
	Mode		mode;
};
typedef struct _Slot	Slot;

 /*
 * EF_DISABLE_BANNER is a global variable used to control whether
 * Electric Fence prints its usual startup message.  If the value is
 * -1, it will be set from the environment default to 0 at run time.
 */
int            EF_DISABLE_BANNER = 1;

/*
 * EF_ALIGNMENT is a global variable used to control the default alignment
 * of buffers returned by malloc(), calloc(), and realloc(). It is all-caps
 * so that its name matches the name of the environment variable that is used
 * to set it. This gives the programmer one less name to remember.
 * If the value is -1, it will be set from the environment or sizeof(int)
 * at run time.
 */
int		EF_ALIGNMENT = 8;

/*
 * EF_PROTECT_FREE is a global variable used to control the disposition of
 * memory that is released using free(). It is all-caps so that its name
 * matches the name of the environment variable that is used to set it.
 * If its value is greater non-zero, memory released by free is made
 * inaccessable and never allocated again. Any software that touches free
 * memory will then get a segmentation fault. If its value is zero, freed
 * memory will be available for reallocation, but will still be inaccessable
 * until it is reallocated.
 * If the value is -1, it will be set from the environment or to 0 at run-time.
 */
int		EF_PROTECT_FREE = -1;

/*
 * EF_PROTECT_BELOW is used to modify the behavior of the allocator. When
 * its value is non-zero, the allocator will place an inaccessable page
 * immediately _before_ the malloc buffer in the address space, instead
 * of _after_ it. Use this to detect malloc buffer under-runs, rather than
 * over-runs. It won't detect both at the same time, so you should test your
 * software twice, once with this value clear, and once with it set.
 * If the value is -1, it will be set from the environment or to zero at
 * run-time
 */
int		EF_PROTECT_BELOW = -1;

/*
 * EF_ALLOW_MALLOC_0 is set if Electric Fence is to allow malloc(0). I
 * trap malloc(0) by default because it is a common source of bugs.
 */
int		EF_ALLOW_MALLOC_0 = 0;

/*
 * EF_FREE_WIPES is set if Electric Fence is to wipe the memory content
 * of freed blocks.  This makes it easier to check if memory is freed or
 * not
 */
int            EF_FREE_WIPES = 1;

static int malloc_init =0;
/*

 * allocationList points to the array of slot structures used to manage the
 * malloc arena.
 */
static Slot *		allocationList = 0;

/*
 * allocationListSize is the size of the allocation list. This will always
 * be a multiple of the page size.
 */
static size_t		allocationListSize = 0;

/*
 * slotCount is the number of Slot structures in allocationList.
 */
static size_t		slotCount = 0;

/*
 * unUsedSlots is the number of Slot structures that are currently available
 * to represent new malloc buffers. When this number gets too low, we will
 * create new slots.
 */
static size_t		unUsedSlots = 0;

/*
 * slotsPerPage is the number of slot structures that fit in a virtual
 * memory page.
 */
static size_t		slotsPerPage = 0;

/*
 * internalUse is set when allocating and freeing the allocatior-internal
 * data structures.
 */
static int		internalUse = 0;

/*
 * noAllocationListProtection is set to tell malloc() and free() not to
 * manipulate the protection of the allocation list. This is only set in
 * realloc(), which does it to save on slow system calls, and in
 * allocateMoreSlots(), which does it because it changes the allocation list.
 */
static int		noAllocationListProtection = 0;

/*
 * bytesPerPage is set at run-time to the number of bytes per virtual-memory
 * page, as returned by Page_Size().
 */
static size_t		bytesPerPage = 0;

 /*
 * mutex to enable multithreaded operation
 */
static pthread_mutex_t mutex ;

static void lock() {
    /* reentrant mutex -see init  */
    pthread_mutex_lock(&mutex);
}

static void unlock() {
    pthread_mutex_unlock(&mutex);
}

/*
 * internalError is called for those "shouldn't happen" errors in the
 * allocator.
 */
static void
internalError(void)
{
	EF_Abort("Internal error in allocator.");
}

/*
 * initialize sets up the memory allocation arena and the run-time
 * configuration information.
 */
static void
initialize(void)
{
	size_t	size = MEMORY_CREATION_SIZE;
	size_t	slack;
	char *	string;
	Slot *	slot;

       if ( EF_DISABLE_BANNER == -1 ) {
               if ( (string = getenv("EF_DISABLE_BANNER")) != 0 )
                       EF_DISABLE_BANNER = atoi(string);
               else
                       EF_DISABLE_BANNER = 0;
       }

       if ( EF_DISABLE_BANNER == 0 )
               EF_Print(version);

	/*
	 * Import the user's environment specification of the default
	 * alignment for malloc(). We want that alignment to be under
	 * user control, since smaller alignment lets us catch more bugs,
	 * however some software will break if malloc() returns a buffer
	 * that is not word-aligned.
	 *
	 * I would like
	 * alignment to be zero so that we could catch all one-byte
	 * overruns, however if malloc() is asked to allocate an odd-size
	 * buffer and returns an address that is not word-aligned, or whose
	 * size is not a multiple of the word size, software breaks.
	 * This was the case with the Sun string-handling routines,
	 * which can do word fetches up to three bytes beyond the end of a
	 * string. I handle this problem in part by providing
	 * byte-reference-only versions of the string library functions, but
	 * there are other functions that break, too. Some in X Windows, one
	 * in Sam Leffler's TIFF library, and doubtless many others.
	 */
	if ( EF_ALIGNMENT == -1 ) {
		if ( (string = getenv("EF_ALIGNMENT")) != 0 )
			EF_ALIGNMENT = (size_t)atoi(string);
		else
			EF_ALIGNMENT = sizeof(int);
	}

	/*
	 * See if the user wants to protect the address space below a buffer,
	 * rather than that above a buffer.
	 */
	if ( EF_PROTECT_BELOW == -1 ) {
		if ( (string = getenv("EF_PROTECT_BELOW")) != 0 )
			EF_PROTECT_BELOW = (atoi(string) != 0);
		else
			EF_PROTECT_BELOW = 0;
	}

	/*
	 * See if the user wants to protect memory that has been freed until
	 * the program exits, rather than until it is re-allocated.
	 */
	if ( EF_PROTECT_FREE == -1 ) {
		if ( (string = getenv("EF_PROTECT_FREE")) != 0 )
			EF_PROTECT_FREE = (atoi(string) != 0);
		else
			EF_PROTECT_FREE = 0;
	}

	/*
	 * See if the user wants to allow malloc(0).
	 */
	if ( EF_ALLOW_MALLOC_0 == -1 ) {
		if ( (string = getenv("EF_ALLOW_MALLOC_0")) != 0 )
			EF_ALLOW_MALLOC_0 = (atoi(string) != 0);
		else
			EF_ALLOW_MALLOC_0 = 0;
	}

	/*
	 * See if the user wants us to wipe out freed memory.
	 */
	if ( EF_FREE_WIPES == -1 ) {
	        if ( (string = getenv("EF_FREE_WIPES")) != 0 )
	                EF_FREE_WIPES = (atoi(string) != 0);
	        else
	                EF_FREE_WIPES = 0;
	}

	/*
	 * Get the run-time configuration of the virtual memory page size.
 	 */
	bytesPerPage = Page_Size();

	/*
	 * Figure out how many Slot structures to allocate at one time.
	 */
	slotCount = slotsPerPage = bytesPerPage / sizeof(Slot);
	allocationListSize = bytesPerPage;

	if ( allocationListSize > size )
		size = allocationListSize;

	if ( (slack = size % bytesPerPage) != 0 )
		size += bytesPerPage - slack;

	/*
	 * Allocate memory, and break it up into two malloc buffers. The
	 * first buffer will be used for Slot structures, the second will
	 * be marked free.
	 */
	slot = allocationList = (Slot *)Page_Create(size);
	memset((char *)allocationList, 0, allocationListSize);

	slot[0].internalSize = slot[0].userSize = allocationListSize;
	slot[0].internalAddress = slot[0].userAddress = allocationList;
	slot[0].mode = INTERNAL_USE;
	if ( size > allocationListSize ) {
		slot[1].internalAddress = slot[1].userAddress
		 = ((char *)slot[0].internalAddress) + slot[0].internalSize;
		slot[1].internalSize
		 = slot[1].userSize = size - slot[0].internalSize;
		slot[1].mode = FREE;
	}

	/*
	 * Deny access to the free page, so that we will detect any software
	 * that treads upon free memory.
	 */
	Page_DenyAccess(slot[1].internalAddress, slot[1].internalSize);

	/*
	 * Account for the two slot structures that we've used.
	 */
	unUsedSlots = slotCount - 2;
}

/*
 * allocateMoreSlots is called when there are only enough slot structures
 * left to support the allocation of a single malloc buffer.
 */
static void
allocateMoreSlots(void)
{
	size_t	newSize = allocationListSize + bytesPerPage;
	void *	newAllocation;
	void *	oldAllocation = allocationList;

	Page_AllowAccess(allocationList, allocationListSize);
	noAllocationListProtection = 1;
	internalUse = 1;

	newAllocation = ef_malloc(newSize);
	memcpy(newAllocation, allocationList, allocationListSize);
	memset(&(((char *)newAllocation)[allocationListSize]), 0, bytesPerPage);

	allocationList = (Slot *)newAllocation;
	allocationListSize = newSize;
	slotCount += slotsPerPage;
	unUsedSlots += slotsPerPage;

	ef_free(oldAllocation);

	/*
	 * Keep access to the allocation list open at this point, because
	 * I am returning to memalign(), which needs that access.
 	 */
	noAllocationListProtection = 0;
	internalUse = 0;
}

/*
 * This is the memory allocator. When asked to allocate a buffer, allocate
 * it in such a way that the end of the buffer is followed by an inaccessable
 * memory page. If software overruns that buffer, it will touch the bad page
 * and get an immediate segmentation fault. It's then easy to zero in on the
 * offending code with a debugger.
 *
 * There are a few complications. If the user asks for an odd-sized buffer,
 * we would have to have that buffer start on an odd address if the byte after
 * the end of the buffer was to be on the inaccessable page. Unfortunately,
 * there is lots of software that asks for odd-sized buffers and then
 * requires that the returned address be word-aligned, or the size of the
 * buffer be a multiple of the word size. An example are the string-processing
 * functions on Sun systems, which do word references to the string memory
 * and may refer to memory up to three bytes beyond the end of the string.
 * For this reason, I take the alignment requests to memalign() and valloc()
 * seriously, and
 *
 * Electric Fence wastes lots of memory. I do a best-fit allocator here
 * so that it won't waste even more. It's slow, but thrashing because your
 * working set is too big for a system's RAM is even slower.
 */
extern C_LINKAGE void *
ef_memalign(size_t alignment, size_t userSize)
{
	register Slot *	slot;
	register size_t	count;
	Slot *		fullSlot = 0;
	Slot *		emptySlots[2];
	size_t		internalSize;
	size_t		slack;
	char *		address;

	if ( userSize == 0 && !EF_ALLOW_MALLOC_0 )
		EF_Abort("Allocating 0 bytes, probably a bug.");

	/*
	 * If EF_PROTECT_BELOW is set, all addresses returned by malloc()
	 * and company will be page-aligned.
 	 */
	if ( !EF_PROTECT_BELOW && alignment > 1 ) {
		if ( (slack = userSize % alignment) != 0 )
			userSize += alignment - slack;
	}

	/*
	 * The internal size of the buffer is rounded up to the next page-size
	 * boudary, and then we add another page's worth of memory for the
	 * dead page.
	 */
	internalSize = userSize + bytesPerPage;
	if ( (slack = internalSize % bytesPerPage) != 0 )
		internalSize += bytesPerPage - slack;

	/*
	 * These will hold the addresses of two empty Slot structures, that
	 * can be used to hold information for any memory I create, and any
	 * memory that I mark free.
	 */
	emptySlots[0] = 0;
	emptySlots[1] = 0;

	/*
	 * The internal memory used by the allocator is currently
	 * inaccessable, so that errant programs won't scrawl on the
	 * allocator's arena. I'll un-protect it here so that I can make
	 * a new allocation. I'll re-protect it before I return.
 	 */
	if ( !noAllocationListProtection )
		Page_AllowAccess(allocationList, allocationListSize);

	/*
	 * If I'm running out of empty slots, create some more before
	 * I don't have enough slots left to make an allocation.
	 */
	if ( !internalUse && unUsedSlots < 7 ) {
		allocateMoreSlots();
	}

	/*
	 * Iterate through all of the slot structures. Attempt to find a slot
	 * containing free memory of the exact right size. Accept a slot with
	 * more memory than we want, if the exact right size is not available.
	 * Find two slot structures that are not in use. We will need one if
	 * we split a buffer into free and allocated parts, and the second if
	 * we have to create new memory and mark it as free.
	 *
	 */

	for ( slot = allocationList, count = slotCount ; count > 0; count-- ) {
		if ( slot->mode == FREE
		 && slot->internalSize >= internalSize ) {
			if ( !fullSlot
			 ||slot->internalSize < fullSlot->internalSize){
				fullSlot = slot;
				if ( slot->internalSize == internalSize
				 && emptySlots[0] )
					break;	/* All done, */
			}
		}
		else if ( slot->mode == NOT_IN_USE ) {
			if ( !emptySlots[0] )
				emptySlots[0] = slot;
			else if ( !emptySlots[1] )
				emptySlots[1] = slot;
			else if ( fullSlot
			 && fullSlot->internalSize == internalSize )
				break;	/* All done. */
		}
		slot++;
	}
	if ( !emptySlots[0] )
		internalError();

	if ( !fullSlot ) {
		/*
		 * I get here if I haven't been able to find a free buffer
		 * with all of the memory I need. I'll have to create more
		 * memory. I'll mark it all as free, and then split it into
		 * free and allocated portions later.
		 */
		size_t	chunkSize = MEMORY_CREATION_SIZE;

		if ( !emptySlots[1] )
			internalError();

		if ( chunkSize < internalSize )
			chunkSize = internalSize;

		if ( (slack = chunkSize % bytesPerPage) != 0 )
			chunkSize += bytesPerPage - slack;

		/* Use up one of the empty slots to make the full slot. */
		fullSlot = emptySlots[0];
		emptySlots[0] = emptySlots[1];
		fullSlot->internalAddress = Page_Create(chunkSize);
		fullSlot->internalSize = chunkSize;
		fullSlot->mode = FREE;
		unUsedSlots--;
	}

	/*
	 * If I'm allocating memory for the allocator's own data structures,
	 * mark it INTERNAL_USE so that no errant software will be able to
	 * free it.
	 */
	if ( internalUse )
		fullSlot->mode = INTERNAL_USE;
	else
		fullSlot->mode = ALLOCATED;

	/*
	 * If the buffer I've found is larger than I need, split it into
	 * an allocated buffer with the exact amount of memory I need, and
	 * a free buffer containing the surplus memory.
	 */
	if ( fullSlot->internalSize > internalSize ) {
		emptySlots[0]->internalSize
		 = fullSlot->internalSize - internalSize;
		emptySlots[0]->internalAddress
		 = ((char *)fullSlot->internalAddress) + internalSize;
		emptySlots[0]->mode = FREE;
		fullSlot->internalSize = internalSize;
		unUsedSlots--;
	}

	if ( !EF_PROTECT_BELOW ) {
		/*
		 * Arrange the buffer so that it is followed by an inaccessable
		 * memory page. A buffer overrun that touches that page will
		 * cause a segmentation fault.
		 */
		address = (char *)fullSlot->internalAddress;

		/* Set up the "live" page. */
		if ( internalSize - bytesPerPage > 0 )
				Page_AllowAccess(
				 fullSlot->internalAddress
				,internalSize - bytesPerPage);

		address += internalSize - bytesPerPage;

		/* Set up the "dead" page. */
		Page_DenyAccess(address, bytesPerPage);

		/* Figure out what address to give the user. */
		address -= userSize;
	}
	else {	/* EF_PROTECT_BELOW != 0 */
		/*
		 * Arrange the buffer so that it is preceded by an inaccessable
		 * memory page. A buffer underrun that touches that page will
		 * cause a segmentation fault.
		 */
		address = (char *)fullSlot->internalAddress;

		/* Set up the "dead" page. */
		Page_DenyAccess(address, bytesPerPage);

		address += bytesPerPage;

		/* Set up the "live" page. */
		if ( internalSize - bytesPerPage > 0 )
			Page_AllowAccess(address, internalSize - bytesPerPage);
	}

	fullSlot->userAddress = address;
	fullSlot->userSize = userSize;

	/*
	 * Make the pool's internal memory inaccessable, so that the program
	 * being debugged can't stomp on it.
	 */
	if ( !internalUse )
		Page_DenyAccess(allocationList, allocationListSize);

	return address;
}

/*
 * Find the slot structure for a user address.
 */
static Slot *
slotForUserAddress(void * address)
{
	register Slot *	slot = allocationList;
	register size_t	count = slotCount;

	for ( ; count > 0; count-- ) {
		if ( slot->userAddress == address )
			return slot;
		slot++;
	}

	return 0;
}

/*
 * Find the slot structure for an internal address.
 */
static Slot *
slotForInternalAddress(void * address)
{
	register Slot *	slot = allocationList;
	register size_t	count = slotCount;

	for ( ; count > 0; count-- ) {
		if ( slot->internalAddress == address )
			return slot;
		slot++;
	}
	return 0;
}

/*
 * Given the internal address of a buffer, find the buffer immediately
 * before that buffer in the address space. This is used by free() to
 * coalesce two free buffers into one.
 */
static Slot *
slotForInternalAddressPreviousTo(void * address)
{
	register Slot *	slot = allocationList;
	register size_t	count = slotCount;

	for ( ; count > 0; count-- ) {
		if ( ((char *)slot->internalAddress)
		 + slot->internalSize == address )
			return slot;
		slot++;
	}
	return 0;
}

extern C_LINKAGE void
ef_free(void * address)
{
	Slot *	slot;
	Slot *	previousSlot = 0;
	Slot *	nextSlot = 0;

    //printf(" ::free %p \n",address);
    lock();

    if ( address == 0 ) {
            unlock();
            return;
    }

	if ( allocationList == 0 )
		EF_Abort("free() called before first malloc().");

	if ( !noAllocationListProtection )
		Page_AllowAccess(allocationList, allocationListSize);

	slot = slotForUserAddress(address);

	if ( !slot )
		EF_Abort("free(%a): address not from malloc().", address);

	if ( slot->mode != ALLOCATED ) {
		if ( internalUse && slot->mode == INTERNAL_USE )
			/* Do nothing. */;
		else {
			EF_Abort(
			 "free(%a): freeing free memory."
			,address);
		}
	}

	if ( EF_PROTECT_FREE )
		slot->mode = PROTECTED;
	else
		slot->mode = FREE;

       if ( EF_FREE_WIPES )
               memset(slot->userAddress, 0xbd, slot->userSize);

	previousSlot = slotForInternalAddressPreviousTo(slot->internalAddress);
	nextSlot = slotForInternalAddress(
	 ((char *)slot->internalAddress) + slot->internalSize);

	if ( previousSlot
	 && (previousSlot->mode == FREE || previousSlot->mode == PROTECTED) ) {
		/* Coalesce previous slot with this one. */
		previousSlot->internalSize += slot->internalSize;
		if ( EF_PROTECT_FREE )
			previousSlot->mode = PROTECTED;

		slot->internalAddress = slot->userAddress = 0;
		slot->internalSize = slot->userSize = 0;
		slot->mode = NOT_IN_USE;
		slot = previousSlot;
		unUsedSlots++;
	}
	if ( nextSlot
	 && (nextSlot->mode == FREE || nextSlot->mode == PROTECTED) ) {
		/* Coalesce next slot with this one. */
		slot->internalSize += nextSlot->internalSize;
		nextSlot->internalAddress = nextSlot->userAddress = 0;
		nextSlot->internalSize = nextSlot->userSize = 0;
		nextSlot->mode = NOT_IN_USE;
		unUsedSlots++;
	}

	slot->userAddress = slot->internalAddress;
	slot->userSize = slot->internalSize;

	/*
	 * Free memory is _always_ set to deny access. When EF_PROTECT_FREE
	 * is true, free memory is never reallocated, so it remains access
	 * denied for the life of the process. When EF_PROTECT_FREE is false,
	 * the memory may be re-allocated, at which time access to it will be
	 * allowed again.
	 */
	Page_DenyAccess(slot->internalAddress, slot->internalSize);

	if ( !noAllocationListProtection )
		Page_DenyAccess(allocationList, allocationListSize);

        unlock();
}

extern C_LINKAGE void *
ef_realloc(void * oldBuffer, size_t newSize)
{
	void *	newBuffer = ef_malloc(newSize);

        lock();

	if ( oldBuffer ) {
		size_t	size;
		Slot *	slot;

		Page_AllowAccess(allocationList, allocationListSize);
		noAllocationListProtection = 1;

		slot = slotForUserAddress(oldBuffer);

		if ( slot == 0 )
			EF_Abort(
			 "realloc(%a, %d): address not from malloc()."
			,oldBuffer
			,newSize);

		if ( newSize < (size = slot->userSize) )
			size = newSize;

		if ( size > 0 )
			memcpy(newBuffer, oldBuffer, size);

		ef_free(oldBuffer);
		noAllocationListProtection = 0;
		Page_DenyAccess(allocationList, allocationListSize);

		if ( size < newSize )
			memset(&(((char *)newBuffer)[size]), 0, newSize - size);

		/* Internal memory was re-protected in free() */
	}
	unlock();

	return newBuffer;
}

extern C_LINKAGE void *
ef_malloc(size_t size)
{

     if  ( malloc_init == 0 ){
            ef_init();
     }

     void  *allocation;

    lock();
    allocation=ef_memalign(EF_ALIGNMENT, size);
    /* put 0xaa into the memset to find uninit issues */
    memset(allocation,0xaa,size);
    #if 0
    int i;
    uint8_t *p=(uint8_t *)allocation;
    for (i=0; i<size; i++) {
        p[i]=(rand()&0xff);
    }
    #endif

    unlock();
    //printf(":: alloc %p %d \n",allocation,(int)size);
	return allocation;
}

extern C_LINKAGE void *
ef_calloc(size_t nelem, size_t elsize)
{
	size_t	size = nelem * elsize;
        void * allocation;

        lock();

        allocation = ef_malloc(size);
        memset(allocation, 0, size);
        unlock();

	return allocation;
}

/*
 * This will catch more bugs if you remove the page alignment, but it
 * will break some software.
 */
extern C_LINKAGE void *
ef_valloc (size_t size)
{
        void * allocation;

        lock();
        allocation= ef_memalign(bytesPerPage, size);
        unlock();

        return allocation;
}

#define REPLACE_MALLOC

#ifdef REPLACE_MALLOC

extern C_LINKAGE void
free(void * address)
{
    ef_free(address);
}

extern C_LINKAGE void *
realloc(void * oldBuffer, size_t newSize)
{
    return (ef_realloc(oldBuffer, newSize));
}

extern C_LINKAGE void *
malloc(size_t size)
{
    return (ef_malloc(size));
}

extern C_LINKAGE void *
calloc(size_t nelem, size_t elsize)
{
    return (ef_calloc(nelem, elsize));
}

extern C_LINKAGE int
posix_memalign(void **memptr, size_t alignment, size_t size)
{
    *memptr=ef_malloc(size);
    return(0);
}

/*
 * This will catch more bugs if you remove the page alignment, but it
 * will break some software.
 */
extern C_LINKAGE void *
valloc (size_t size)
{
    return (ef_valloc(size));

}
#endif

extern C_LINKAGE void ef_init(void ){

    if  ( malloc_init == 0 ){
        malloc_init=1;
        pthread_mutexattr_t Attr;

        pthread_mutexattr_init(&Attr);
        pthread_mutexattr_settype(&Attr, PTHREAD_MUTEX_RECURSIVE);

        if ( pthread_mutex_init(&mutex, &Attr) != 0 ){
            exit(-1);
        }
        initialize();
    }

}


text:
from numpy import dot, zeros, ix_, eye, triu
from numpy.linalg import cholesky, LinAlgError
from ..core.logio import logger
from ..core.material import Material

class AnisotropicElasticMaterial(Material):
    name = "elastic2"

    def __init__(self, **parameters):
        """Set up the Elastic material"""
        # Define mapping from 21 elastic parameters to location
        # in parameter array
        param_names = ['C{0}{1}'.format(i+1,j+1)
                       for i in range(6) for j in range(i,6)]

        # Create the parameter array and check inputs
        self.params = zeros(len(param_names))
        for (i, name) in enumerate(param_names):
            self.params[i] = parameters.pop(name, 0.)
        if parameters:
            unused = ', '.join(list(parameters.keys()))
            logger.warning('The following parameters were '
                           'unused {0}'.format(unused))

        # check if C is positive definite
        C = self.form_stiff(self.params)
        try:
            cholesky(C)
        except LinAlgError:
            raise ValueError('elastic stiffness not positive definite')

    @staticmethod
    def form_stiff(cij):
        C = zeros((6,6))
        i = 0
        for k in range(6):
            j = 6 - k
            C[k, k:] = cij[i:i+j]
            i += j
        return C + triu(C,k=1).T

    def eval(self, time, dtime, temp, dtemp, F0, F,
             stran, d, stress, statev, **kwargs):
        """Compute updated stress given strain increment"""

        # elastic stiffness
        ddsdde = self.form_stiff(self.params)

        # stress update
        stress = dot(ddsdde, stran)

        return stress, statev, ddsdde