text:
'use strict'

const _ = require('lodash')

// const eyes = require('eyes'), p = eyes.inspect.bind(eyes)

/**
 * Base class for [`ClientError`]{@link module:classeur-api-client.ClientError} and [`ServerError`]{@link module:classeur-api-client.ServerError} objects.
 * @deprecated  You should never need to construct one of these directly they will be provided to callbacks for REST API operations as the first argument if they occur.
 * @extends [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
 * @memberof module:classeur-api-client
 */
class ErrorBase extends Error {
	/** @lends module:classeur-api-client.ErrorBase */
	constructor(error, data, response) {
		if ( _.isString(error) ) {
			error = new Error(error)
		}
		if ( ! _.isError(error) ) {
			throw new Error(`Expected string or Error object, got ${error} instead`)
		}

		super(error)
		let message = _.replace(this.message, /^\s*Error:\s*/, '')
		_.merge(this, data)
		_.merge(this, error)
		this.message = message

		if (response) {
			/**
			 * JSON decoding failures will raise a {@link module:classeur-api-client.ClientError} instead.
			 * This field is only present if its value could be derived from the error object returned from the REST client.
			 * @summary The JSON-decoded response sent back from the server with the error.
			 * @deprecated  This is usually not useful the properties `reason` and `status` are usually of more interest than `response`, and they are directly readable from instances of this class.
			 * @type {Object?}
			 * @instance
			 * @readonly
			 */
			this.response = response
		}

		if ( data ) {
			/**
			 * JSON decoding failures will raise a {@link module:classeur-api-client.ClientError} instead.
			 * This field is only present if its value could be derived from the error object returned from the REST client.
			 * @summary The JSON-decoded response-data sent back from the server with the error.
			 * @deprecated  This is usually not useful the properties `reason` and `status` are usually all that is contained in `data`, and they are directly readable from instances of this class.
			 * @type {Object?}
			 * @instance
			 * @readonly
			 */
			this.data = data
		}

		if ( _.property('body.reason')(error) ) {
			/**
			 * This is usually the best source for detailed failure/debugging information.
			 * This field is only present if its value could be derived from the error object returned from the REST client.
			 * @summary Information sent back by the server indicating why a request failed.
			 * @type {String?}
			 * @instance
			 * @readonly
			 */
			this.reason = error.body.reason
		}

		if ( _.property('body.error')(error) ) {
		 	/**
		 	 * This field is only present if its value could be derived from the error object returned from the REST client.
			 * Usually a short word or phrase explaining what a given error code means in HTTP convention.
		 	 * @summary English version of [ServerError#status]{@link module:classeur-api-client.ServerError#status}.
		 	 * @type {String?}
		 	 * @instance
		 	 * @readonly
		 	 */
		 	this.shortReason = error.body.error
		}
	}
}

// Bizarre link formatting for the @extends argument is due to jsdoc parser limitations:
// it doesn't support spaces in @extends, even if those spaces are in a @link location field.
/**
 * Object representation of an error that occurred on the server while performing a REST API operation.
 * This is a thin wrapper around a [flashheart](https://github.com/bbc/flashheart) error object, and exists as a separate class only to deliniate server-caused errors from client-caused errors.
 * @deprecated  You should never need to construct one of these directly they will be provided to callbacks for REST API operations as the first argument if they occur.
 * @extends [ErrorBase](./module-classeur-api-client.ErrorBase.html)
 * @memberof module:classeur-api-client
 * @see The [flashheart documentation](https://github.com/bbc/flashheart#errors) for more info on possible Error contents.
 * @example
 * const ServerError = require('classeur-api-client').ServerError
 * myClient.getFile('nonexistent', (error) => {
 *     if ( error instanceof ServerError ) {
 *         console.log(error.message) // e.g. 'Server error: Received HTTP code 403 for GET https:// ...'
 *         console.log(error.reason) // e.g. 'file_is_not_readable'
 *         console.log(error.status) // e.g. 403
 *         throw error
 *     }
 * })
 */
class ServerError extends ErrorBase {
	/** @lends module:classeur-api-client.ServerError */
	constructor(error, body, response) {
		if ( ! _.property('statusCode')(error) ) {
			throw new Error(`Expected error object to have 'statusCode' property: ${error}`)
		}
		if ( ! _.isNumber(error.statusCode) ) {
			throw new Error(`Expected error.statusCode to be numeric, got ${error.statusCode} instead`)
		}
		super(error, body, response)
		this.message = 'Server error: ' + this.message
		/**
		 * If headers were returned from the server with the error, this object will contain their contents. It is supplied directly by the flashheart REST client library.
		 * @memberOf module:classeur-api-client.ServerError
		 * @member {Object} headers
		 * @instance
		 * @readonly
		 * @see The [flashheart documentation]{@link https://github.com/bbc/flashheart#errors} for more information about this field's contents.
		 */

		/**
		 * HTTP status code of the error.
		 * @type {Number}
		 * @instance
		 * @readonly
		 */
		this.status = error.statusCode
	}
}

/**
 * Object representation of an error that occurred on the client during or after the processing REST API operation.
 * Example causes if a client error (and valid values for the `message` property) include:
 * - Request aborted
 * - Request timed out
 * - Corrupt/non-JSON-decodable content received
 *
 * ClientError instances are usually thin wrappers around [flashheart](https://github.com/bbc/flashheart) error objects, and exist only to deliniate server-caused errors from client-caused errors. ClientErrors may not contain all/most error fields supplied by flashheart, though, since ClientErrors may occur before error metadata is returned from the server.
 * @deprecated You should never need to construct one of these directly they will be provided to callbacks for REST API operations as the first argument if they occur.
 * @extends [ErrorBase](./module-classeur-api-client.ErrorBase.html)
 * @memberof module:classeur-api-client
 * @see The [flashheart documentation](https://github.com/bbc/flashheart#errors) for more info on possible Error contents.
 * @example
 * const ClientError = require('classeur-api-client').ClientError
 * myClient.getFile('nonexistent', (error) => {
 *     if ( error instanceof ClientError ) {
 *         console.log(error.message) // e.g. 'JSON decoding failed!'
 *         throw error
 *     }
 * })
 */
class ClientError extends ErrorBase {
	/** @lends module:classeur-api-client.ClientError*/
	constructor(error, body, response, clntimeout) {
		super(error, body, response)
		this.message = 'Client error: ' + this.message

		if ( this.message.includes('ETIMEDOUT') ) {
			/**
			 * If a timeout occurred, this property will be set to the timeout threshold that was exceeded, in milliseconds. This property will only be set if a ClientError occurred due to a timeout.
			 * @type {Number?}
			 * @instance
			 * @readonly
			 */
		    this.timeout = clntimeout
		}
	}
}

module.exports.ServerError = ServerError
module.exports.ClientError = ClientError


text:
resultpath = '\\raspberry\d_work\IFCB1\ifcb_data_mvco_jun06\Manual_fromClass\';
load([resultpath 'manual_list']) %load the manual list detailing annotate mode for each sample file
filelist = manual_list(2:end,1);

class2use_sub4new = {'not_ciliate'    'ciliate_mix'    'tintinnid'    'Myrionecta'    'Laboea'    'S_conicum'...
    'tiarina'    'strombidium1'    'Scaudatum'    'Tontonia' 'strombidium2'    'S_wulffi'    'S_inclinatum'...
    'Euplotes'    'Didinium'    'Leegaardiella'    'Sol'    'strawberry'    'S_capitatum'};

for ii = 1:length(filelist),
    disp(filelist{ii})
    clear class2use_sub4
    load([resultpath filelist{ii}], 'class2use_sub4');
    if exist('class2use_sub4', 'var'),
        class2use_sub4 = class2use_sub4new;
        save([resultpath filelist{ii}], 'class2use_sub4', '-append');
    end;
end;

redpajama_set_name: RedPajamaGithub


text:
namespace rx
{

DisplayVkWin32::DisplayVkWin32(const egl::DisplayState &state)
    : DisplayVk(state), mWindowClass(NULL), mDummyWindow(nullptr)
{}

DisplayVkWin32::~DisplayVkWin32() {}

void DisplayVkWin32::terminate()
{
    if (mDummyWindow)
    {
        DestroyWindow(mDummyWindow);
        mDummyWindow = nullptr;
    }
    if (mWindowClass)
    {
        if (!UnregisterClassA(reinterpret_cast<const char *>(mWindowClass),
                              GetModuleHandle(nullptr)))
        {
            WARN() << "Failed to unregister ANGLE window class: " << gl::FmtHex(mWindowClass);
        }
        mWindowClass = NULL;
    }

    DisplayVk::terminate();
}

bool DisplayVkWin32::isValidNativeWindow(EGLNativeWindowType window) const
{
    return (IsWindow(window) == TRUE);
}

SurfaceImpl *DisplayVkWin32::createWindowSurfaceVk(const egl::SurfaceState &state,
                                                   EGLNativeWindowType window)
{
    return new WindowSurfaceVkWin32(state, window);
}

egl::Error DisplayVkWin32::initialize(egl::Display *display)
{
    ANGLE_TRY(DisplayVk::initialize(display));

    HINSTANCE hinstance = GetModuleHandle(nullptr);

    std::ostringstream stream;
    stream << "ANGLE DisplayVkWin32 " << gl::FmtHex(display) << " Intermediate Window Class";

    const LPSTR idcArrow  = MAKEINTRESOURCEA(32512);
    std::string className = stream.str();
    WNDCLASSA wndClass;
    if (!GetClassInfoA(hinstance, className.c_str(), &wndClass))
    {
        WNDCLASSA intermediateClassDesc     = {};
        intermediateClassDesc.style         = CS_OWNDC;
        intermediateClassDesc.lpfnWndProc   = DefWindowProcA;
        intermediateClassDesc.cbClsExtra    = 0;
        intermediateClassDesc.cbWndExtra    = 0;
        intermediateClassDesc.hInstance     = GetModuleHandle(nullptr);
        intermediateClassDesc.hIcon         = nullptr;
        intermediateClassDesc.hCursor       = LoadCursorA(nullptr, idcArrow);
        intermediateClassDesc.hbrBackground = 0;
        intermediateClassDesc.lpszMenuName  = nullptr;
        intermediateClassDesc.lpszClassName = className.c_str();
        mWindowClass                        = RegisterClassA(&intermediateClassDesc);
        if (!mWindowClass)
        {
            return egl::EglNotInitialized()
                   << "Failed to register intermediate OpenGL window class \"" << className.c_str()
                   << "\":" << gl::FmtErr(HRESULT_CODE(GetLastError()));
        }
    }

    mDummyWindow =
        CreateWindowExA(0, reinterpret_cast<const char *>(mWindowClass), "ANGLE Dummy Window",
                        WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
                        CW_USEDEFAULT, nullptr, nullptr, nullptr, nullptr);
    if (!mDummyWindow)
    {
        return egl::EglNotInitialized() << "Failed to create dummy OpenGL window.";
    }

    VkSurfaceKHR surfaceVk;
    VkWin32SurfaceCreateInfoKHR info = {VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR, nullptr, 0,
                                        GetModuleHandle(nullptr), mDummyWindow};

    VkInstance instance         = mRenderer->getInstance();
    VkPhysicalDevice physDevice = mRenderer->getPhysicalDevice();

    if (vkCreateWin32SurfaceKHR(instance, &info, nullptr, &surfaceVk) != VK_SUCCESS)
    {
        return egl::EglNotInitialized() << "vkCreateWin32SurfaceKHR failed";
    }
    uint32_t surfaceFormatCount;

    if (vkGetPhysicalDeviceSurfaceFormatsKHR(physDevice, surfaceVk, &surfaceFormatCount, nullptr) !=
        VK_SUCCESS)
    {
        return egl::EglNotInitialized() << "vkGetPhysicalDeviceSurfaceFormatsKHR failed";
    }
    mSurfaceFormats.resize(surfaceFormatCount);
    if (vkGetPhysicalDeviceSurfaceFormatsKHR(physDevice, surfaceVk, &surfaceFormatCount,
                                             mSurfaceFormats.data()) != VK_SUCCESS)
    {
        return egl::EglNotInitialized() << "vkGetPhysicalDeviceSurfaceFormatsKHR (2nd) failed";
    }
    vkDestroySurfaceKHR(instance, surfaceVk, nullptr);

    DestroyWindow(mDummyWindow);
    mDummyWindow = nullptr;

    return egl::NoError();
}

egl::ConfigSet DisplayVkWin32::generateConfigs()
{
    constexpr GLenum kColorFormats[] = {GL_RGB565, GL_BGRA8_EXT, GL_BGRX8_ANGLEX};
    return egl_vk::GenerateConfigs(kColorFormats, egl_vk::kConfigDepthStencilFormats, this);
}

bool DisplayVkWin32::checkConfigSupport(egl::Config *config)
{
    const vk::Format &formatVk = this->getRenderer()->getFormat(config->renderTargetFormat);
    VkFormat nativeFormat      = formatVk.vkImageFormat;

    // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
    // the surface has no preferred format.  Otherwise, at least one
    // supported format will be returned.
    if (mSurfaceFormats.size() == 1u && mSurfaceFormats[0].format == VK_FORMAT_UNDEFINED)
    {
        return true;
    }

    for (const VkSurfaceFormatKHR &surfaceFormat : mSurfaceFormats)
    {
        if (surfaceFormat.format == nativeFormat)
        {
            return true;
        }
    }

    return false;
}

const char *DisplayVkWin32::getWSIExtension() const
{
    return VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
}

bool IsVulkanWin32DisplayAvailable()
{
    return true;
}

DisplayImpl *CreateVulkanWin32Display(const egl::DisplayState &state)
{
    return new DisplayVkWin32(state);
}
}  // namespace rx


text:
///////////////////////////////////////////////////////////////////////////
//                                                                       //
// AliFemtoCorrFctn3DSpherical: a class to calculate 3D correlation      //
// for pairs of identical particles, binned in spherical coordinates     //
// (q_inv, phi, cos(theta))
//                                                                       //
///////////////////////////////////////////////////////////////////////////

#ifndef ALIFEMTOCORRFCTN3DSPHERICALEMCIC_H
#define ALIFEMTOCORRFCTN3DSPHERICALEMCIC_H

#include "AliFemtoCorrFctn.h"
#include "AliFemtoPairCut.h"
#include "TH3D.h"

class AliFemtoCorrFctn3DSphericalEMCIC : public AliFemtoCorrFctn{
public:
  AliFemtoCorrFctn3DSphericalEMCIC(char* title,
			      const int& nqbins, const float& QLo, const float& QHi,
			      const int& nphibins, const int& ncthetabins);
  AliFemtoCorrFctn3DSphericalEMCIC(const AliFemtoCorrFctn3DSphericalEMCIC& aCorrFctn);
  virtual ~AliFemtoCorrFctn3DSphericalEMCIC();

  AliFemtoCorrFctn3DSphericalEMCIC& operator=(const AliFemtoCorrFctn3DSphericalEMCIC& aCorrFctn);

  virtual AliFemtoString Report();
  virtual void AddRealPair( AliFemtoPair* aPair);
  virtual void AddMixedPair( AliFemtoPair* aPair);

  virtual void Finish();

  void WriteOutHistos();
  virtual TList* GetOutputList();

  void SetSpecificPairCut(AliFemtoPairCut* aCut);

 private:

  TH3D* fNumerator;         // numerator
  TH3D* fDenominator;       // denominator
  //EMCIC histograms:
  /*TH3D* fEnergyTotalReal;       // E1+E2 from real pairs
  TH3D* fEnergyMultReal;        // E1*E2
  TH3D* fPzMultReal;            // Pz1*Pz2
  TH3D* fPtMultReal;            // Pt1*Pt2  */
  TH3D* fEnergyTotalMix;       // E1+E2 from mixed pairs
  TH3D* fEnergyMultMix;        // E1*E2
  TH3D* fPzMultMix;            // Pz1*Pz2
  TH3D* fPtMultMix;            // Pt1*Pt2
  AliFemtoPairCut* fPairCut;    //! this is a PairCut specific to THIS CorrFctn, not the Analysis

#ifdef __ROOT__
  ClassDef(AliFemtoCorrFctn3DSphericalEMCIC, 1)
#endif
};

inline  void AliFemtoCorrFctn3DSphericalEMCIC::SetSpecificPairCut(AliFemtoPairCut* pc){fPairCut=pc;}

#endif


text:
#ifndef PHP_V8_NAMED_PROPERTY_HANDLER_CONFIGURATION_H
#define PHP_V8_NAMED_PROPERTY_HANDLER_CONFIGURATION_H

typedef struct _php_v8_named_property_handler_configuration_t php_v8_named_property_handler_configuration_t;

#include "php_v8_callbacks.h"
#include <v8.h>

extern "C" {
#include "php.h"

#ifdef ZTS
#include "TSRM.h"
#endif
}

extern zend_class_entry* php_v8_named_property_handler_configuration_class_entry;

inline php_v8_named_property_handler_configuration_t * php_v8_named_property_handler_configuration_fetch_object(zend_object *obj);

#define PHP_V8_NAMED_PROPERTY_HANDLER_FETCH(zv) php_v8_named_property_handler_configuration_fetch_object(Z_OBJ_P(zv))
#define PHP_V8_NAMED_PROPERTY_HANDLER_FETCH_INTO(pzval, into) php_v8_named_property_handler_configuration_t *(into) = PHP_V8_NAMED_PROPERTY_HANDLER_FETCH((pzval));

#define PHP_V8_EMPTY_NAMED_PROPERTY_MSG "NamedProperty" PHP_V8_EMPTY_HANDLER_MSG_PART
#define PHP_V8_CHECK_EMPTY_NAMED_PROPERTY_HANDLER_MSG(val, message) if (NULL == (val)->bucket) { PHP_V8_THROW_EXCEPTION(message); return; }
#define PHP_V8_CHECK_EMPTY_NAMED_PROPERTY_HANDLER(val) PHP_V8_CHECK_EMPTY_NAMED_PROPERTY_HANDLER_MSG((val), PHP_V8_EMPTY_NAMED_PROPERTY_MSG)

#define PHP_V8_NAMED_PROPERTY_HANDLER_FETCH_WITH_CHECK(pzval, into) \
    PHP_V8_NAMED_PROPERTY_HANDLER_FETCH_INTO(pzval, into); \
    PHP_V8_CHECK_EMPTY_NAMED_PROPERTY_HANDLER(into);

#define PHP_V8_NAMED_PROPERTY_HANDLER_STORE_ISOLATE(to_zval, from_isolate_zv) zend_update_property(php_v8_named_property_handler_configuration_class_entry, (to_zval), ZEND_STRL("isolate"), (from_isolate_zv));
#define PHP_V8_NAMED_PROPERTY_HANDLER_READ_ISOLATE(from_zval) zend_read_property(php_v8_named_property_handler_configuration_class_entry, (from_zval), ZEND_STRL("isolate"), 0, &rv)

typedef struct _php_v8_named_property_handler_configuration_t {
  v8::GenericNamedPropertyGetterCallback getter;
  v8::GenericNamedPropertySetterCallback setter;
  v8::GenericNamedPropertyQueryCallback query;
  v8::GenericNamedPropertyDeleterCallback deleter;
  v8::GenericNamedPropertyEnumeratorCallback enumerator;

  long flags;

  phpv8::CallbacksBucket *bucket;

  zval *gc_data;
  int   gc_data_count;

  zend_object std;
} php_v8_named_property_handler_configuration_t;

inline php_v8_named_property_handler_configuration_t * php_v8_named_property_handler_configuration_fetch_object(zend_object *obj) {
    return (php_v8_named_property_handler_configuration_t *)((char *)obj - XtOffsetOf(php_v8_named_property_handler_configuration_t, std));
}

PHP_MINIT_FUNCTION(php_v8_named_property_handler_configuration);

#endif //PHP_V8_NAMED_PROPERTY_HANDLER_CONFIGURATION_H


text:
id: known-issues
title: Known Issues
layout: docs
category: Guides
permalink: docs/known-issues.html
next: performance
---

### Missing Modules and Native Views

This is an initial release of React Native Android and therefore not all of the views present on iOS are released on Android. We are very much interested in the communities' feedback on the next set of modules and views for Open Source. Not all native views between iOS and Android have a 100% equivalent representation, here it will be necessary to use a counterpart eg using ProgressBar on Android in place of ActivityIndicator on iOS.

Our provisional plan for common views and modules includes:

#### Views

```
Swipe Refresh
Spinner
ART
Maps
Modal
Webview
```

#### Modules

```
Geo Location
Net Info
Camera Roll
App State
Dialog
Intent
Media
Pasteboard
PushNotificationIOS
Alert
```

### Some props are only supported on one platform

There are properties that work on one platform only, either because they can inherently only be supported on that platform or because they haven't been implemented on the other platforms yet. All of these are annotated with `@platform` in JS docs and have a small badge next to them on the website. See e.g. [Image](https://facebook.github.io/react-native/docs/image.html).

### Platform parity

There are known cases where the APIs could be made more consistent across iOS and Android:

- `<SwitchAndroid>` and `<SwitchIOS>` are very similar and should be unified to a single `<Switch>` component.
- `<AndroidViewPager>` (to be open sourced soon) and `<ScrollView pagingEnabled={true}>` on iOS do a similar thing. We might want to unify them to `<ViewPager>`.
- `alert()` needs Android support (once the Dialogs module is open sourced)
- It might be possible to bring `LinkingIOS` and `IntentAndroid` (to be open sourced) closer together.
- `ActivityIndicator` could render a native spinning indicator on both platforms (currently this is done using `ActivityIndicatorIOS` on iOS and `ProgressBarAndroid` on Android).
- `ProgressBar` could render a horizontal progress bar on both platforms (currently only supported on iOS via `ProgressViewIOS`).

### Publishing modules on Android

There is currently no easy way of publishing custom native modules on Android. Smooth work flow for contributors is important and this will be looked at very closely after the initial Open Source release. Of course the aim will be to streamline and optimize the process between iOS and Android as much as possible.

### Overlay view with opacity of 0 cannot be clicked through

There is a noted difference in the handling of Views with an opacity of 0 between iOS and Android. While iOS will allow these views to be clicked through and the View below will receive the touch input, for Android the touch will be blocked. This can be demonstrated in this example where it will only be possible to click the touchable on iOS.

```
<View style={{flex: 1}}>
  <TouchableOpacity onPress={() => alert('hi!')}>
    <Text>HELLO!</Text>
  </TouchableOpacity>

  <View style={{
    position: 'absolute',
    top: 0,
    left: 0,
    bottom: 0,
    right: 0,
    opacity: 0}} />
</View>
```

The behavior on Android is what you would expect from the web as well.  If you want to be able to click through an overlaying transparent view, you can set `pointerEvents='none'` on it.

### The `overflow` style property defaults to `hidden` and cannot be changed on Android

This is a result of how Android rendering works. This feature is not being worked on as it would be a significant undertaking and there are many more important tasks.

### No support for shadows on Android

We don't support shadows on Android currently. These are notoriously hard to implement as they require drawing outside of a view's bounds and Android's invalidation logic has a hard time with that. A possible solution is to use [elevation](https://developer.android.com/training/material/shadows-clipping.html), but more experimentation will be required.

### Layout-only nodes on Android

An optimization feature of the Android version of React Native is for views which only contribute to the layout to not have a native view, only their layout properties are propagated to their children views. This optimization is to provide stability in deep view hierarchies for React Native and is therefore enabled by default. Should you depend on a view being present or internal tests incorrectly detect a view is layout only it will be necessary to turn off this behavior. To do this, set `collapsable` to false as in this example:
```
<View collapsable={false}>
    ...
</View>
```

### Memory issues with PNG images

React Native Android depends on [Fresco](https://github.com/facebook/fresco) for loading and displaying images. Currently we have disabled downsampling because it is experimental, so you may run into memory issues when loading large PNG images.

### react-native init hangs

Try running `react-native init` with `--verbose` and see [#2797](https://github.com/facebook/react-native/issues/2797) for common causes.

### Text Input Border

The text input has by default a border at the bottom of its view. This border has its padding set by the background image provided by the system, and it cannot be changed. Solutions to avoid this is to either not set height explicitly, case in which the system will take care of displaying the border in the correct position, or to not display the border by setting underlineColor to transparent.


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of CelulaController
 *
 * @author Marks-Calderon
 */

namespace AE\ConfigurarBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Security\Core\SecurityContext;
use AE\DataBundle\Entity\Red;
use AE\DataBundle\Entity\Celula;
use AE\DataBundle\Entity\Ubicacion;

class CelulaController extends Controller {
    //put your code here

    public function viewAction(){

        return $this->render('AEConfigurarBundle:Default:celulas.html.twig');
    }

    public function editAction(){

    }

    public function saveAction()
    {
        $request = $this->get('request');
        $datos =$request->request->get('formulario');
        $return = array();

        $em = $this->getDoctrine()->getManager();

        $em->beginTransaction();

        try{

            $dis = $datos['distrito_lista'];

            $distrito = $em->getRepository('AEDataBundle:Ubigeos')->find($dis);

            $ubicacion = new Ubicacion();
            $ubicacion->setDireccion($datos['inputDireccion']);
            $ubicacion->setReferencia($datos['inputReferencia']);
            $ubicacion->setLatitud(0);
            $ubicacion->setLongitud(0);
            $ubicacion->setUbigeo($distrito);
            $em->persist($ubicacion);
            $em->flush();

            $red = $em->getRepository('AEDataBundle:Red')->find($datos['red_lista']);

            $c = new Celula();

            $c->setActivo(TRUE);
            $c->setDia($datos['dia']);
            $c->setHora($datos['hora']);
            $c->setFamilia($datos['familia']);

            $c->setIdRed($red);

            $c->setIdUbicacion($ubicacion);
            $c->setTelefono($datos['telefono']);
            $c->setTipo($datos['tipo']);

            $fechaConv_b = $datos['creacion'];

            $fechaConv_a = explode('/', $fechaConv_b, 3);

            $fecha = $fechaConv_a[2].'-'.$fechaConv_a[1].'-'.$fechaConv_a[0];
            $c->setFechaCreacion(new \DateTime($fecha));

            if($datos['lider_id'] != '-1')
            {

                $c->setLider($em->getRepository('AEDataBundle:Lider')->find($datos['lider_id']));

            }

            $em->persist($c);
            $em->flush();

            $em->commit();
            $em->clear();

            $return=array("responseCode"=>200, "greeting"=>"Ok");
        } catch (Exception $ex) {

            $em->rollback();
            $em->clear();
            $em->close();
            $return=array("responseCode"=>400, "greeting"=>"Ok");
        }

        return new JsonResponse($return);
    }

    public function deleteAction(){

    }
}


text:
//
//  BWMProductPutawayPostModel.h
//  BeautifulShop
//
//  Created by Bi Weiming on 15/6/15.
//  Copyright (c) 2015年 Bi Weiming. All rights reserved.
//

#import <Foundation/Foundation.h>

/**
 *  @brief  上下架类型
 */
typedef NS_ENUM(NSInteger, BWMProductPutawayPostModelType){
    /**
     *  @brief  上架
     */
    BWMProductPutawayPostModelTypeAdd,
    /**
     *  @brief  下架
     */
    BWMProductPutawayPostModelTypeDel
};

/**
 *  @brief  上下架Post请求Model
 */
@interface BWMProductPutawayPostModel : NSObject

@property (strong, nonatomic, readonly) NSString *userID;
@property (assign, nonatomic) BWMProductPutawayPostModelType type;
@property (strong, nonatomic, readonly) NSArray *productsID;

- (void)addProductID:(NSString *)productID;
- (NSDictionary *)postDictionary;

+ (NSString *)API;

+ (instancetype)modelWithType:(BWMProductPutawayPostModelType)type;

@end


text:
<!DOCTYPE HTML>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

123


text:
created: 2019-06-25
last updated: 2019-08-01
status: Dropped
title: Platforms and Strategies
authors:
  - katre
reviewers:
  - philwo (lead)
  - ishikhman
  - agoulti
discussion thread: https://groups.google.com/d/msg/bazel-dev/NjcyelfHvyA/n9Buk1mODQAJ
---

# Status

This proposal has been dropped due to being likely to confuse users. See the
[discussion thread](https://groups.google.com/d/msg/bazel-dev/NjcyelfHvyA/n9Buk1mODQAJ)
for more details.

# Background

Bazel currently has two different systems that select where a build action is
executed: [execution
platforms](https://docs.bazel.build/versions/master/platforms.html) and
[execution
strategies](https://docs.bazel.build/versions/master/user-manual.html#strategy-options).
Historically, these have not communicated: this leads to the situation where
they can mismatch, for example by selecting a local-only toolchain, but using
the "remote" execution strategy, or the opposite, where remote execution
platforms and toolchains are selected, but the "remote" strategy is not enabled.
Both of these situations lead to failed builds and confused users.

With the recent addition of [automatic execution strategy selection in Bazel
0.27](https://blog.bazel.build/2019/06/19/list-strategy.html), we now have a
chance to update this selection, and make both systems aware of each other.

# Proposal

This proposal calls for changes to both toolchain resolution, and to execution
strategy selection, in order for both systems to be aware of each other.

To facilitate these changes, a new attribute will be added to the `platform`
rule.

## Platform Rule

A new attribute, `spawn_strategy`, will be added to the `platform` rule, which
will take a list of strings. The contents of the list will be compared to the
names of the existing execution strategies (i.e., the allowed values for the
[`--spawn_strategy`](https://docs.bazel.build/versions/master/user-manual.html#flag--spawn_strategy)
flag), but with no explicit checking for allowed values.

Example:
```py
platform(
    name = "local",
    spawn_strategies = [
      "local",
      "sandbox",
      "worker",
    ],
)

platform(
    name = "remote",
    spawn_strategies = [
      "remote",
    ],
)
```

In the [PlatformInfo
provider](https://docs.bazel.build/versions/master/skylark/lib/PlatformInfo.html),
these will be converted to a `Set<String>`, indicating that order of the
strategies does not matter.

Open questions:
-  Should the strategies be lower-cased? `--spawn_strategy` does not appear to
   do any special processing.
-  Is there a better name for the attribute? I prefer `execution_strategies`,
   but `spawn_strategies` more closely matches the existing `--spawn_strategy`
   flag, and so may be clearer.

Once the new attribute is available, the existing default host platforms will be
updated to add the following strategies:
-  worker
-  sandboxed
-  local

When a platform is not being used as an execution platform (for example, if a
platform is used as a target platform), the new attribute will be unused.

### Alternatives Considered

Instead of adding a new attribute which is only useful for execution platforms,
a new flag could be added: `--platform_spawn_strategy`. Any execution platform
that is not also the host platform would use these values for the following
stages. The host platform would use the hard-coded defaults from above.

## Toolchain Resolution

During [toolchain
resolution](https://docs.bazel.build/versions/master/toolchains.html#toolchain-resolution),
Bazel first determines the correct set of toolchain implementations to use for
each available execution platform. Then, it selects the highest priority
execution platform, determined by the order execution platforms are defined,
first via the `--extra_execution_platforms` flag and then by the order of calls
to `register_execution_platforms` in WORKSPACE.

To consider execution strategy, instead of using ordering to determine priority,
toolchain resolution will instead use the order of available execution
strategies (as given by the `--spawn_strategy` flag). The selection of execution
platform will then follow this logic:

1. For each execution strategy in order:
   1. Find the first execution strategy that claims support for the strategy, as
      indicated by the new `spawn_strategies` attribute.
   2. Verify is this strategy and execution platform are compatible with the
      target under consideration by checking the (non-configurable) `tags`
      attribute (as the execution strategy selection does now).
2. If all execution strategies have been tried and no available execution
   platform exists, fail with an error describing the situation.

In order for legacy platforms to continue working, a platform that does not set
the `spawn_strategies` attribute will be considered to support every execution
strategy.

At this point target configuration can continue as it currently does.

## Execution Strategy Selection

When an action is executed, each available strategy is checked in order to see
if it supports the action (based on execution requirements from the tags and
other sources, such as the toolchain).

When considering the execution platform, the selection of spawn strategy only
needs to add a check that the selected execution platform (which is currently
available as
[Spawn.getExecutionPlatform](https://source.bazel.build/bazel/+/master:src/main/java/com/google/devtools/build/lib/actions/BaseSpawn.java;l=155?q=BaseSpawn)),
so no new interfaces need to be added.

It will still be possible to end up in a situation where the execution strategy
and the execution platform do not match: toolchain resolution will not be able
to verify toolchain-based execution requirements, and the existence of the
[`--strategy
mnemonic=strategy`](https://docs.bazel.build/versions/master/user-manual.html#flag--strategy)
and
[`--strategy_regexp`](https://docs.bazel.build/versions/master/user-manual.html#flag--strategy_regexp)
flags mean that the strategy selection can still be overridden. In these cases,
we need to make sure the error messages from action execution indicate both the
selected execution strategy and the selected execution platform, so that users
can diagnose and fix these types of mis-configuration.

# Backwards Compatibility

The changes in this proposal will not take effect unless the new attribute on
`platform` is specified. Therefore, any existing users will see no changes until
the platforms they use are updated.

# Documentation

As part of this work, documentation and tutorials also need to be added, with
special attention to examples that cause errors or misconfiguration, and how to
recover.


text:
default: fmt test

fmt:
	go fmt

test:
	go test -cover


text:
    # The argexist, subarg and confirmed_to_proceed methods come from the external args.py
    # The subarg methods returns a LIST(!) of all related entries. Even the default is return as a list!
    # The TIFFs are saved in conventional format: (height, width, layers)
    # -p argument can now recognise individual files and invalid paths

import sys
from args import argexist, subarg

def main():
    import matplotlib.pyplot as plt
    import cv2
    import os
    from sklearn.cluster import KMeans
    import numpy as np
    from timeit import default_timer as timer
    import time
    import datetime
    import tifffile as tiff
    from args import argexist, subarg, confirmed_to_proceed

    ## Specify path
    #default_path = "/Volumes/INH_1TB/MND_HistReg_Scratch/NP140-14_dissection_photos/Cropped/Blocks/"
    default_path = os.getcwd()
    try:
        FPATH = subarg('-p', default_path)
    except AssertionError as exp:
        print("Fatal error. Program terminates.\n", exp)
        exit()

    ## Specify extensions
    try:
        extlist = subarg('-e', "tif,tiff")
    except AssertionError as exp:
        print("Fatal error. Program terminates.\n", exp)
        exit()
    EXTENSIONS = tuple(".{}".format(extlist))

    ## Specify the number of clusters
    try:
        N_CLUSTERS = int(subarg('-c', 2)[0])
    except AssertionError as exp:
        print("Fatal error. Program terminates.\n", exp)
        exit()

    ## Specify output: masks only (default) / masks and images / images only
    MASKTAG = '_mask.tif'
    SEGTAG = '_seg.tif'
    savemask, applymask = True, False
    if argexist('-a'):
        if N_CLUSTERS == 2:
            applymask = True
            if not argexist('-m'):
                savemask = False
        else:
            print "N_CLUSTERS = {}".format(N_CLUSTERS)
            sys.stderr.write("WARNING: Segmentation mask not applicable if not binary. Output will be mask-only.\n")

    imglist = []
    for fp in FPATH:
        if os.path.isdir(fp):
            for path, subdirs, files in os.walk(fp, topdown=True):
                if not argexist('-r'):
                    subdirs[:] = []
                for file in files:
                    if (file[0] != '.') & (file.lower().endswith(EXTENSIONS)) & \
                            (not file.lower().endswith(MASKTAG)) & \
                            (not file.lower().endswith(SEGTAG)):
                        imglist.append(os.path.join(path, file))

        elif os.path.isfile(fp):
            fn = os.path.split(fp)[-1]
            if (fn[0] != '.') & (fn.lower().endswith(EXTENSIONS)) & \
                    (not fn.lower().endswith(MASKTAG)) & \
                    (not fn.lower().endswith(SEGTAG)):
                imglist.append(fp)
        else:
            print 'WARNING: Path {} could not be recognised.'.format(fp)

    # Terminate application if no files are selected
    if len(imglist) == 0:
        print 'RESULT: No files were found with the current setting. The program terminates. Please change the search path or the inclusion/exclusion criteria and try again.'
        exit()
    print "\nFiles to be processed {} (excluding _seg and _mask files):".format(len(imglist))
    print "=======================================================\n"
    print "\n".join(imglist)
    print "\nWould you like to start the process? [yes/no]: "
    if confirmed_to_proceed() == False:
        exit()

    # Loop through the list of images
    start = timer()
    t = datetime.datetime.fromtimestamp(time.time())
    print "Process started at {}".format(t.strftime('%Y-%m-%d %H:%M:%S'))

    for img in imglist:
        # Load image
        print "Reading {}...".format(img)
        im = np.asarray(tiff.imread(img))
        h,w = im.shape[:2]

        # Extract hue channel
        ch = cv2.cvtColor(im, cv2.COLOR_RGB2HSV)[:,:,0]

        # Segment image using KMeans clustering
        ch = np.reshape(ch, (-1,1))
        kmeans = KMeans(n_clusters=N_CLUSTERS).fit(ch)
        mask = np.asarray(kmeans.labels_, dtype=np.int8).reshape((h,w), order='C')

        # Invert mask if the top-left pixel is the brightest (permissive).
        if mask[0,0] == np.max(mask):
            mask = np.max(mask) - mask

        # Normalise mask labels so that they can be seen in a regular image viewer
        mask = mask / np.max(mask) * 255
        #mask[mask > 0] = 1 ### Decision: don't automatically binarize masks.

        # Create output
        if savemask:
            tiff.imsave(img[:-4] + MASKTAG, mask[:, :, np.newaxis].astype(np.uint8))
            print "Mask file saved as {}.".format(img.split(os.sep)[-1][:-4] + MASKTAG)
        if applymask:
            seg = np.copy(im)
            seg[mask==0] = 0
            tiff.imsave(img[:-4] + SEGTAG, seg[:, :, :].astype(np.uint8))
            print "Segmented image saved as {}.".format(img.split(os.sep)[-1][:-4] + SEGTAG)

    end = timer()
    t = datetime.datetime.fromtimestamp(time.time())
    print "\nSegmentation was completed at {} ({:.1f} seconds)".format(t.strftime('%Y-%m-%d %H:%M:%S'), end - start)

if __name__ == '__main__':
    if len(sys.argv) > 1:
        main()
    else:
        print """
        The segment-by-hue utility performs k-Means segmentation on digital photographs using the values of the Hue colour channel.
        The output can be a label mask, a segmented image or both.

        Usage: ./segment-by-hue.py [options]

        Options:
            -p <path1,path2...>     root path of image files (add multiple paths as comma-separated list)
                                    the default is the current working directory
            -r                      process files in subdirectories
            -e <ext1,ext2...>       file extensions to be included (as comma-separated list)
                                    the default is tif,tiff

            -c <number>             number of segmentation clusters (default: 2)

            -a                      apply segmentation mask (binary mask is needed: use -c 2)
            -m                      save mask file(s) (only needed if -a is used)

        """


text:
#include <shogun/features/DotFeatures.h>
#include <shogun/features/SparseFeatures.h>
#include <shogun/lib/Hash.h>
#include <shogun/mathematics/Math.h>
#include <shogun/structure/HashedMultilabelModel.h>
#include <shogun/structure/MultilabelSOLabels.h>
#include <shogun/lib/DynamicArray.h>

using namespace shogun;

CHashedMultilabelModel::CHashedMultilabelModel()
	: CStructuredModel()
{
	init(0);
}

CHashedMultilabelModel::CHashedMultilabelModel(CFeatures * features,
                CStructuredLabels * labels, int32_t dim) : CStructuredModel(features, labels)
{
	init(dim);
}

CHashedMultilabelModel::~CHashedMultilabelModel()
{
}

CStructuredLabels * CHashedMultilabelModel::structured_labels_factory(
        int32_t num_examples)
{
	return new CMultilabelSOLabels(num_examples, m_num_classes);
}

void CHashedMultilabelModel::init(int32_t dim)
{
	SG_ADD(&m_false_positive, "false_positive", "Misclassification cost for false positive");
	SG_ADD(&m_false_negative, "false_negative", "Misclassification cost for false negative");
	SG_ADD(&m_num_classes, "num_classes", "Number of (binary) class assignment per label");
	SG_ADD(&m_dim, "dim", "New joint feature space dimension");
	SG_ADD(&m_seeds, "seeds", "Vector of seeds used for hashing");

	m_false_positive = 1;
	m_false_negative = 1;
	m_num_classes = 0;
	m_dim = dim;

	if (m_labels != NULL)
	{
		m_seeds = SGVector<uint32_t>(
		                  ((CMultilabelSOLabels *)m_labels)->get_num_classes());
		SGVector<uint32_t>::range_fill_vector(m_seeds.vector, m_seeds.vlen);
	}
	else
	{
		m_seeds = SGVector<uint32_t>(0);
	}
}

int32_t CHashedMultilabelModel::get_dim() const
{
	return m_dim;
}

void CHashedMultilabelModel::set_misclass_cost(float64_t false_positive,
                float64_t false_negative)
{
	m_false_positive = false_positive;
	m_false_negative = false_negative;
}

void CHashedMultilabelModel::set_seeds(SGVector<uint32_t> seeds)
{
	REQUIRE(((CMultilabelSOLabels *)m_labels)->get_num_classes() == seeds.vlen,
	        "Seeds for all the classes not provided. \n");
	m_seeds = seeds;
}

SGVector<float64_t> CHashedMultilabelModel::get_joint_feature_vector(
        int32_t feat_idx, CStructuredData * y)
{
	SG_ERROR("compute_joint_feature(int32_t, CStructuredData*) is not "
	         "implemented for %s!\n", get_name());

	return SGVector<float64_t>();
}

SGSparseVector<float64_t> CHashedMultilabelModel::get_sparse_joint_feature_vector(
        int32_t feat_idx, CStructuredData * y)
{
	SGSparseVector<float64_t> vec = ((CSparseFeatures<float64_t> *)m_features)->
	                                get_sparse_feature_vector(feat_idx);

	CSparseMultilabel * slabel = y->as<CSparseMultilabel>();
	ASSERT(slabel != NULL);
	SGVector<int32_t> slabel_data = slabel->get_data();

	SGSparseVector<float64_t> psi(vec.num_feat_entries * slabel_data.vlen);
	index_t k = 0;

	for (int32_t i = 0; i < slabel_data.vlen; i++)
	{
		int32_t label = slabel_data[i];
		uint32_t seed = (uint32_t)m_seeds[label];

		for (int32_t j = 0; j < vec.num_feat_entries; j++)
		{
			uint32_t hash = CHash::MurmurHash3(
			                        (uint8_t *)&vec.features[j].feat_index,
			                        sizeof(index_t), seed);
			psi.features[k].feat_index = (hash >> 1) % m_dim;
			psi.features[k++].entry =
			        (hash % 2 == 1 ? -1.0 : 1.0) * vec.features[j].entry;
		}

	}

	psi.sort_features(true);
	return psi;
}

float64_t CHashedMultilabelModel::delta_loss(CStructuredData * y1,
                CStructuredData * y2)
{
	CSparseMultilabel * y1_slabel = y1->as<CSparseMultilabel>();
	CSparseMultilabel * y2_slabel = y2->as<CSparseMultilabel>();

	ASSERT(y1_slabel != NULL);
	ASSERT(y2_slabel != NULL);

	CMultilabelSOLabels * multi_labels = (CMultilabelSOLabels *)m_labels;
	return delta_loss(
	               CMultilabelSOLabels::to_dense(y1_slabel,
	                               multi_labels->get_num_classes(), 1, 0),
	               CMultilabelSOLabels::to_dense(y2_slabel,
	                               multi_labels->get_num_classes(), 1, 0));
}

float64_t CHashedMultilabelModel::delta_loss(SGVector<float64_t> y1,
                SGVector<float64_t> y2)
{
	REQUIRE(y1.vlen == y2.vlen, "Size of both the vectors should be same\n");

	float64_t loss = 0;

	for (index_t i = 0; i < y1.vlen; i++)
	{
		loss += delta_loss(y1[i], y2[i]);
	}

	return loss;
}

float64_t CHashedMultilabelModel::delta_loss(float64_t y1, float64_t y2)
{
	return y1 > y2 ? m_false_negative : y1 < y2 ? m_false_positive : 0;
}

void CHashedMultilabelModel::init_primal_opt(
        float64_t regularization,
        SGMatrix<float64_t> &A,
        SGVector<float64_t> a,
        SGMatrix<float64_t> B,
        SGVector<float64_t> &b,
        SGVector<float64_t> &lb,
        SGVector<float64_t> &ub,
        SGMatrix<float64_t> &C)
{
	C = SGMatrix<float64_t>::create_identity_matrix(get_dim(), regularization);
}

SGSparseVector<float64_t> CHashedMultilabelModel::get_hashed_feature_vector(
        int32_t feat_idx, uint32_t seed)
{
	SGSparseVector<float64_t> vec = ((CSparseFeatures<float64_t> *)m_features)->
	                                get_sparse_feature_vector(feat_idx);

	SGSparseVector<float64_t> h_vec(vec.num_feat_entries);

	for (int32_t j = 0; j < vec.num_feat_entries; j++)
	{
		uint32_t hash = CHash::MurmurHash3(
		                        (uint8_t *)&vec.features[j].feat_index,
		                        sizeof(index_t), seed);
		h_vec.features[j].feat_index = (hash >> 1) % m_dim;
		h_vec.features[j].entry =
		        (hash % 2 == 1 ? -1.0 : 1.0) * vec.features[j].entry;
	}

	h_vec.sort_features(true);

	return h_vec;
}

SGVector<int32_t> CHashedMultilabelModel::to_sparse(SGVector<float64_t> dense_vec,
                float64_t d_true, float64_t d_false)
{
	int32_t size = 0;

	for (index_t i = 0; i < dense_vec.vlen; i++)
	{
		REQUIRE(dense_vec[i] == d_true || dense_vec[i] == d_false,
		        "The values of dense vector should be either (%d) or (%d).\n",
		        d_true, d_false);

		if (dense_vec[i] == d_true)
		{
			size++;
		}
	}

	SGVector<int32_t> sparse_vec(size);
	index_t j = 0;

	for (index_t i = 0; i < dense_vec.vlen; i++)
	{
		if (dense_vec[i] == d_true)
		{
			sparse_vec[j] = i;
			j++;
		}
	}

	return sparse_vec;
}

CResultSet * CHashedMultilabelModel::argmax(SGVector<float64_t> w,
                int32_t feat_idx, bool const training)
{
	CMultilabelSOLabels * multi_labs = (CMultilabelSOLabels *)m_labels;

	if (training)
	{
		m_num_classes = multi_labs->get_num_classes();
	}
	else
	{
		REQUIRE(m_num_classes > 0, "The model needs to be trained before using"
		        "it for prediction.\n");
	}

	int32_t dim = get_dim();
	ASSERT(dim == w.vlen);

	float64_t score = 0, total_score = 0;

	CSparseMultilabel * slabel = multi_labs->get_label(feat_idx)->as<CSparseMultilabel>();
	SGVector<int32_t> slabel_data = slabel->get_data();
	SGVector<float64_t> y_truth = CMultilabelSOLabels::to_dense(
	                                      slabel, m_num_classes, 1, 0);
	SG_UNREF(slabel);

	SGVector<float64_t> y_pred_dense(m_num_classes);
	y_pred_dense.zero();
	int32_t count = 0;

	for (int32_t c = 0; c < m_num_classes; c++)
	{
		SGSparseVector<float64_t> phi = get_hashed_feature_vector(feat_idx,
		                                m_seeds[c]);
		score = phi.dense_dot(1.0, w.vector, w.vlen, 0);

		if (score > 0)
		{
			y_pred_dense[c] = 1;
			total_score += score;
			count++;
		}

	}

	SGVector<int32_t> y_pred_sparse = to_sparse(y_pred_dense, 1, 0);
	ASSERT(count == y_pred_sparse.vlen);

	CResultSet * ret = new CResultSet();
	SG_REF(ret);
	ret->psi_computed_sparse = true;
	ret->psi_computed = false;

	CSparseMultilabel * y_pred_label = new CSparseMultilabel(y_pred_sparse);
	SG_REF(y_pred_label);

	ret->psi_pred_sparse = get_sparse_joint_feature_vector(feat_idx, y_pred_label);
	ret->score = total_score;
	ret->argmax = y_pred_label;

	if (training)
	{
		ret->delta = CStructuredModel::delta_loss(feat_idx, y_pred_label);
		ret->psi_truth_sparse = CStructuredModel::get_sparse_joint_feature_vector(
		                                feat_idx, feat_idx);
		ret->score += (ret->delta - ret->psi_truth_sparse.dense_dot(1, w.vector,
		                w.vlen, 0));
	}

	return ret;
}


text:
copyright:
 years: 2015, 2016

---

# Conservation des notifications pour Android
{: #hold-notifications-android}

Lorsque votre application passe en arrière-plan, il peut être judicieux que Push conserve les notifications qui lui sont envoyées. Pour conserver des notifications, appelez la méthode hold() dans la méthode onPause() de l'activité qui traite les notifications push.

```
@Override
protected void onPause() {
    super.onPause();

    if (push != null) {
        push.hold();
    }
}
```


text:
#pragma once
#include <aws/sso-admin/SSOAdmin_EXPORTS.h>
#include <aws/sso-admin/model/StatusValues.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace SSOAdmin
{
namespace Model
{

  /**
   *
A structure that is used to provide the status of the provisioning operation
   * for a specified permission set.

See Also:
   AWS
   * API Reference

   */
  class AWS_SSOADMIN_API PermissionSetProvisioningStatus
  {
  public:
    PermissionSetProvisioningStatus();
    PermissionSetProvisioningStatus(Aws::Utils::Json::JsonView jsonValue);
    PermissionSetProvisioningStatus& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The status of the permission set provisioning process.

     */
    inline const StatusValues& GetStatus() const{ return m_status; }

    /**
     *
The status of the permission set provisioning process.

     */
    inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; }

    /**
     *
The status of the permission set provisioning process.

     */
    inline void SetStatus(const StatusValues& value) { m_statusHasBeenSet = true; m_status = value; }

    /**
     *
The status of the permission set provisioning process.

     */
    inline void SetStatus(StatusValues&& value) { m_statusHasBeenSet = true; m_status = std::move(value); }

    /**
     *
The status of the permission set provisioning process.

     */
    inline PermissionSetProvisioningStatus& WithStatus(const StatusValues& value) { SetStatus(value); return *this;}

    /**
     *
The status of the permission set provisioning process.

     */
    inline PermissionSetProvisioningStatus& WithStatus(StatusValues&& value) { SetStatus(std::move(value)); return *this;}

    /**
     *
The identifier for tracking the request operation that is generated by the
     * universally unique identifier (UUID) workflow.

     */
    inline const Aws::String& GetRequestId() const{ return m_requestId; }

    /**
     *
The identifier for tracking the request operation that is generated by the
     * universally unique identifier (UUID) workflow.

     */
    inline bool RequestIdHasBeenSet() const { return m_requestIdHasBeenSet; }

    /**
     *
The identifier for tracking the request operation that is generated by the
     * universally unique identifier (UUID) workflow.

     */
    inline void SetRequestId(const Aws::String& value) { m_requestIdHasBeenSet = true; m_requestId = value; }

    /**
     *
The identifier for tracking the request operation that is generated by the
     * universally unique identifier (UUID) workflow.

     */
    inline void SetRequestId(Aws::String&& value) { m_requestIdHasBeenSet = true; m_requestId = std::move(value); }

    /**
     *
The identifier for tracking the request operation that is generated by the
     * universally unique identifier (UUID) workflow.

     */
    inline void SetRequestId(const char* value) { m_requestIdHasBeenSet = true; m_requestId.assign(value); }

    /**
     *
The identifier for tracking the request operation that is generated by the
     * universally unique identifier (UUID) workflow.

     */
    inline PermissionSetProvisioningStatus& WithRequestId(const Aws::String& value) { SetRequestId(value); return *this;}

    /**
     *
The identifier for tracking the request operation that is generated by the
     * universally unique identifier (UUID) workflow.

     */
    inline PermissionSetProvisioningStatus& WithRequestId(Aws::String&& value) { SetRequestId(std::move(value)); return *this;}

    /**
     *
The identifier for tracking the request operation that is generated by the
     * universally unique identifier (UUID) workflow.

     */
    inline PermissionSetProvisioningStatus& WithRequestId(const char* value) { SetRequestId(value); return *this;}

    /**
     *
The identifier of the AWS account from which to list the assignments.

     */
    inline const Aws::String& GetAccountId() const{ return m_accountId; }

    /**
     *
The identifier of the AWS account from which to list the assignments.

     */
    inline bool AccountIdHasBeenSet() const { return m_accountIdHasBeenSet; }

    /**
     *
The identifier of the AWS account from which to list the assignments.

     */
    inline void SetAccountId(const Aws::String& value) { m_accountIdHasBeenSet = true; m_accountId = value; }

    /**
     *
The identifier of the AWS account from which to list the assignments.

     */
    inline void SetAccountId(Aws::String&& value) { m_accountIdHasBeenSet = true; m_accountId = std::move(value); }

    /**
     *
The identifier of the AWS account from which to list the assignments.

     */
    inline void SetAccountId(const char* value) { m_accountIdHasBeenSet = true; m_accountId.assign(value); }

    /**
     *
The identifier of the AWS account from which to list the assignments.

     */
    inline PermissionSetProvisioningStatus& WithAccountId(const Aws::String& value) { SetAccountId(value); return *this;}

    /**
     *
The identifier of the AWS account from which to list the assignments.

     */
    inline PermissionSetProvisioningStatus& WithAccountId(Aws::String&& value) { SetAccountId(std::move(value)); return *this;}

    /**
     *
The identifier of the AWS account from which to list the assignments.

     */
    inline PermissionSetProvisioningStatus& WithAccountId(const char* value) { SetAccountId(value); return *this;}

    /**
     *
The ARN of the permission set that is being provisioned. For more information
     * about ARNs, see Amazon
     * Resource Names (ARNs) and AWS Service Namespaces in the AWS General
     * Reference.

     */
    inline const Aws::String& GetPermissionSetArn() const{ return m_permissionSetArn; }

    /**
     *
The ARN of the permission set that is being provisioned. For more information
     * about ARNs, see Amazon
     * Resource Names (ARNs) and AWS Service Namespaces in the AWS General
     * Reference.

     */
    inline bool PermissionSetArnHasBeenSet() const { return m_permissionSetArnHasBeenSet; }

    /**
     *
The ARN of the permission set that is being provisioned. For more information
     * about ARNs, see Amazon
     * Resource Names (ARNs) and AWS Service Namespaces in the AWS General
     * Reference.

     */
    inline void SetPermissionSetArn(const Aws::String& value) { m_permissionSetArnHasBeenSet = true; m_permissionSetArn = value; }

    /**
     *
The ARN of the permission set that is being provisioned. For more information
     * about ARNs, see Amazon
     * Resource Names (ARNs) and AWS Service Namespaces in the AWS General
     * Reference.

     */
    inline void SetPermissionSetArn(Aws::String&& value) { m_permissionSetArnHasBeenSet = true; m_permissionSetArn = std::move(value); }

    /**
     *
The ARN of the permission set that is being provisioned. For more information
     * about ARNs, see Amazon
     * Resource Names (ARNs) and AWS Service Namespaces in the AWS General
     * Reference.

     */
    inline void SetPermissionSetArn(const char* value) { m_permissionSetArnHasBeenSet = true; m_permissionSetArn.assign(value); }

    /**
     *
The ARN of the permission set that is being provisioned. For more information
     * about ARNs, see Amazon
     * Resource Names (ARNs) and AWS Service Namespaces in the AWS General
     * Reference.

     */
    inline PermissionSetProvisioningStatus& WithPermissionSetArn(const Aws::String& value) { SetPermissionSetArn(value); return *this;}

    /**
     *
The ARN of the permission set that is being provisioned. For more information
     * about ARNs, see Amazon
     * Resource Names (ARNs) and AWS Service Namespaces in the AWS General
     * Reference.

     */
    inline PermissionSetProvisioningStatus& WithPermissionSetArn(Aws::String&& value) { SetPermissionSetArn(std::move(value)); return *this;}

    /**
     *
The ARN of the permission set that is being provisioned. For more information
     * about ARNs, see Amazon
     * Resource Names (ARNs) and AWS Service Namespaces in the AWS General
     * Reference.

     */
    inline PermissionSetProvisioningStatus& WithPermissionSetArn(const char* value) { SetPermissionSetArn(value); return *this;}

    /**
     *
The message that contains an error or exception in case of an operation
     * failure.

     */
    inline const Aws::String& GetFailureReason() const{ return m_failureReason; }

    /**
     *
The message that contains an error or exception in case of an operation
     * failure.

     */
    inline bool FailureReasonHasBeenSet() const { return m_failureReasonHasBeenSet; }

    /**
     *
The message that contains an error or exception in case of an operation
     * failure.

     */
    inline void SetFailureReason(const Aws::String& value) { m_failureReasonHasBeenSet = true; m_failureReason = value; }

    /**
     *
The message that contains an error or exception in case of an operation
     * failure.

     */
    inline void SetFailureReason(Aws::String&& value) { m_failureReasonHasBeenSet = true; m_failureReason = std::move(value); }

    /**
     *
The message that contains an error or exception in case of an operation
     * failure.

     */
    inline void SetFailureReason(const char* value) { m_failureReasonHasBeenSet = true; m_failureReason.assign(value); }

    /**
     *
The message that contains an error or exception in case of an operation
     * failure.

     */
    inline PermissionSetProvisioningStatus& WithFailureReason(const Aws::String& value) { SetFailureReason(value); return *this;}

    /**
     *
The message that contains an error or exception in case of an operation
     * failure.

     */
    inline PermissionSetProvisioningStatus& WithFailureReason(Aws::String&& value) { SetFailureReason(std::move(value)); return *this;}

    /**
     *
The message that contains an error or exception in case of an operation
     * failure.

     */
    inline PermissionSetProvisioningStatus& WithFailureReason(const char* value) { SetFailureReason(value); return *this;}

    /**
     *
The date that the permission set was created.

     */
    inline const Aws::Utils::DateTime& GetCreatedDate() const{ return m_createdDate; }

    /**
     *
The date that the permission set was created.

     */
    inline bool CreatedDateHasBeenSet() const { return m_createdDateHasBeenSet; }

    /**
     *
The date that the permission set was created.

     */
    inline void SetCreatedDate(const Aws::Utils::DateTime& value) { m_createdDateHasBeenSet = true; m_createdDate = value; }

    /**
     *
The date that the permission set was created.

     */
    inline void SetCreatedDate(Aws::Utils::DateTime&& value) { m_createdDateHasBeenSet = true; m_createdDate = std::move(value); }

    /**
     *
The date that the permission set was created.

     */
    inline PermissionSetProvisioningStatus& WithCreatedDate(const Aws::Utils::DateTime& value) { SetCreatedDate(value); return *this;}

    /**
     *
The date that the permission set was created.

     */
    inline PermissionSetProvisioningStatus& WithCreatedDate(Aws::Utils::DateTime&& value) { SetCreatedDate(std::move(value)); return *this;}

  private:

    StatusValues m_status;
    bool m_statusHasBeenSet;

    Aws::String m_requestId;
    bool m_requestIdHasBeenSet;

    Aws::String m_accountId;
    bool m_accountIdHasBeenSet;

    Aws::String m_permissionSetArn;
    bool m_permissionSetArnHasBeenSet;

    Aws::String m_failureReason;
    bool m_failureReasonHasBeenSet;

    Aws::Utils::DateTime m_createdDate;
    bool m_createdDateHasBeenSet;
  };

} // namespace Model
} // namespace SSOAdmin
} // namespace Aws


text:
Simple scrolling events for [d3](https://github.com/mbostock/d3) graphs. Based on [stack](https://github.com/mbostock/stack.git)

### [Demo/Documentation](http://1wheel.github.io/graph-scroll/)

*graph-scroll* takes a selection of explanatory text sections and dispatches `active` events as different sections are scrolled into to view. These `active` events can be used to update a chart's state.

```
graphScroll()
    .sections(d3.selectAll('#sections > div'))
    .on('active', function(i){ console.log(i + 'th section active') })
```

The top most element scrolled fully into view is classed `graph-scroll-active`. This makes it easy to highlight the active section with css:

```
#sections > div{
	opacity: .3
}

#sections div.graph-scroll-active{
	opacity: 1;
}
```

To support headers and intro images/text, we use a container element containing the explanatory text and graph.

```
<h1>Page Title</div>
<div id='container'>
	<div id='sections'>
		<div>Section 0</div>
		<div>Section 1</div>
		<div>Section 2</div>
	</div>

	<div id='graph'></div>
</div>
<h1>Footer</h1>
```

If these elements are passed to graphScroll as selections with `container` and `graph`, every element in the graph selection will be classed `graph-scroll-graph` if the top of the container is out of view.

```
graphScroll()
	.graph(d3.selectAll('#graph'))
	.container(d3.select('#container'))
  .sections(d3.selectAll('#sections > div'))
  .on('active', function(i){ console.log(i + 'th section active') })

```

With a little bit of css, the graph element snaps to the top of the page while the text scrolls by.

```
#container{
  position: relative;
  overflow: auto;
}

#sections{
  width: 200px;
  float: left;
}

#graph{
  width: 600px;
  float: left;
  margin-left: 40px;
}

#graph.graph-scroll-fixed{
  position: fixed;
  top: 0px;
  margin-left: 240px;
}
```

As the bottom of the container approaches the top of the page, the graph is classed with `graph-scroll-below`. A little more css allows the graph slide out of view gracefully:

```
#graph.graph-scroll-below{
  position: absolute;
  bottom: 0px;
  margin-left: 240px;
}
```


text:
package com.sunny.spider.service;

/**
 * AbstractImageService
 *
 * @author sunny
 * @version 1.0.0
 * @since 2017-04-28
 */
public abstract class AbstractSpiderService implements ISpiderService {

    @Override
    public final void start(Object context) {
        preProcess(context);
        processing(context);
        postProcess(context);
    }

    @Override
    public void postProcess(Object context) {

    }

}


text:
 MailRemind.me

Login:

         Facebook
         Google


text:
<?php
/*
 * This file bootstraps the test environment.
 */
namespace Doctrine\Tests;

error_reporting(E_ALL | E_STRICT);

require_once __DIR__ . '/../../../lib/vendor/doctrine-common/lib/Doctrine/Common/ClassLoader.php';

$classLoader = new \Doctrine\Common\ClassLoader('Doctrine\Common', __DIR__ . '/../../../lib/vendor/doctrine-common/lib');
$classLoader->register();

$classLoader = new \Doctrine\Common\ClassLoader('Doctrine\DBAL', __DIR__ . '/../../../lib');
$classLoader->register();

$classLoader = new \Doctrine\Common\ClassLoader('Doctrine\Tests', __DIR__ . '/../../');
$classLoader->register();

$classLoader = new \Doctrine\Common\ClassLoader('Symfony', __DIR__ . "/../../../lib/vendor");
$classLoader->register();


text:
//
// TnefAttributeLevel.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

namespace MimeKit.Tnef {
	/// <summary>
	/// A TNEF attribute level.
	/// </summary>
	/// <remarks>
	/// A TNEF attribute level.
	/// </remarks>
	public enum TnefAttributeLevel {
		/// <summary>
		/// The attribute is a message-level attribute.
		/// </summary>
		Message    = 1,

		/// <summary>
		/// The attribute is an attachment-level attribute.
		/// </summary>
		Attachment = 2,
	}
}


text:
The Power Functions Package API
===============================

The Extended Module
-------------------

.. automodule:: power_functions.extended
    :members:
    :undoc-members:
    :show-inheritance:

The Combo Direct Module
-----------------------

.. automodule:: power_functions.combo_direct
    :members:
    :undoc-members:
    :show-inheritance:

The Single Output Module
------------------------

.. automodule:: power_functions.single_output
    :members:
    :undoc-members:
    :show-inheritance:

The Combo PWM Module
--------------------

.. automodule:: power_functions.combo_pwm
    :members:
    :undoc-members:
    :show-inheritance:


text: from tigre import Config, Tigre, do_it


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

        <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
        <title>Average overlay</title>
        <link rel="stylesheet" type="text/css" href="Help.css" />
    <link href="../../Scripts and style sheets/style_2.css" rel="stylesheet" type="text/css">

Average overlay

This tool can be used to find the average value in each cell of a grid from
            a set of input images. It is therefore similar to the             Weighted Sum tool except that each input image is given equal
            weighting. This tool has been optimized for parallel processing.

See Also:

Weighted Sum

Max Overlay

Max Absolute Overlay

Min Overlay

Scripting:

The following is an example of a Python script using this tool:

                wd = pluginHost.getWorkingDirectory()

                # You may have multiple input files but they must

                # be separated by semicolons in the string.

                inputFiles = wd + "input1.dep" + ";" + wd + "input2.dep" + ";" + wd + "input3.dep"

                outputFile = wd + "output.dep"

                args = [inputFiles, outputFile]

                pluginHost.runPlugin("AverageOverlay", args, False)

This is a Groovy script also using this tool:

                def wd = pluginHost.getWorkingDirectory()

                // You may have multiple input files but they must

                // be separated by semicolons in the string.

                def inputFiles = wd + "input1.dep" + ";" + wd + "input2.dep" + ";" + wd + "input3.dep"

                def outputFile = wd + "output.dep"

                String[] args = [inputFiles, outputFile]

                pluginHost.runPlugin("AverageOverlay", args, false)

Credits:

John Lindsay (2013) email: jlindsay@uoguelph.ca


text:
package user_test

import (
	testapi "github.com/cloudfoundry/cli/cf/api/fakes"
	. "github.com/cloudfoundry/cli/cf/commands/user"
	"github.com/cloudfoundry/cli/cf/configuration/core_config"
	"github.com/cloudfoundry/cli/cf/models"
	testcmd "github.com/cloudfoundry/cli/testhelpers/commands"
	testconfig "github.com/cloudfoundry/cli/testhelpers/configuration"
	testreq "github.com/cloudfoundry/cli/testhelpers/requirements"
	testterm "github.com/cloudfoundry/cli/testhelpers/terminal"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	. "github.com/cloudfoundry/cli/testhelpers/matchers"
)

var _ = Describe("org-users command", func() {
	var (
		ui                  *testterm.FakeUI
		requirementsFactory *testreq.FakeReqFactory
		configRepo          core_config.ReadWriter
		userRepo            *testapi.FakeUserRepository
	)

	BeforeEach(func() {
		ui = &testterm.FakeUI{}
		userRepo = &testapi.FakeUserRepository{}
		configRepo = testconfig.NewRepositoryWithDefaults()
		requirementsFactory = &testreq.FakeReqFactory{}
	})

	runCommand := func(args ...string) bool {
		return testcmd.RunCommand(NewOrgUsers(ui, configRepo, userRepo), args, requirementsFactory)
	}

	Describe("requirements", func() {
		It("fails with usage when invoked without an org name", func() {
			requirementsFactory.LoginSuccess = true

			runCommand()
			Expect(ui.FailedWithUsage).To(BeTrue())
		})

		It("fails when not logged in", func() {
			Expect(runCommand("say-hello-to-my-little-org")).To(BeFalse())
		})
	})

	Context("when logged in and given an org with users", func() {
		BeforeEach(func() {
			org := models.Organization{}
			org.Name = "the-org"
			org.Guid = "the-org-guid"

			user := models.UserFields{}
			user.Username = "user1"
			user2 := models.UserFields{}
			user2.Username = "user2"
			user3 := models.UserFields{}
			user3.Username = "user3"
			user4 := models.UserFields{}
			user4.Username = "user4"
			userRepo.ListUsersByRole = map[string][]models.UserFields{
				models.ORG_MANAGER:     []models.UserFields{user, user2},
				models.BILLING_MANAGER: []models.UserFields{user4},
				models.ORG_AUDITOR:     []models.UserFields{user3},
			}

			requirementsFactory.LoginSuccess = true
			requirementsFactory.Organization = org
		})

		It("shows the special users in the given org", func() {
			runCommand("the-org")

			Expect(userRepo.ListUsersOrganizationGuid).To(Equal("the-org-guid"))
			Expect(ui.Outputs).To(ContainSubstrings(
				[]string{"Getting users in org", "the-org", "my-user"},
				[]string{"ORG MANAGER"},
				[]string{"user1"},
				[]string{"user2"},
				[]string{"BILLING MANAGER"},
				[]string{"user4"},
				[]string{"ORG AUDITOR"},
				[]string{"user3"},
			))
		})

		Context("when the -a flag is provided", func() {
			BeforeEach(func() {
				user := models.UserFields{}
				user.Username = "user1"
				user2 := models.UserFields{}
				user2.Username = "user2"
				userRepo.ListUsersByRole = map[string][]models.UserFields{
					models.ORG_USER: []models.UserFields{user, user2},
				}
			})

			It("lists all org users, regardless of role", func() {
				runCommand("-a", "the-org")

				Expect(userRepo.ListUsersOrganizationGuid).To(Equal("the-org-guid"))
				Expect(ui.Outputs).To(ContainSubstrings(
					[]string{"Getting users in org", "the-org", "my-user"},
					[]string{"USERS"},
					[]string{"user1"},
					[]string{"user2"},
				))
			})
		})

		Context("when cc api verson is >= 2.21.0", func() {
			BeforeEach(func() {
				userRepo.ListUsersInOrgForRole_CallCount = 0
				userRepo.ListUsersInOrgForRoleWithNoUAA_CallCount = 0
			})

			It("calls ListUsersInOrgForRoleWithNoUAA()", func() {
				configRepo.SetApiVersion("2.22.0")
				runCommand("the-org")

				Expect(userRepo.ListUsersInOrgForRoleWithNoUAA_CallCount).To(BeNumerically(">=", 1))
				Expect(userRepo.ListUsersInOrgForRole_CallCount).To(Equal(0))
			})
		})

		Context("when cc api verson is < 2.21.0", func() {
			It("calls ListUsersInOrgForRole()", func() {
				configRepo.SetApiVersion("2.20.0")
				runCommand("the-org")

				Expect(userRepo.ListUsersInOrgForRoleWithNoUAA_CallCount).To(Equal(0))
				Expect(userRepo.ListUsersInOrgForRole_CallCount).To(BeNumerically(">=", 1))
			})
		})
	})
})


text:
<?php
/*
|--------------------------------------------------------------------------
| DeleteStateFailAuthTest.php
|--------------------------------------------------------------------------
| Created by Shawn Legge
| Feature:
|    In order to prevent non-admin from deleting states
|    As a user
|    I want to delete a state
|
| Scenario:
|   Given: I am not an admin
|   When: I submit a request to delete a state
|   Then: The state should not be deleted and I should receive an error message
*/
namespace Tests\Feature\acceptance\admin\states;

use Tests\Feature\acceptance\admin\AbstractTestPost;

class DeleteStateFailAuthTest extends AbstractTestPost
{
    use \SetUpAddressTrait;

    protected $postRoute = 'admin/api/states';

    protected function setUp()
    {
        parent::setUp();
        $this->setUpState();
        $this->postRoute = $this->postRoute . '/'  . $this->state->id;
    }

    /**
     * @group admin
     * @group states
     * @group acceptance
     * @test
     */
    public function guests_can_not_submit_a_delete_state_form()
    {
        $this->setPostResponse(['_method' => 'delete']);
        $this->postResponse->assertStatus(401);
    }

    /**
     * @group admin
     * @group states
     * @group acceptance
     * @test
     */
    public function users_can_not_submit_a_delete_state_form()
    {
        $this->setPostResponseUser(['_method' => 'delete']);
        $this->postResponse->assertStatus(302);
    }
}


text:
/**
 * ui.js
 * -----
 * Provides visual notifications through backbone.notifier
 */

var Marionette = require('marionette');
var Notifier = require('backbone.notifier');
var Radio = require('backbone.radio');
var Config = require('./config');

var UI = Marionette.Object.extend({
    initialize: function() {
        Radio.channel('notify').comply('show:success', function(message) {
            this.showSuccess(message);
        }, this);

        Radio.channel('notify').comply('show:error', function(message) {
            this.showError(message);
        }, this);

        Radio.channel('notify').comply('validation:error', function(errors) {
            this.showFormErrors(errors);
        }, this);

        Radio.channel('notify').comply('show:loader', function(message) {
            this.showLoader(message);
        }, this);

        Radio.channel('notify').comply('clean', function(keepLoader) {
            this.clean(keepLoader);
        }, this);
    },

    showFormErrors: function(errors) {
        this.clean();

        var msg = "Please correct the following errors:";

        for (var error in errors) {
            msg += "
" + errors[error];
        }

        var notifier = new Notifier();
        this.notify = notifier.notify({
            message: msg,
            type: 'error',
            position: Config.Notifier.position,
            ms: 5000
        });
    },

    showError: function(err) {
        this.clean();
        var notifier = new Notifier();
        this.notify = notifier.notify({
            message: err,
            type: 'error',
            position: Config.Notifier.position,
            ms: 5000
        });
    },

    showInfo: function(info) {
        this.clean();
        var notifier = new Notifier();
        this.notify = notifier.notify({
            message: info,
            type: 'info',
            position: Config.Notifier.position,
            ms: 3000
        });
    },

    showSuccess: function(success) {
        this.clean();
        var notifier = new Notifier();
        this.notify = notifier.notify({
            message: success,
            type: 'success',
            position: Config.Notifier.position,
            ms: 3000
        });
    },

    showLoader: function(message) {
        this.clean();
        var msg = message || "Loading...";

        var notifier = new Notifier();
        this.notify = notifier.notify({
            message: msg,
            position: 'center',
            fadeInMs: 0,
            fadeOutMs: 0,
            ms: false,
            modal: true,
            loader: true
        });
    },

    clean: function(keepLoader) {
        if (this.notify) {
            if (keepLoader && this.notify.settings.loader)
                return;
            this.notify.destroy();
        }
    }
});

module.exports = UI;


text:
package org.wso2.carbon.jndi.internal.osgi;

import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;

import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;

/**
 * OSGiServiceNaming enumeration implementation..
 */
public class OSGiServiceNamingEnumeration implements NamingEnumeration<NameClassPair> {

    /**
     * Caller bundle context.
     */
    private BundleContext bundleContext;
    /**
     * Maintain current position of the references.
     */
    private int currentIndex = 0;
    /**
     * Maintains list of bindings.
     */
    private List<NameClassPair> nameClassPairList;

    /**
     * create OSGiServiceNamingEnumeration instance building the NameClassPair objects.
     *
     * @param bundleContext owning bundle context
     * @param refs          servicereferences of each service of the registry
     */
    public OSGiServiceNamingEnumeration(BundleContext bundleContext, List<ServiceReference> refs) {
        this.bundleContext = bundleContext;
        nameClassPairList = buildNameClassPair(refs);
    }

    private List<NameClassPair> buildNameClassPair(List<ServiceReference> serviceReferencesList) {
        //A Binding object contains the name, class of the service, and the service object.
        //name are a string with the service.id number
        Predicate<ServiceReference> filterNotNullReferences =
                (ServiceReference reference) -> (bundleContext.getService(reference) != null);

        return serviceReferencesList.stream()
                .filter(filterNotNullReferences)
                .map(this::buildNameClassPair)
                .collect(Collectors.toList());
    }

    private NameClassPair buildNameClassPair(ServiceReference serviceReference) {
        NameClassPair nameClassPair =
                new NameClassPair(String.valueOf(serviceReference.getProperty(Constants.SERVICE_ID)),
                        bundleContext.getService(serviceReference).getClass().getName());
        bundleContext.ungetService(serviceReference);
        return nameClassPair;
    }

    /**
     * Retrieves the next element in the enumeration.
     */
    @Override
    public NameClassPair next() throws NamingException {
        return nextElement();
    }

    /**
     * Determines whether there are any more elements in the enumeration.
     */
    @Override
    public boolean hasMore() throws NamingException {
        return hasMoreElements();
    }

    @Override
    public void close() throws NamingException {
    }

    /**
     * Tests if this enumeration contains more elements.
     */
    @Override
    public boolean hasMoreElements() {
        return currentIndex < nameClassPairList.size();
    }

    /**
     * Returns the next element of this enumeration if this enumeration
     * object has at least one more element to provide.
     */
    @Override
    public NameClassPair nextElement() {
        return nameClassPairList.get(currentIndex++);
    }
}


text:
@implementation LoLMasteryPages

@end


text:
<?php

namespace Rakorium\Okapi\Markdown;

/* import */
use Rakorium\Okapi\Lang\Token;
use Rakorium\Okapi\Dom;
use DOMElement, DOMNode;

/**
 * Description of Helpers
 *
 *
 */
trait Helpers
{
    /**
     * @param array $nodes
     * @return int
     */
    protected function clearEmptyNodes(array $nodes)
    {
        $count = 0;
        foreach ($nodes as $node) {
            if ($node->parentNode && !$node->hasChildNodes()) {
                $node->parentNode->removeChild($node);
                $count++;
            }
        }
        return $count;
    }

    /**
     * @param DOMNode $node
     * @return DOMNode
     */
    protected function normBlockNode(DOMNode $node)
    {
        if ($node->firstChild && $node->firstChild->nodeType == XML_TEXT_NODE) {
            $node->firstChild->data = ltrim($node->firstChild->data);
        }
        if ($node->lastChild && $node->lastChild->nodeType == XML_TEXT_NODE) {
            $node->lastChild->data = rtrim($node->lastChild->data);
        }
        return $node;
    }

    /**
     * Returns the number of element child nodes
     * @param DOMNode $node
     * @return DOMElement
     */
    protected function onlyElementChild(DOMNode $node)
    {
        $child = null;
        foreach (new Dom\Children($node) as $c) {
            if ($c->nodeType == XML_ELEMENT_NODE) {
                if (!$child) {
                    $child = $c;
                } else {
                    $child = null;
                    break;
                }
            }
        }
        return $child;
    }

    /**
     * @param Token $token
     * @return string
     */
    protected function listTag(Token $token)
    {
        $tag = '';
        if ($token->match('BULLET')) {
            $tag = 'ul';
        } elseif ($token->match('NUM_DOT') || $token->match('NUM_PAR')) {
            $tag = 'ol';
        }
        return $tag;
    }

    /**
     * @param Token $token
     * @return string
     */
    protected function tagName(Token $token)
    {
        return ltrim(rtrim($token->value(), '> '), '</');
    }

    /**
     * @param string $string
     * @return string
     */
    protected function idAttrValue($string)
    {
        return trim(preg_replace('/[^\w\-\.\:]+/', '-', $string), '-');
    }

    /**
     * @param DOMElement $element
     * @return string
     */
    protected function refAttrName(DOMElement $element)
    {
        $n = strtolower($element->nodeName);
        return ($n == 'a' ? 'href' : 'src');
    }

    /**
     * @param DOMNode $node
     * @return array
     */
    protected function nodeAttributes(DOMNode $node)
    {
        $values = [];
        $attribs = $node->attributes;
        if ($attribs) {
            foreach ($attribs as $k => $a) {
                $values[$k] = $a->value;
            }
        }
        return $values;
    }

}