text:
package alien4cloud.rest.application;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import alien4cloud.dao.ESGenericSearchDAO;
import alien4cloud.dao.model.FacetedSearchFacet;
import alien4cloud.model.deployment.Deployment;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import org.alien4cloud.tosca.catalog.index.ArchiveIndexer;
import org.alien4cloud.tosca.model.templates.Topology;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import alien4cloud.application.ApplicationEnvironmentService;
import alien4cloud.application.ApplicationService;
import alien4cloud.application.ApplicationVersionService;
import alien4cloud.audit.annotation.Audit;
import alien4cloud.dao.IGenericSearchDAO;
import alien4cloud.dao.model.FacetedSearchResult;
import alien4cloud.exception.AlreadyExistException;
import alien4cloud.exception.DeleteDeployedException;
import alien4cloud.images.IImageDAO;
import alien4cloud.images.exception.ImageUploadException;
import alien4cloud.model.application.Application;
import alien4cloud.model.application.ApplicationVersion;
import alien4cloud.paas.exception.OrchestratorDisabledException;
import alien4cloud.rest.application.model.CreateApplicationRequest;
import alien4cloud.rest.application.model.UpdateApplicationRequest;
import alien4cloud.rest.model.*;
import alien4cloud.security.AuthorizationUtil;
import alien4cloud.security.model.ApplicationRole;
import alien4cloud.security.model.Role;
import alien4cloud.utils.VersionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import static alien4cloud.dao.FilterUtil.fromKeyValueCouples;

/**
 * Service that allows managing applications.
 */
@Slf4j
@RestController
@RequestMapping({ "/rest/applications", "/rest/v1/applications", "/rest/latest/applications" })
@Api(value = "", description = "Operations on Applications")
public class ApplicationController {
    @Resource
    private IImageDAO imageDAO;
    @Resource(name = "alien-es-dao")
    private IGenericSearchDAO alienDAO;
    @Resource
    ArchiveIndexer archiveIndexer;
    @Resource
    private ApplicationService applicationService;
    @Resource
    private ApplicationVersionService applicationVersionService;
    @Resource
    private ApplicationEnvironmentService applicationEnvironmentService;

    /**
     * Create a new application in the system.
     *
     * @param request The new application to create.
     */
    @ApiOperation(value = "Create a new application in the system.", notes = "If successfull returns a rest response with the id of the created application in data. If not successful a rest response with an error content is returned. Role required [ APPLICATIONS_MANAGER ]. "
            + "By default the application creator will have application roles [APPLICATION_MANAGER, DEPLOYMENT_MANAGER]")
    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseStatus(value = HttpStatus.CREATED)
    @PreAuthorize("isAuthenticated()")
    @Audit
    public RestResponse<String> create(@Valid @RequestBody CreateApplicationRequest request) {
        AuthorizationUtil.checkHasOneRoleIn(Role.APPLICATIONS_MANAGER);
        final Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        // check the topology template id to recover the related topology id
        String topologyId = request.getTopologyTemplateVersionId();
        Topology template = null;
        if (topologyId != null) {
            template = applicationVersionService.getTemplateTopology(topologyId);
        }

        // check unity of archive name
        try {
            archiveIndexer.ensureUniqueness(request.getArchiveName(), VersionUtil.DEFAULT_VERSION_NAME);
        } catch (AlreadyExistException e) {
            return RestResponseBuilder.<String> builder()
                    .error(RestErrorBuilder.builder(RestErrorCode.APPLICATION_CSAR_VERSION_ALREADY_EXIST).message(
                            "CSAR: " + request.getArchiveName() + ", Version: " + VersionUtil.DEFAULT_VERSION_NAME + " already exists in the repository.")
                            .build())
                    .build();
        }

        // create the application with default environment and version
        String applicationId = applicationService.create(auth.getName(), request.getArchiveName(), request.getName(), request.getDescription(), template);
        ApplicationVersion version = applicationVersionService.createInitialVersion(applicationId, topologyId);
        applicationEnvironmentService.createApplicationEnvironment(auth.getName(), applicationId, version.getTopologyVersions().keySet().iterator().next());
        return RestResponseBuilder.<String> builder().data(applicationId).build();
    }

    /**
     * Get an application from it's id.
     *
     * @param applicationId The application id.
     */
    @ApiOperation(value = "Get an application based from its id.", notes = "Returns the application details. Application role required [ APPLICATION_MANAGER | APPLICATION_USER | APPLICATION_DEVOPS | DEPLOYMENT_MANAGER ]")
    @RequestMapping(value = "/{applicationId:.+}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @PreAuthorize("isAuthenticated()")
    public RestResponse<Application> get(@PathVariable String applicationId) {
        return RestResponseBuilder.<Application> builder().data(applicationService.checkAndGetApplication(applicationId)).build();
    }

    /**
     * Search for an application.
     *
     * @param searchRequest The element that contains criterias for search operation.
     * @return A rest response that contains a {@link FacetedSearchResult} containing applications.
     */
    @ApiOperation(value = "Search for applications", notes = "Returns a search result with that contains applications matching the request. A application is returned only if the connected user has at least one application role in [ APPLICATION_MANAGER | APPLICATION_USER | APPLICATION_DEVOPS | DEPLOYMENT_MANAGER ]")
    @RequestMapping(value = "/search", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @PreAuthorize("isAuthenticated()")
    public RestResponse<FacetedSearchResult> search(@RequestBody FilteredSearchRequest searchRequest) {
        QueryBuilder authorizationFilter = AuthorizationUtil.getResourceAuthorizationFilters();

        // We want to sort applications by deployed/undeployed and then application name.

        FacetedSearchResult<Application> facetedSearchResult = alienDAO.facetedSearch(Application.class, searchRequest.getQuery(), searchRequest.getFilters(), authorizationFilter, "", 0, Integer.MAX_VALUE);

        // Get their status (deployed vs undeployed)
        List<DeployedAppHolder> appHolders = Lists.newLinkedList();
        for (Application hit : facetedSearchResult.getData()) {
            String id = hit.getId();
            String appName = hit.getName();
            boolean isDeployed = alienDAO.buildQuery(Deployment.class).setFilters(fromKeyValueCouples("sourceId", id, "endDate", null)).count() > 0;
            appHolders.add(new DeployedAppHolder(id, appName, isDeployed));
        }

        // Sort to have first all deployed apps sorted by name and then all undeployed apps sorted by name.
        Collections.sort(appHolders);

        // Compute the list of app ids to fetch based on the query pagination parameters
        List<String> appIdsToFetch = Lists.newArrayList();
        int to = searchRequest.getFrom() + searchRequest.getSize();
        for (int i = searchRequest.getFrom(); i < appHolders.size() && i < to; i++) {
            appIdsToFetch.add(appHolders.get(i).appId);
        }
        List<Application> applications;
        if (appIdsToFetch.size() == 0) {
            applications = Lists.newArrayList();
        } else {
            applications = alienDAO.findByIds(Application.class, appIdsToFetch.toArray(new String[appIdsToFetch.size()]));
        }

        return RestResponseBuilder.<FacetedSearchResult> builder()
                .data(new FacetedSearchResult<>(searchRequest.getFrom(), to, facetedSearchResult.getQueryDuration(), appHolders.size(),
                        new String[] { Application.class.getSimpleName() }, applications.toArray(new Application[applications.size()]), facetedSearchResult.getFacets()))
                .build();
    }

    @AllArgsConstructor
    private class DeployedAppHolder implements Comparable<DeployedAppHolder> {
        private String appId;
        private String appName;
        private boolean isDeployed;

        @Override
        public int compareTo(DeployedAppHolder o) {
            if (this.isDeployed == o.isDeployed) {
                // Both are deployed or not deployed so compare on name
                return appName.toLowerCase().compareTo(o.appName.toLowerCase());
            }
            if (this.isDeployed) {
                return -1; // I am deployed so other is not (see previous if). smaller (first in sorted list).
            }
            return 1;
        }
    }

    /**
     * Delete an application based on it's id.
     *
     * @param applicationId The id of the application to delete.
     * @return A rest response.
     */
    @ApiOperation(value = "Delete an application from its id.", notes = "The logged-in user must have the application manager role for this application. Application role required [ APPLICATION_MANAGER ]")
    @RequestMapping(value = "/{applicationId:.+}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
    @PreAuthorize("isAuthenticated()")
    @Audit
    public RestResponse<Boolean> delete(@PathVariable String applicationId) {
        applicationService.checkAndGetApplication(applicationId, ApplicationRole.APPLICATION_MANAGER);

        try {
            boolean deleted = applicationService.delete(applicationId);
            if (!deleted) {
                throw new DeleteDeployedException(
                        "Application with id <" + applicationId + "> cannot be deleted since one of its environment is still deployed.");
            }
        } catch (OrchestratorDisabledException e) {
            log.error("Failed to delete the application due to Cloud error", e);
            return RestResponseBuilder.<Boolean> builder().data(false).error(RestErrorBuilder.builder(RestErrorCode.CLOUD_DISABLED_ERROR)
                    .message("Could not delete the application with id <" + applicationId + "> with error : " + e.getMessage()).build()).build();

        }
        return RestResponseBuilder.<Boolean> builder().data(true).build();
    }

    /**
     * Update application's image.
     *
     * @param applicationId The application id.
     * @param image new image of the application
     * @return nothing if success, error will be handled in global exception strategy
     */
    @ApiOperation(value = "Updates the image for the application.", notes = "The logged-in user must have the application manager role for this application. Application role required [ APPLICATION_MANAGER ]")
    @RequestMapping(value = "/{applicationId:.+}/image", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @PreAuthorize("isAuthenticated()")
    @Audit
    public RestResponse<String> updateImage(@PathVariable String applicationId, HttpServletRequest request) {
        String imageId = null;
        String fileName = "<image>";
        Application application = applicationService.checkAndGetApplication(applicationId, ApplicationRole.APPLICATION_MANAGER);

        try {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(request);
            if (iter.hasNext()) {
               FileItemStream item = iter.next();
               InputStream stream = item.openStream();
               if (!item.isFormField()) {
                  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                  int nRead;
                  byte[] datapart = new byte[10240];
                  while ((nRead = stream.read(datapart)) != -1) {
                      buffer.write(datapart, 0, nRead);
                  }
                  buffer.flush();
                  byte[] data = buffer.toByteArray();
                  imageId = imageDAO.writeImage(data);
                  fileName = item.getName();
               }
               stream.close();
            }
        } catch (IOException | FileUploadException e) {
            throw new ImageUploadException(
                    "Unable to read image from file upload [" + fileName + "] to update application [" + applicationId + "]", e);
        }
        application.setImageId(imageId);
        alienDAO.save(application);
        return RestResponseBuilder.<String> builder().data(imageId).build();
    }

    /**
     * Update application's name
     *
     * @param applicationId The application id.
     * @return nothing if success, error will be handled in global exception strategy
     */
    @ApiOperation(value = "Updates by merging the given request into the given application .", notes = "The logged-in user must have the application manager role for this application. Application role required [ APPLICATION_MANAGER ]")
    @RequestMapping(value = "/{applicationId:.+}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @PreAuthorize("isAuthenticated()")
    @Audit
    public RestResponse<Void> update(@PathVariable String applicationId, @RequestBody UpdateApplicationRequest request) {
        applicationService.update(applicationId, request.getName(), request.getDescription());
        return RestResponseBuilder.<Void> builder().build();
    }

}


text:
local ffi = require "ffi"

ffi.cdef [[
typedef int32_t ovrResult;
typedef enum ovrSuccessType_
{
ovrSuccess = 0,
ovrSuccess_NotVisible = 1000,
ovrSuccess_HMDFirmwareMismatch = 4100,
ovrSuccess_TrackerFirmwareMismatch = 4101,
} ovrSuccessType;
typedef enum ovrErrorType_
{
ovrError_MemoryAllocationFailure = -1000,
ovrError_SocketCreationFailure = -1001,
ovrError_InvalidHmd = -1002,
ovrError_Timeout = -1003,
ovrError_NotInitialized = -1004,
ovrError_InvalidParameter = -1005,
ovrError_ServiceError = -1006,
ovrError_NoHmd = -1007,
ovrError_AudioReservedBegin = -2000,
ovrError_AudioReservedEnd = -2999,
ovrError_Initialize = -3000,
ovrError_LibLoad = -3001,
ovrError_LibVersion = -3002,
ovrError_ServiceConnection = -3003,
ovrError_ServiceVersion = -3004,
ovrError_IncompatibleOS = -3005,
ovrError_DisplayInit = -3006,
ovrError_ServerStart = -3007,
ovrError_Reinitialization = -3008,
ovrError_MismatchedAdapters = -3009,
ovrError_InvalidBundleAdjustment = -4000,
ovrError_USBBandwidth = -4001,
ovrError_USBEnumeratedSpeed = -4002,
ovrError_ImageSensorCommError = -4003,
ovrError_GeneralTrackerFailure = -4004,
ovrError_ExcessiveFrameTruncation = -4005,
ovrError_ExcessiveFrameSkipping = -4006,
ovrError_SyncDisconnected = -4007,
ovrError_HMDFirmwareMismatch = -4100,
ovrError_TrackerFirmwareMismatch = -4101,
ovrError_Incomplete = -5000,
ovrError_Abandoned = -5001,
} ovrErrorType;
typedef char ovrBool;
typedef struct ovrVector2i_ { int x, y; } ovrVector2i;
typedef struct ovrSizei_ { int w, h; } ovrSizei;
typedef struct ovrRecti_
{
ovrVector2i Pos;
ovrSizei Size;
} ovrRecti;
typedef struct ovrQuatf_ { float x, y, z, w; } ovrQuatf;
typedef struct ovrVector2f_ { float x, y; } ovrVector2f;
typedef struct ovrVector3f_ { float x, y, z; } ovrVector3f;
typedef struct ovrMatrix4f_ { float M[4][4]; } ovrMatrix4f;
typedef struct ovrPosef_
{
ovrQuatf Orientation;
ovrVector3f Position;
} ovrPosef;
typedef struct ovrPoseStatef_
{
ovrPosef ThePose;
ovrVector3f AngularVelocity;
ovrVector3f LinearVelocity;
ovrVector3f AngularAcceleration;
ovrVector3f LinearAcceleration;
char pad0[4];
double TimeInSeconds;
} ovrPoseStatef;
typedef struct ovrFovPort_
{
float UpTan;
float DownTan;
float LeftTan;
float RightTan;
} ovrFovPort;
typedef enum ovrHmdType_
{
ovrHmd_None = 0,
ovrHmd_DK1 = 3,
ovrHmd_DKHD = 4,
ovrHmd_DK2 = 6,
ovrHmd_CB = 8,
ovrHmd_Other = 9,
ovrHmd_EnumSize = 0x7fffffff
} ovrHmdType;
typedef enum ovrHmdCaps_
{
ovrHmdCap_DebugDevice = 0x0010,
ovrHmdCap_LowPersistence = 0x0080,
ovrHmdCap_DynamicPrediction = 0x0200,
ovrHmdCap_Writable_Mask = ovrHmdCap_LowPersistence | ovrHmdCap_DynamicPrediction,
ovrHmdCap_Service_Mask = ovrHmdCap_LowPersistence | ovrHmdCap_DynamicPrediction,
ovrHmdCap_EnumSize = 0x7fffffff
} ovrHmdCaps;
typedef enum ovrTrackingCaps_
{
ovrTrackingCap_Orientation = 0x0010,
ovrTrackingCap_MagYawCorrection = 0x0020,
ovrTrackingCap_Position = 0x0040,
ovrTrackingCap_Idle = 0x0100,
ovrTrackingCap_EnumSize = 0x7fffffff
} ovrTrackingCaps;
typedef enum ovrEyeType_
{
ovrEye_Left = 0,
ovrEye_Right = 1,
ovrEye_Count = 2,
ovrEye_EnumSize = 0x7fffffff
} ovrEyeType;
typedef struct ovrHmdDesc_
{
struct ovrHmdStruct* Handle;
ovrHmdType Type;
const char* ProductName;
const char* Manufacturer;
short VendorId;
short ProductId;
char SerialNumber[24];
short FirmwareMajor;
short FirmwareMinor;
float CameraFrustumHFovInRadians;
float CameraFrustumVFovInRadians;
float CameraFrustumNearZInMeters;
float CameraFrustumFarZInMeters;
unsigned int HmdCaps;
unsigned int TrackingCaps;
ovrFovPort DefaultEyeFov[ovrEye_Count];
ovrFovPort MaxEyeFov[ovrEye_Count];
ovrEyeType EyeRenderOrder[ovrEye_Count];
ovrSizei Resolution;
} ovrHmdDesc;
typedef const ovrHmdDesc* ovrHmd;
typedef enum ovrStatusBits_
{
ovrStatus_OrientationTracked = 0x0001,
ovrStatus_PositionTracked = 0x0002,
ovrStatus_CameraPoseTracked = 0x0004,
ovrStatus_PositionConnected = 0x0020,
ovrStatus_HmdConnected = 0x0080,
ovrStatus_EnumSize = 0x7fffffff
} ovrStatusBits;
typedef struct ovrSensorData_
{
ovrVector3f Accelerometer;
ovrVector3f Gyro;
ovrVector3f Magnetometer;
float Temperature;
float TimeInSeconds;
} ovrSensorData;
typedef struct ovrTrackingState_
{
ovrPoseStatef HeadPose;
ovrPosef CameraPose;
ovrPosef LeveledCameraPose;
ovrSensorData RawSensorData;
unsigned int StatusFlags;
uint32_t LastCameraFrameCounter;
char pad0[4];
} ovrTrackingState;
typedef struct ovrFrameTiming_
{
double DisplayMidpointSeconds;
double FrameIntervalSeconds;
unsigned AppFrameIndex;
unsigned DisplayFrameIndex;
} ovrFrameTiming;
typedef struct ovrEyeRenderDesc_
{
ovrEyeType Eye;
ovrFovPort Fov;
ovrRecti DistortedViewport;
ovrVector2f PixelsPerTanAngleAtCenter;
ovrVector3f HmdToEyeViewOffset;
} ovrEyeRenderDesc;
typedef struct ovrTimewarpProjectionDesc_
{
float Projection22;
float Projection23;
float Projection32;
} ovrTimewarpProjectionDesc;
typedef struct ovrViewScaleDesc_
{
ovrVector3f HmdToEyeViewOffset[ovrEye_Count];
float HmdSpaceToWorldScaleInMeters;
} ovrViewScaleDesc;
typedef enum ovrRenderAPIType_
{
ovrRenderAPI_None,
ovrRenderAPI_OpenGL,
ovrRenderAPI_Android_GLES,
ovrRenderAPI_D3D9_Obsolete,
ovrRenderAPI_D3D10_Obsolete,
ovrRenderAPI_D3D11,
ovrRenderAPI_Count,
ovrRenderAPI_EnumSize = 0x7fffffff
} ovrRenderAPIType;
typedef struct ovrTextureHeader_
{
ovrRenderAPIType API;
ovrSizei TextureSize;
} ovrTextureHeader;
typedef struct ovrTexture_
{
ovrTextureHeader Header;
uintptr_t PlatformData[8];
} ovrTexture;
typedef struct ovrSwapTextureSet_
{
ovrTexture* Textures;
int TextureCount;
int CurrentIndex;
} ovrSwapTextureSet;
typedef enum ovrInitFlags_
{
ovrInit_Debug = 0x00000001,
ovrInit_ServerOptional = 0x00000002,
ovrInit_RequestVersion = 0x00000004,
ovrInit_ForceNoDebug = 0x00000008,
ovrInit_EnumSize = 0x7fffffff
} ovrInitFlags;
typedef enum ovrLogLevel_
{
ovrLogLevel_Debug = 0,
ovrLogLevel_Info = 1,
ovrLogLevel_Error = 2,
ovrLogLevel_EnumSize = 0x7fffffff
} ovrLogLevel;
typedef void (__cdecl* ovrLogCallback)(int level, const char* message);
typedef struct ovrInitParams_
{
uint32_t Flags;
uint32_t RequestedMinorVersion;
ovrLogCallback LogCallback;
uint32_t ConnectionTimeoutMS;
} ovrInitParams;
ovrResult ovr_Initialize(const ovrInitParams* params);
void ovr_Shutdown();
typedef struct ovrErrorInfo_
{
ovrResult Result;
char ErrorString[512];
} ovrErrorInfo;
void ovr_GetLastErrorInfo(ovrErrorInfo* errorInfo);
const char* ovr_GetVersionString();
//int ovr_TraceMessage(int level, const char* message);
ovrResult ovrHmd_Detect();
ovrResult ovrHmd_Create(int index, ovrHmd* pHmd);
ovrResult ovrHmd_CreateDebug(ovrHmdType type, ovrHmd* pHmd);
void ovrHmd_Destroy(ovrHmd hmd);
unsigned int ovrHmd_GetEnabledCaps(ovrHmd hmd);
void ovrHmd_SetEnabledCaps(ovrHmd hmd, unsigned int hmdCaps);
ovrResult ovrHmd_ConfigureTracking(ovrHmd hmd, unsigned int supportedTrackingCaps, unsigned int requiredTrackingCaps);
void ovrHmd_RecenterPose(ovrHmd hmd);
ovrTrackingState ovrHmd_GetTrackingState(ovrHmd hmd, double absTime);
typedef enum ovrLayerType_
{
ovrLayerType_Disabled = 0,
ovrLayerType_EyeFov = 1,
ovrLayerType_EyeFovDepth = 2,
ovrLayerType_QuadInWorld = 3,
ovrLayerType_QuadHeadLocked = 4,
ovrLayerType_Direct = 6,
ovrLayerType_EnumSize = 0x7fffffff
} ovrLayerType;
typedef enum ovrLayerFlags_
{
ovrLayerFlag_HighQuality = 0x01,
ovrLayerFlag_TextureOriginAtBottomLeft = 0x02
} ovrLayerFlags;
typedef struct ovrLayerHeader_
{
ovrLayerType Type;
unsigned Flags;
} ovrLayerHeader;
typedef struct ovrLayerEyeFov_
{
ovrLayerHeader Header;
ovrSwapTextureSet* ColorTexture[ovrEye_Count];
ovrRecti Viewport[ovrEye_Count];
ovrFovPort Fov[ovrEye_Count];
ovrPosef RenderPose[ovrEye_Count];
} ovrLayerEyeFov;
typedef struct ovrLayerEyeFovDepth_
{
ovrLayerHeader Header;
ovrSwapTextureSet* ColorTexture[ovrEye_Count];
ovrRecti Viewport[ovrEye_Count];
ovrFovPort Fov[ovrEye_Count];
ovrPosef RenderPose[ovrEye_Count];
ovrSwapTextureSet* DepthTexture[ovrEye_Count];
ovrTimewarpProjectionDesc ProjectionDesc;
} ovrLayerEyeFovDepth;
typedef struct ovrLayerQuad_
{
ovrLayerHeader Header;
ovrSwapTextureSet* ColorTexture;
ovrRecti Viewport;
ovrPosef QuadPoseCenter;
ovrVector2f QuadSize;
} ovrLayerQuad;
typedef struct ovrLayerDirect_
{
ovrLayerHeader Header;
ovrSwapTextureSet* ColorTexture[ovrEye_Count];
ovrRecti Viewport[ovrEye_Count];
} ovrLayerDirect;
typedef union ovrLayer_Union_
{
ovrLayerHeader Header;
ovrLayerEyeFov EyeFov;
ovrLayerEyeFovDepth EyeFovDepth;
ovrLayerQuad Quad;
ovrLayerDirect Direct;
} ovrLayer_Union;
void ovrHmd_DestroySwapTextureSet(ovrHmd hmd, ovrSwapTextureSet* textureSet);
void ovrHmd_DestroyMirrorTexture(ovrHmd hmd, ovrTexture* mirrorTexture);
ovrSizei ovrHmd_GetFovTextureSize(ovrHmd hmd, ovrEyeType eye, ovrFovPort fov, float pixelsPerDisplayPixel);
ovrEyeRenderDesc ovrHmd_GetRenderDesc(ovrHmd hmd, ovrEyeType eyeType, ovrFovPort fov);
ovrResult ovrHmd_SubmitFrame(ovrHmd hmd, unsigned int frameIndex, const ovrViewScaleDesc* viewScaleDesc, ovrLayerHeader const * const * layerPtrList, unsigned int layerCount);
ovrFrameTiming ovrHmd_GetFrameTiming(ovrHmd hmd, unsigned int frameIndex);
//void ovrHmd_ResetFrameTiming(ovrHmd hmd, unsigned int frameIndex);
double ovr_GetTimeInSeconds();
typedef enum ovrPerfHudMode_
{
ovrPerfHud_Off = 0,
ovrPerfHud_LatencyTiming = 1,
ovrPerfHud_RenderTiming = 2,
ovrPerfHud_Count = 2,
ovrPerfHud_EnumSize = 0x7fffffff
} ovrPerfHudMode;

//ovrBool ovrHmd_GetBool(ovrHmd hmd, const char* propertyName, ovrBool defaultVal);
//ovrBool ovrHmd_SetBool(ovrHmd hmd, const char* propertyName, ovrBool value);
//int ovrHmd_GetInt(ovrHmd hmd, const char* propertyName, int defaultVal);
//ovrBool ovrHmd_SetInt(ovrHmd hmd, const char* propertyName, int value);
//float ovrHmd_GetFloat(ovrHmd hmd, const char* propertyName, float defaultVal);
//ovrBool ovrHmd_SetFloat(ovrHmd hmd, const char* propertyName, float value);
//unsigned int ovrHmd_GetFloatArray(ovrHmd hmd, const char* propertyName, float values[], unsigned int valuesCapacity);
//ovrBool ovrHmd_SetFloatArray(ovrHmd hmd, const char* propertyName, const float values[], unsigned int valuesSize);
//const char* ovrHmd_GetString(ovrHmd hmd, const char* propertyName, const char* defaultVal);
//ovrBool ovrHmd_SetString(ovrHmd hmd, const char* propertyName, const char* value);

typedef enum ovrProjectionModifier_
{
ovrProjection_None = 0x00,
ovrProjection_RightHanded = 0x01,
ovrProjection_FarLessThanNear = 0x02,
ovrProjection_FarClipAtInfinity = 0x04,
ovrProjection_ClipRangeOpenGL = 0x08,
} ovrProjectionModifier;

ovrMatrix4f ovrMatrix4f_Projection(ovrFovPort fov, float znear, float zfar, unsigned int projectionModFlags);
//ovrTimewarpProjectionDesc ovrTimewarpProjectionDesc_FromProjection(ovrMatrix4f projection, unsigned int projectionModFlags);
//ovrMatrix4f ovrMatrix4f_OrthoSubProjection(ovrMatrix4f projection, ovrVector2f orthoScale, float orthoDistance, float hmdToEyeViewOffsetX);
void ovr_CalcEyePoses(ovrPosef headPose, const ovrVector3f hmdToEyeViewOffset[2], ovrPosef outEyePoses[2]);
void ovrHmd_GetEyePoses(ovrHmd hmd, unsigned int frameIndex, const ovrVector3f hmdToEyeViewOffset[2], ovrPosef outEyePoses[2], ovrTrackingState* outHmdTrackingState);
//double ovr_WaitTillTime(double absTime);

// GL stuff
typedef unsigned int GLuint;
typedef struct ovrGLTextureData_s
{
ovrTextureHeader Header;
GLuint TexId;
} ovrGLTextureData;
typedef union ovrGLTexture_s
{
ovrTexture Texture; ///< General device settings.
ovrGLTextureData OGL; ///< OpenGL-specific settings.
} ovrGLTexture;
ovrResult ovrHmd_CreateSwapTextureSetGL(ovrHmd hmd, GLuint format, int width, int height, ovrSwapTextureSet** outTextureSet);
ovrResult ovrHmd_CreateMirrorTextureGL(ovrHmd hmd, GLuint format, int width, int height, ovrTexture** outMirrorTexture);

]]

local ovr = ffi.load(ffi.os == "Windows" and "bin/LibOVR.dll" or error("Oculus really should support not windows, too."))

local ret = {}

--- Initialize the Rift.
-- Quality defaults to 0.9, set lower or higher depending on GPU performance.
-- In practice 0.9 is usually about ideal, but >1 can be used for super sampling
-- the buffers.
-- Usage:
-- 	local rift = ovr.init()
-- 	-- (later)
-- 	rift:shutdown()
-- @param quality scaling factor for render buffers.
function ret.init(quality)
	local rift
	quality = quality or 0.9
	if ovr.ovr_Initialize(nil) == ovr.ovrSuccess then
		rift = {}
		print("Initialized LibOVR")
		local hmd = ffi.new("ovrHmd[?]", 1)
		if ovr.ovrHmd_Create(0, hmd) == ovr.ovrSuccess then
			hmd = hmd[0]
			print("Initialized HMD")

			local flags = ovr.ovrTrackingCap_Orientation
			flags = bit.bor(flags, ovr.ovrTrackingCap_MagYawCorrection)
			flags = bit.bor(flags, ovr.ovrTrackingCap_Position) -- DK2+

			ovr.ovrHmd_SetEnabledCaps(hmd, bit.bor(ovr.ovrHmdCap_LowPersistence, ovr.ovrHmdCap_DynamicPrediction))
			ovr.ovrHmd_ConfigureTracking(hmd, flags, 0)

			rift.hmd = hmd

			local rec_size = ovr.ovrHmd_GetFovTextureSize(hmd, ovr.ovrEye_Left, hmd.DefaultEyeFov[0], quality)
			local rec_size_r = ovr.ovrHmd_GetFovTextureSize(hmd, ovr.ovrEye_Right, hmd.DefaultEyeFov[1], quality)
			rec_size.w = rec_size.w + rec_size_r.w
			rec_size.h = math.max(rec_size.h, rec_size_r.h)

			local function mk_color(hmd, size)
				local swaps = ffi.new("ovrSwapTextureSet*[?]", 1)
				local textures = {}
				assert(ovr.ovrHmd_CreateSwapTextureSetGL(hmd, GL.RGBA, size.w, size.h, swaps) == ovr.ovrSuccess)
				print(string.format("Created %dx%d swap texture set.", size.w, size.h))
				for i = 1, swaps[0].TextureCount do
					local tex = ffi.cast("ovrGLTexture*", swaps[0].Textures[i-1])
					gl.BindTexture(GL.TEXTURE_2D_MULTISAMPLE, tex.OGL.TexId)
					gl.TexParameteri(GL.TEXTURE_2D_MULTISAMPLE, GL.TEXTURE_MIN_FILTER, GL.LINEAR)
					gl.TexParameteri(GL.TEXTURE_2D_MULTISAMPLE, GL.TEXTURE_MAG_FILTER, GL.LINEAR)
					gl.TexParameteri(GL.TEXTURE_2D_MULTISAMPLE, GL.TEXTURE_WRAP_S, GL.CLAMP_TO_EDGE)
					gl.TexParameteri(GL.TEXTURE_2D_MULTISAMPLE, GL.TEXTURE_WRAP_T, GL.CLAMP_TO_EDGE)
					gl.TexImage2DMultisample(GL.TEXTURE_2D_MULTISAMPLE, 4, GL.RGBA8, size.w, size.h, false)
					textures[i] = tex.OGL.TexId
				end
				local fbo = ffi.new("GLuint[?]", 1)
				gl.GenFramebuffers(1, fbo)

				local cpml = require "cpml"
				return {
					swaps = swaps,
					size = cpml.vec2(size.w, size.h),
					textures = textures,
					fbo = fbo
				}
			end

			local function mk_depth(size)
				local dt = ffi.new("GLuint[?]", 1)
				gl.GenTextures(1, dt)
				gl.BindTexture(GL.TEXTURE_2D, dt[0])

				gl.TexParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.LINEAR)
				gl.TexParameteri(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, GL.LINEAR)
				gl.TexParameteri(GL.TEXTURE_2D, GL.TEXTURE_WRAP_S, GL.CLAMP_TO_EDGE)
				gl.TexParameteri(GL.TEXTURE_2D, GL.TEXTURE_WRAP_T, GL.CLAMP_TO_EDGE)

				-- Your shitty system had better have GL_ARB_depth_buffer_float, scrublord.
				gl.TexImage2D(GL.TEXTURE_2D, 0, GL.DEPTH_COMPONENT32F, size.w, size.h, 0, GL.DEPTH_COMPONENT, GL.FLOAT, nil)

				return dt
			end

			local textures = {
				color = {},
				depth = {}
			}
			for i=0,1 do
			local size = ovr.ovrHmd_GetFovTextureSize(hmd, ffi.cast("ovrEyeType", i), hmd.DefaultEyeFov[i], quality)
				textures.color[i] = mk_color(hmd, size)
				textures.depth[i] = mk_depth(size)
			end
			rift.textures = textures

			-- Initialize our single full screen Fov layer.
			local layer = ffi.new("ovrLayerEyeFov")
			layer.Header.Type = ovr.ovrLayerType_EyeFov
			layer.Header.Flags = ovr.ovrLayerFlag_TextureOriginAtBottomLeft

			local rect = ffi.new("ovrRecti[?]", 2)
			rect[1].Pos.x, rect[1].Pos.y = 0, 0
			rect[1].Size.w, rect[1].Size.h = rec_size.w / 2, rec_size.h

			rect[0].Pos.x, rect[0].Pos.y = 0, 0 --rec_size.w / 2, 0
			rect[0].Size.w, rect[0].Size.h = rec_size.w / 2, rec_size.h

			-- Initialize VR structures, filling out description.
			local eyeRenderDesc = ffi.new("ovrEyeRenderDesc*[?]", 2)
			local hmdToEyeViewOffset = ffi.new("ovrVector3f[?]", 2)
			eyeRenderDesc[0] = ovr.ovrHmd_GetRenderDesc(hmd, ovr.ovrEye_Left, hmd.DefaultEyeFov[0])
			eyeRenderDesc[1] = ovr.ovrHmd_GetRenderDesc(hmd, ovr.ovrEye_Right, hmd.DefaultEyeFov[1])

			rift.offsets = {}
			for i = 0, 1 do
				hmdToEyeViewOffset[i] = eyeRenderDesc[i].HmdToEyeViewOffset
				rift.offsets[i] = hmdToEyeViewOffset[i]
				layer.ColorTexture[i] = textures.color[i].swaps[0]
				layer.Viewport[i] = rect[i]
				layer.Fov[i] = eyeRenderDesc[i].Fov
			end

			rift.layer = layer

			rift.fov = {
				[0] = {
					UpTan = eyeRenderDesc[0].Fov.UpTan,
					DownTan = eyeRenderDesc[0].Fov.DownTan,
					LeftTan = eyeRenderDesc[0].Fov.LeftTan,
					RightTan = eyeRenderDesc[0].Fov.RightTan
				},
				[1] = {
					UpTan = eyeRenderDesc[1].Fov.UpTan,
					DownTan = eyeRenderDesc[1].Fov.DownTan,
					LeftTan = eyeRenderDesc[1].Fov.LeftTan,
					RightTan = eyeRenderDesc[1].Fov.RightTan
				}
			}

			-- Create mirror texture and an FBO used to copy mirror texture to back buffer
			local mirrorTexture = ffi.new("ovrGLTexture*[?]", 1)
			local w, h = love.graphics.getDimensions()
			ovr.ovrHmd_CreateMirrorTextureGL(hmd, GL.RGBA, w, h, ffi.cast("ovrTexture**", mirrorTexture))
			rift.mirror_texture = mirrorTexture

			-- Configure the mirror read buffer
			local mirrorFBO = ffi.new("GLuint[?]", 1)
			gl.GenFramebuffers(1, mirrorFBO)
			gl.BindFramebuffer(GL.READ_FRAMEBUFFER, mirrorFBO[0])
			gl.FramebufferTexture2D(GL.READ_FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.TEXTURE_2D, mirrorTexture[0].OGL.TexId, 0)
			gl.FramebufferRenderbuffer(GL.READ_FRAMEBUFFER, GL.DEPTH_ATTACHMENT, GL.RENDERBUFFER, 0)
			gl.BindFramebuffer(GL.READ_FRAMEBUFFER, 0)
			rift.mirror_fbo = mirrorFBO

			local layers = ffi.new("const ovrLayerHeader*[?]", 1)
			layers[0] = rift.layer.Header

			local vsd = ffi.new("ovrViewScaleDesc")
			vsd.HmdSpaceToWorldScaleInMeters = 1.0
			vsd.HmdToEyeViewOffset[0] = rift.offsets[0]
			vsd.HmdToEyeViewOffset[1] = rift.offsets[1]

			rift.layers = layers
			rift.vsd = vsd

			local eye_offsets = ffi.new("ovrVector3f[?]", 2)
			eye_offsets[0] = rift.offsets[0]
			eye_offsets[1] = rift.offsets[1]

			rift.eye_offsets = eye_offsets
		end
	end
	return rift
end

--- Clean up all data used by LibOVR.
-- Call this when shutting down your program.
-- @param rift
function ret.shutdown(rift)
	if type(rift) == "table" then
		if rift.hmd then
			ovr.ovrHmd_Destroy(rift.hmd)
			rift.hmd = nil
			rift.layer = nil
			rift.fov = nil
			print("Shutdown HMD")
		end
		ovr.ovr_Shutdown()
		rift = nil
		print("Shutdown LibOVR")
	end
end

--- Draw a mirror of what is displaying on the Rift.
-- Used to view what is happening on the headset on your monitor.
--
-- Note: Blits directly to the window.
-- @param rift
function ret.draw_mirror(rift)
	if not rift.mirror_texture then
		return
	end
	-- Blit mirror texture to back buffer
	gl.BindFramebuffer(GL.READ_FRAMEBUFFER, rift.mirror_fbo[0])
	gl.BindFramebuffer(GL.DRAW_FRAMEBUFFER, 0)
	local w = rift.mirror_texture[0].OGL.Header.TextureSize.w
	local h = rift.mirror_texture[0].OGL.Header.TextureSize.h
	gl.BlitFramebuffer(0, h, w, 0, 0, 0, w, h, GL.COLOR_BUFFER_BIT, GL.NEAREST)
	gl.BindFramebuffer(GL.READ_FRAMEBUFFER, 0)
end

--- Create a projection matrix appropriate for HMD usage.
-- Convenience function.
--
-- Shortcut for `cpml.mat4():hmd_perspective(rift.fov[eye], near, far, false, false)`.
-- @param rift
-- @param eye eye index
function ret.projection(rift, eye)
	local cpml = require "cpml"
	local fov = assert(rift.fov[eye])
	return cpml.mat4():hmd_perspective(fov, 0.01, 10000, false, false)
end

--- Iterator for processing each view.
-- You should draw the same thing for each eye, just offset with the pose.
-- Usage:
-- 	for eye, pose in rift:eyes() do
-- 		-- eye is a number, pose is an orientation and a position.
-- 		-- Usually used like this (ugly! may be cleaned up later).
-- 		-- cpml.mat4():rotate(pose.orientation:conjugate()):translate(-pose.position)
-- 		draw(eye, pose)
-- 	end
-- This function takes care of frame timings and per-eye render setup for you.
-- @param rift
function ret.eyes(rift)
	if not rift or not rift.hmd then
		return nil
	end

	local eye = -1

	local ft = ovr.ovrHmd_GetFrameTiming(rift.hmd, 0)
	local ts = ovr.ovrHmd_GetTrackingState(rift.hmd, ft.DisplayMidpointSeconds)

	if bit.band(ts.StatusFlags, bit.bor(ovr.ovrStatus_OrientationTracked, ovr.ovrStatus_PositionTracked)) ~= 0 then
		local eye_poses = ffi.new("ovrPosef[?]", 2)
		ovr.ovr_CalcEyePoses(ts.HeadPose.ThePose, rift.eye_offsets, eye_poses)

		rift.layer.RenderPose[0] = eye_poses[0]
		rift.layer.RenderPose[1] = eye_poses[1]
	end

	local idx = ft.AppFrameIndex % 2

	local closure = function()
		if eye >= 1 then
			local w, h = love.graphics.getDimensions()

			gl.FramebufferTexture2D(GL.FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.TEXTURE_2D, 0, 0)
			gl.FramebufferTexture2D(GL.FRAMEBUFFER, GL.DEPTH_ATTACHMENT, GL.TEXTURE_2D, 0, 0)

			gl.BindFramebuffer(GL.FRAMEBUFFER, 0)
			gl.Viewport(0, 0, w, h)
			gl.Clear(bit.bor(tonumber(GL.COLOR_BUFFER_BIT), tonumber(GL.DEPTH_BUFFER_BIT)))

			return nil
		else
			eye = eye + 1

			local cpml        = require "cpml"
			local pose        = rift.layer.RenderPose[eye]
			local orientation = cpml.quat(pose.Orientation.x, pose.Orientation.y, pose.Orientation.z, pose.Orientation.w)
			local position	   = cpml.vec3(pose.Position.x, pose.Position.y, pose.Position.z)

			local texture = {
				color = rift.textures.color[eye],
				depth = rift.textures.depth[eye],
			}
			texture.color.swaps[0].CurrentIndex = idx

			local fbo = texture.color.fbo

			gl.BindFramebuffer(GL.FRAMEBUFFER, fbo[0])
			gl.FramebufferTexture2D(GL.FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.TEXTURE_2D, texture.color.textures[idx+1], 0)
			gl.FramebufferTexture2D(GL.FRAMEBUFFER, GL.DEPTH_ATTACHMENT, GL.TEXTURE_2D, texture.depth[0], 0)

			-- Does the GPU support current FBO configuration?
			local status = gl.CheckFramebufferStatus(GL.FRAMEBUFFER)
			assert(status == GL.FRAMEBUFFER_COMPLETE)

			gl.Viewport(0, 0, texture.color.size.x, texture.color.size.y)
			gl.Clear(bit.bor(tonumber(GL.COLOR_BUFFER_BIT), tonumber(GL.DEPTH_BUFFER_BIT)))

			return eye, { orientation = orientation, position = position }
		end
	end
	return closure
end

--- Submit current frame to Rift.
-- @param rift
function ret.submit_frame(rift)
	assert(ovr.ovrHmd_SubmitFrame(rift.hmd, 0, rift.vsd, rift.layers, 1) == ovr.ovrSuccess)
end

return setmetatable(ret, { __index = ovr })

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;

using NUnit.Framework;

using JetBrains.Application;
using JetBrains.Threading;

using OrderUsings.Configuration;
using OrderUsings.ReSharper.Settings;

[assembly: AssemblyTitle("OrderUsings.ReSharper810.Tests")]
[assembly: AssemblyDescription("Tests for ReSharper v8.1 Order Usings plug-in")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ian Griffiths")]
[assembly: AssemblyProduct("Order Usings")]
[assembly: AssemblyCopyright("Copyright © Ian Griffiths, 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]

[assembly: ComVisible(false)]

/// <summary>
/// Test environment. Must be in the global namespace.
/// </summary>
[SetUpFixture]
// ReSharper disable once CheckNamespace
public class TestEnvironmentAssembly : ReSharperTestEnvironmentAssembly
{
    /// <summary>
    /// Gets the assemblies to load into test environment.
    /// Should include all assemblies which contain components.
    /// </summary>
    /// <returns>
    /// The assemblies to load.
    /// </returns>
    private static IEnumerable<Assembly> GetAssembliesToLoad()
    {
        // Test assembly
        yield return Assembly.GetExecutingAssembly();

        yield return typeof(GroupRule).Assembly;
        yield return typeof(OrderUsingsSettings).Assembly;
    }

    public override void SetUp()
    {
        base.SetUp();
        ReentrancyGuard.Current.Execute(
            "LoadAssemblies",
            () => Shell.Instance.GetComponent<AssemblyManager>().LoadAssemblies(
                GetType().Name, GetAssembliesToLoad()));
    }

    public override void TearDown()
    {
        ReentrancyGuard.Current.Execute(
            "UnloadAssemblies",
            () => Shell.Instance.GetComponent<AssemblyManager>().UnloadAssemblies(
                GetType().Name, GetAssembliesToLoad()));
        base.TearDown();
    }
}


text:
package org.workcraft.plugins.petri.tools;

import java.awt.event.MouseEvent;

import org.workcraft.dom.Node;
import org.workcraft.dom.visual.VisualModel;
import org.workcraft.dom.visual.connections.VisualConnection;
import org.workcraft.gui.events.GraphEditorMouseEvent;
import org.workcraft.gui.graph.tools.ConnectionTool;
import org.workcraft.plugins.petri.PetriNetUtils;
import org.workcraft.plugins.petri.VisualPlace;
import org.workcraft.plugins.petri.VisualReplicaPlace;
import org.workcraft.plugins.petri.VisualTransition;

public class PetriConnectionTool extends ConnectionTool {

    @Override
    public boolean isConnectable(Node node) {
        return (node instanceof VisualPlace)
              || (node instanceof VisualReplicaPlace)
              || (node instanceof VisualTransition);
    }

    @Override
    public String getSecondHintMessage() {
        return super.getSecondHintMessage() + " Hold Shift to create a place proxy.";
    }

    @Override
    public VisualConnection finishConnection(GraphEditorMouseEvent e) {
        VisualConnection connection = super.finishConnection(e);
        if (connection != null) {
            if ((connection.getFirst() instanceof VisualPlace)
                    || (connection.getSecond() instanceof VisualPlace)) {

                if ((e.getModifiers() & MouseEvent.SHIFT_DOWN_MASK) != 0) {
                    VisualModel visualModel = e.getEditor().getModel();
                    connection = PetriNetUtils.replicateConnectedPlace(visualModel, connection);
                }
            }
        }
        return connection;
    }

}


text:
import os
import sys

from pprint import pprint
from random import randint

sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from stream import filter, map, ThreadPool, ProcessPool

## The test data

dataset = []

def alternating(n):
	values = []
	for i in range(1, n+1):
		values.append(i)
		values.append(-i)
	return values

def randomized(n):
	values = []
	for _ in range(n):
		values.append(randint(-sys.maxint, sys.maxint))
	return values

for v in [10, 100, 1000] >> map(alternating):
	dataset.append(v)

for v in [10, 100, 1000] >> map(randomized):
	dataset.append(v)

func = filter(lambda x: x&1)

resultset = dataset >> map(lambda s: s >> func >> set) >> list

## Test scenario

def threadpool(i):
	result = dataset[i] >> ThreadPool(func, poolsize=2) >> set
	pprint(result)
	assert result == resultset[i]

def processpool(i):
	result = dataset[i] >> ProcessPool(func, poolsize=2) >> set
	pprint(result)
	assert result == resultset[i]

## Test cases

def test_ThreadPool():
	for i in range(len(dataset)):
		yield threadpool, i

def test_ProcessPool():
	for i in range(len(dataset)):
		yield processpool, i

if __name__ == '__main__':
	import nose
	nose.main()


text:
package com.codeboy
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._

/**
 * only need sbt 0.13 and scala 2.10.4
 * no need to install any spark
 */
object WordCount {
  def main(args: Array[String]) {
    val myFile = "/etc/passwd" // Should be some file on your system
    val sc = new SparkContext("local", "Simple App")
    val in = sc.textFile(myFile)
    val words = in.map(l => l.split(":")(0))
    	.filter(word => word.startsWith("_") == false)
    	.filter(word => word.startsWith("#") == false)

    val count = words.map(w => (w, 1)).reduceByKey(_ + _)
    println("Word Count Result:============");

    count.foreach(touple => (println(touple._1 + ":" + touple._2)))

    sc.stop()
  }
}


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

<title>no.nordicsemi.android.error</title>
<meta name="date" content="2015-07-22">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package no.nordicsemi.android.error

Class Summary

Class
Description

GattError

Parses the error numbers according to the gatt_api.h file from bluedroid stack.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
package io.github.benas.randombeans.randomizers.range;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * Generate a random {@link LocalDateTime} in the given range.
 *
 * @author Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com)
 */
public class LocalDateTimeRangeRandomizer extends AbstractRangeRandomizer<LocalDateTime> {

    private final LocalDateRangeRandomizer localDateRangeRandomizer;

    private final LocalTimeRangeRandomizer localTimeRangeRandomizer;

    /**
     * Create a new {@link LocalDateTimeRangeRandomizer}.
     *
     * @param min min value
     * @param max max value
     */
    public LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max) {
        super(min, max);
        localDateRangeRandomizer = new LocalDateRangeRandomizer(this.min.toLocalDate(), this.max.toLocalDate());
        localTimeRangeRandomizer = new LocalTimeRangeRandomizer(this.min.toLocalTime(), this.max.toLocalTime());
    }

    /**
     * Create a new {@link LocalDateTimeRangeRandomizer}.
     *
     * @param min  min value
     * @param max  max value
     * @param seed initial seed
     */
    public LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed) {
        super(min, max, seed);
        localDateRangeRandomizer = new LocalDateRangeRandomizer(this.min.toLocalDate(), this.max.toLocalDate(), seed);
        localTimeRangeRandomizer = new LocalTimeRangeRandomizer(this.min.toLocalTime(), this.max.toLocalTime(), seed);
    }

    /**
     * Create a new {@link LocalDateTimeRangeRandomizer}.
     *
     * @param min min value
     * @param max max value
     * @return a new {@link LocalDateTimeRangeRandomizer}.
     */
    public static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max) {
        return new LocalDateTimeRangeRandomizer(min, max);
    }

    /**
     * Create a new {@link LocalDateTimeRangeRandomizer}.
     *
     * @param min  min value
     * @param max  max value
     * @param seed initial seed
     * @return a new {@link LocalDateTimeRangeRandomizer}.
     */
    public static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed) {
        return new LocalDateTimeRangeRandomizer(min, max, seed);
    }

    @Override
    protected void checkValues() {
        if (min.isAfter(max)) {
            throw new IllegalArgumentException("max must be after min");
        }
    }

    @Override
    protected LocalDateTime getDefaultMinValue() {
        return LocalDateTime.MIN;
    }

    @Override
    protected LocalDateTime getDefaultMaxValue() {
        return LocalDateTime.MAX;
    }

    @Override
    public LocalDateTime getRandomValue() {
        LocalDate randomLocalDate = localDateRangeRandomizer.getRandomValue();
        LocalTime randomLocalTime = localTimeRangeRandomizer.getRandomValue();
        return LocalDateTime.of(randomLocalDate, randomLocalTime);
    }

}


text:
import {
  Component, Input, AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit,
    DoCheck, OnChanges, OnDestroy, OnInit, SimpleChanges, Inject, ChangeDetectionStrategy
} from '@angular/core';

import {RubService} from '../services/rub.service';
import {Rub} from '../../model/rub';
import {Spice} from '../../model/spice';
import {SpiceMix} from '../../model/spicemix';
import {MySpiceMix} from '../../model/mySpiceMix';

import {Message, SelectItem} from 'primeng/components/common/api';

import { Router } from '@angular/router';

import 'rxjs/add/operator/switchMap';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/finally';

import { ActivatedRoute, ParamMap } from '@angular/router';
import { Location } from '@angular/common';

import {MY_LOGGING_TOKEN} from '../../shared/token';
import {SpicelistService} from '../../spices/spicelist/services/spicelist.service';
import {MySpice} from '../../model/mySpice';

import { Observable } from 'rxjs/Observable';

import { IAppState } from '../../app.state';
import { select } from '@angular-redux/store';
import { RubActions } from '../../actions/rubs';

export function allRubs(state: IAppState) {
  return state.rubs.all;
}

@Component({
  selector: 'app-rub-detail',
  templateUrl: './rubdetail.component.html'
})
export class RubdetailComponent implements OnInit, OnChanges, DoCheck, AfterContentInit,
  AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy {

  @select(allRubs) myRubs$: Observable<Rub[]>;

  msgs: Message[] = [];
  isDebug = false;

  private paramsIdSubscription$: Subscription;
  private pageSubscription$: Subscription;

  rub: Rub;

  spices: Spice[];

  gewuerzMischung: SpiceMix[];
  spiceMix: SpiceMix = new MySpiceMix(0, 0, 0, 0, '', '', 0, '', new MySpice(0, 0, 0, 0, '', '', '', '', '', ''));
  newspiceMix: boolean;

  selectedSpiceMix: SpiceMix;

  gewuerze: SelectItem[];
  selectedGewuerz: any;

  cols: any[];
  columnOptions: SelectItem[];

  id: number;

  displayDialog: boolean;

  edit$: Subscription;
  delete$: Subscription;

  editSpiceMix$: Subscription;
  addSpiceMix$: Subscription;

  constructor(
    @Inject(MY_LOGGING_TOKEN) loggingToken: boolean,
    private rubService: RubService,
    private spicelistService: SpicelistService,
    private router: Router,
    private route: ActivatedRoute,
    private location: Location,
    private rubsAction: RubActions
  ) {
    this.isDebug = loggingToken;
  }

  ngOnInit() {
    this.showSuccess('GPL Detail init');
    this.id = this.route.snapshot.params['id'];
    this.showSuccess(this.route.snapshot.params['id']);

    this.route.params.subscribe(params => {
      const paramId = params['id'];
    });

    const gpl = this.route.snapshot.data['rub'];

    this.paramsIdSubscription$ = this.route.params.subscribe(params => {
      console.log('GPL Param from subscription: ' + params['id']); // (+) converts string 'id' to a number
    });

    this.pageSubscription$ = this.route
      .queryParams
      .subscribe(params => {
        console.log('GPL Param from subscription Rub Name: ' + JSON.stringify(params));
      });

    this.spicelistService.getSpices().subscribe(
      allSpices => {
        if (this.spices !== undefined) {
          console.log('gesamte Gewuerze: ' + allSpices.length);
        }
        this.spices = allSpices;
        this.generateGewuerze(allSpices);
      },
      error => this.showError(error)
    );

    if (this.id !== null && this.id > 0) {
      this.rub = this.route.snapshot.data['rub'];
      if (this.rub.gewuerzMischung === null || this.rub.gewuerzMischung === undefined ) {
        this.gewuerzMischung = [];
      } else {
        this.gewuerzMischung = this.rub.gewuerzMischung;
      }
    } else {
      this.rubService.getRubTemplate()
        .subscribe(
          (rubTemplate: Rub) => {
            this.rub = rubTemplate;
            this.id = rubTemplate.id;
            this.gewuerzMischung = rubTemplate.gewuerzMischung;
          },
          error => this.showError(error)
        );
    }

    this.cols = [
      {field: 'mengeneinheit', header: 'Mengeneinheit (contains)', sortable: 'true',
        filter: 'true', editable: 'true', filterMatchMode: 'contains', fPlaceholder: 'Search'},
      {field: 'menge', header: 'Menge (startsWith)', sortable: 'true',
        filter: 'true', editable: 'true', filterMatchMode: 'equals', fPlaceholder: 'Search'},
      {field: 'gewuerz.name', header: 'Gewürz (startsWith)', sortable: 'true',
        filter: 'true', editable: 'true', filterMatchMode: 'equals', fPlaceholder: 'Search'},
      {field: 'gewuerz.art', header: 'Art (startsWith)', sortable: 'true',
        filter: 'true', editable: 'true', filterMatchMode: 'equals', fPlaceholder: 'Search'},
      {field: 'gewuerz.beschreibung', header: 'Beschreibung (startsWith)', sortable: 'true',
        filter: 'true', editable: 'true', filterMatchMode: 'equals', fPlaceholder: 'Search'},
      {field: 'gewuerz.url', header: 'URL (startsWith)', sortable: 'true',
        filter: 'true', editable: 'true', filterMatchMode: 'equals', fPlaceholder: 'Search'}

    ];
    this.columnOptions = [];
    for (const col of this.cols) {
      this.columnOptions.push({label: col.header, value: col});
    }
  }

  generateGewuerze(spicesArray: Spice[]) {
    const spiceList: any[] = [];
    for (const spice of spicesArray) {
      const spicArt = spice.art !== undefined && spice.art !== null ? spice.art : '';
      spiceList.push({
        label: spice.name + ' ' + spicArt,
        value: {
          id: spice.id,
          lockVersion: spice.lockVersion,
          creationDate: spice.creationDate,
          modificationDate: spice.modificationDate,
          createdUser: spice.createdUser,
          modificationUser: spice.modificationUser,
          name: spice.name,
          art: spice.art,
          beschreibung: spice.beschreibung,
          url: spice.url
        }
      });
    }
    this.gewuerze = spiceList;
  }

  ngOnChanges(changes: SimpleChanges) {
    const changesMsgs: string[] = [];
    for (const propName in changes) {
      // this.showSuccess(propName);
    }
  }

  // Beware! Called frequently!
  // Called in every change detection cycle anywhere on the page
  ngDoCheck() {
    this.showSuccess(`DoCheck`);
  }

  ngAfterContentInit() {
    this.showSuccess(`AfterContentInit`);
  }

  // Beware! Called frequently!
  // Called in every change detection cycle anywhere on the page
  ngAfterContentChecked() {
    this.showSuccess(`AfterContentChecked`);
  }

  ngAfterViewInit() {
    this.showSuccess(`AfterViewInit`);
  }

  // Beware! Called frequently!
  // Called in every change detection cycle anywhere on the page
  ngAfterViewChecked() {
    this.showSuccess(`AfterViewChecked`);
  }

  ngOnDestroy() {
    this.showSuccess(`OnDestroy`);
    this.paramsIdSubscription$.unsubscribe();
    this.pageSubscription$.unsubscribe();
  }

  goBack(): void {
    this.location.back();
  }

  onRowDblClickCRUD(event: any) {
    // create a clone of the selected employee
    this.newspiceMix = false;
    console.log('onRowSelectCRUD: ' + JSON.stringify(event.data));
    // this.spiceMix = Object.assign({}, event.data);
    this.editSpiceMix();
    // this.displayDialog = true;
  }

  onSelectFocus() {
    this.showSuccess(`OnDestroy`);
  }

  onSelectBlur() {
    this.showSuccess(`OnDestroy`);
  }

  onSelectChange() {
    this.showSuccess(`OnDestroy`);
    this.spiceMix.gewuerz = this.selectedGewuerz;
  }

  save() {
    console.log('GPL Rub detail save: ');

    if (this.rub.id && this.rub.id > 0) {
      this.edit$ = this.rubService.updateRub(this.rub)
        .finally(() => {
        })
        .subscribe(
          (rub: Rub) => {
            this.rub = rub;
          },
          error => this.showError(error)
        );
    } else {
      this.rubService.createRub(this.rub)
        .finally(() => {
        })
        .subscribe(
          (rub: Rub) => {
            this.rub = rub;
            this.router.navigate(['/rublist']);
          },
          error => this.showError(error)
        );
    }

  }

  saveSpiceMix() {
    console.log('saveSpiceMix');
    const gewuerzMischung = [...this.gewuerzMischung];
    if (this.newspiceMix) {
      gewuerzMischung.push(this.spiceMix);
    } else {
      gewuerzMischung[this.findSelectedSpiceMixIndex()] = this.spiceMix;
    }

    if (this.spiceMix.id && this.spiceMix.id > 0) {
      console.log('update');
      // update
      this.editSpiceMix$ = this.spicelistService.updateSpiceMix(this.id, this.spiceMix, this.rub)
        .finally(() => {
          this.spiceMix = null;
          this.displayDialog = false;
        })
        .subscribe(
          () => {
            this.gewuerzMischung.some((element: SpiceMix, index: number) => {
              if (element.id === this.spiceMix.id) {
                this.gewuerzMischung[index] = Object.assign({}, this.spiceMix);
                this.gewuerzMischung = [...this.gewuerzMischung];
                this.selectedSpiceMix = this.gewuerzMischung[index];
                return true;
              }
            });
            this.showSuccess('Spice was successfully updated');
          },
          error => this.showError(error)
        );
    } else {
      // create
      console.log('create');
      this.addSpiceMix$ = this.spicelistService.createSpiceMix(this.id, this.spiceMix)
        .finally(() => {
          this.spiceMix = null;
          this.selectedSpiceMix = null;
          this.displayDialog = false;
        })
        .subscribe(
          (spiceMix: SpiceMix) => {
            this.gewuerzMischung = [...this.gewuerzMischung, spiceMix];
            this.showSuccess('Spice was successfully created');
          },
          error => this.showError(error)
        );
    }
  }

  deleteSpiceMix() {
    console.log('deleteSpiceMix start');
    this.removeSpiceMix();
    console.log('deleteSpiceMix end');
  }

  addSpiceMix() {
    console.log('addSpiceMix start');
    // create an empty employee
    this.newspiceMix = true;
    const mySpice = new MySpice(0, 0, 0, 0, '', '', '', '', '', '');
    const myS = new MySpiceMix(0, 0, 0, 0, '', '', 0, '', mySpice);
    this.spiceMix = new MySpiceMix(0, 0, 0, 0, '', '', 0, '', new MySpice(0, 0, 0, 0, '', '', '', '', '', ''));
    this.router.navigate(['/rubdetail/' + this.rub.id + '/spicemixdetail/' + this.spiceMix.id]);
    // this.displayDialog = true;
    console.log('addSpiceMix end');
  }

  editSpiceMix() {
    console.log('editSpiceMix start');
    // create a clone of the selected employee
    this.spiceMix = Object.assign({}, this.selectedSpiceMix);
    this.router.navigate(['/rubdetail/' + this.rub.id + '/spicemixdetail/' + this.spiceMix.id]);

    // this.displayDialog = true;
    console.log('editSpiceMix end');
  }

  removeSpiceMix() {
    console.log('removeSpiceMix');

    if (this.selectedSpiceMix === null) {
      return;
    }

    if (confirm('Wollen Sie den Rub wirklich löschen?')) {
      const index = this.findSelectedSpiceMixIndex();

      this.delete$ = this.rubService.deleteSpiceMix(this.rub.id, this.selectedSpiceMix.id)
        .finally(() => {
          this.selectedSpiceMix = null;
          this.spiceMix = null;
          this.displayDialog = false;

        })
        .subscribe(
          () => {
            this.gewuerzMischung = this.gewuerzMischung.filter(
              (element: SpiceMix) => element.id !== this.selectedSpiceMix.id);
            this.showSuccess('Rub was successfully removed');
          },
          error => this.showError(error)
        );

      console.log('removed');
    }
  }

  findSelectedSpiceMixIndex(): number {
    return this.gewuerzMischung.indexOf(this.selectedSpiceMix);
  }

  areFormsSaved(): boolean {
    console.log('areFormsSaved');
    return true;
  }

  private showError(errMsg: string) {
    this.msgs = [];
    this.msgs.push({severity: 'error', summary: 'Sorry, an error occurred', detail: errMsg});
  }

  private showSuccess(successMsg: string) {
    this.msgs = [];
    this.msgs.push({severity: 'success', detail: successMsg});
  }

}


text:
/*
 * @test
 * @bug 6618658
 * @summary Deserialization allows creation of mutable SignedObject
 */

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import java.security.SignedObject;

public class Correctness {

    public static void main(String[] args) throws Exception {

        String SIGALG = "SHA1withRSA";
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        KeyPair kp = kpg.generateKeyPair();

        SignedObject so1 = new SignedObject("Hello", kp.getPrivate(),
                Signature.getInstance(SIGALG));

        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(so1);
        out.close();

        byte[] data = byteOut.toByteArray();

        SignedObject so2 = (SignedObject)new ObjectInputStream(
                new ByteArrayInputStream(data)).readObject();

        if (!so2.getObject().equals("Hello")) {
            throw new Exception("Content changed");
        }
        if (!so2.getAlgorithm().equals(SIGALG)) {
            throw new Exception("Signature algorithm unknown");
        }
        if (!so2.verify(kp.getPublic(), Signature.getInstance(SIGALG))) {
            throw new Exception("Not verified");
        }
    }
}


text:
package se.lth.cs.docforia.data;

/**
 * null representation (Singleton)
 */
public class NullRef extends DataRef {

    private NullRef() {

    }

    @Override
    public String stringValue() {
        return "";
    }

    @Override
    public DataRef copy() {
        return this;
    }

    @Override
    public boolean equals(Object o) {
        return o != null && o.getClass() == this.getClass();
    }

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

    public static final NullRef INSTANCE = new NullRef();
}


text:
'use strict';

require('chai').should();

const Translate = require('.');

describe('Translate', () => {
	describe('instantiation', () => {
		it('should reflect the constructor arguments', () => new Translate('A1').ref.should.equal('A1'));
	});

	describe('getting column', () =>
		it('should return Z', () => new Translate('M1').col.should.equal('M'))
	);

	describe('getting column number', () =>
		it('should return 26', () => new Translate('M1').colNum.should.equal(13))
	);

	describe('getting row number', () =>
		it('should return 5', () => new Translate('L5').row.should.equal(5))
	);

	describe('setting column', () =>
		it('should set the correct column', () => {
			const t = new Translate('A1');
			t.col = 'B';
			t.ref.should.equal('B1');
		})
	);

	describe('setting row', () =>
		it('should set the correct row', () => {
			const t = new Translate('A1');
			t.row = 2;
			t.ref.should.equal('A2');
		})
	);

	describe('horizontal translation', () =>
		it('should reflect the horizontal translation', () => new Translate('A1').translate(1,0).ref.should.equal('B1'))
	);

	describe('vertical translation', () =>
		it('should reflect the vertical translation', () => new Translate('A1').translate(0,1).ref.should.equal('A2'))
	);

	describe('vertical and horizontal translations', () =>
		it('should reflect the vertical and horizontal translations', () => new Translate('A1').translate(2,2).ref.should.equal('C3'))
	);

	describe('negative vertical and horizontal translations', () =>
		it('should reflect the vertical and horizontal translations', () => new Translate('D4').translate(-2,-2).ref.should.equal('B2'))
	);

	describe('invalid horizontal translation', () =>
		it('should throw an error', () => (() => new Translate('A1').translate(-1,0)).should.throw(Error))
	);

	describe('invalid vertical translation', () =>
		it('should throw an error', () => (() => new Translate('A1').translate(0,-1)).should.throw(Error))
	);
});


text:
namespace solaire { namespace serial {
	enum serial_type : uint8_t {
		VOID_T,
		CHAR_T,
		BOOL_T,
		UNSIGNED_T,
		SIGNED_T,
		FLOAT_T,
		POINTER_T,
		STRING_T,
		ARRAY_T,
		OBJECT_T
	};

	class value {
	protected:
		union {
			char mChar;
			bool mBool;
			uint64_t mUnsigned;
			int64_t mSigned;
			double mFloat;
			void* mPointer;
		};
		serial_type mType;
	public:
		value();
		value(value&&);
		value(const value&);
		value(char);
		value(bool);
		value(uint8_t);
		value(uint16_t);
		value(uint32_t);
		value(uint64_t);
		value(int8_t);
		value(int16_t);
		value(int32_t);
		value(int64_t);
		value(float);
		value(double);
		value(const c_string&);
		value(const container<value>&);
		value(const std::map<c_string, value>&);
		~value();

		value& operator=(value&&);
		value& operator=(const value&);

		serial_type get_type() const throw();

		bool is_void() const throw();
		bool is_char() const throw();
		bool is_bool() const throw();
		bool is_unsigned() const throw();
		bool is_signed() const throw();
		bool is_float() const throw();
		bool is_pointer() const throw();
		bool is_string() const throw();
		bool is_array() const throw();
		bool is_object() const throw();

		char get_char() const;
		bool get_bool() const;
		uint64_t get_unsigned() const;
		int64_t get_signed() const;
		double get_float() const;
		void* get_pointer() const;
		c_string get_string() const;
		const container<value>& get_array() const;
		const std::map<c_string, value>& get_object() const;

		char& get_char();
		bool& get_bool();
		uint64_t& get_unsigned();
		int64_t& get_signed();
		double& get_float();
		void*& get_pointer();
		c_string& get_string();
		stack<value>& get_array();
		std::map<c_string, value>& get_object();

		void set_void();
		void set_char(char);
		void set_bool(bool);
		void set_unsigned(uint64_t);
		void set_signed(int64_t);
		void set_float(double);
		void set_pointer(void*);
		void set_string(const c_string&);
		void set_array(const container<value>&);
		void set_object(const std::map<c_string, value>&);
	};
}}

#endif


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Histogram of Letter Frequency | D3 Workshop</title>
  <meta name="author" content="David Newbury">

  <meta name="viewport" content="width=device-width, initial-scale=1">

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

  <link rel="stylesheet" href="/globals/normalize.css">
  <link rel="stylesheet" href="/globals/skeleton.css">
  <link rel="stylesheet" href="/globals/base.css">
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.7.0/styles/monokai-sublime.min.css">

  <link rel="icon" type="image/png" href="../globals/favicon.png">

#14: Histogram of Letter Frequency

D3 provides a seris of useful helper methods for data visualization, such as axisBottom or axisLeft.

This is an example of a histogram of letter frequency, taken from http://bl.ocks.org/mbostock/3885304.  The

            <svg width="100%" height="100%"></svg>

            Back to Index
            Prev
            Next

          <form id="codepen" action="http://codepen.io/pen/define" method="POST" target="_blank" >
              <input id="codepen_submit" type="hidden" name="data" value='{}'>
              <input type="submit" value="View on CodePen">
          </form>

This Example's Code

This code block is preceded by initialization code that defines parent, svg, margin, width, & height.

This Example's Data

This written work created as part of this project is licensed under a
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
All code is licensed under a MIT License.

            Thanks to all the wonderful examples, demos and libraries that I've cribbed from while generating this.  You made my learning D3 possible and I hope to pass on that favor to others.


text:
package com.svbio.workflow.base;

import javax.annotation.Nullable;

/**
 * Signals an error while transitioning between lifecycle phases.
 */
public final class LifecycleException extends RuntimeException {
    private static final long serialVersionUID = -6507533140656216132L;

    /**
     * Constructs a new linker exception with the specified detail message.
     *
     * @param message The detail message (which is saved for later retrieval by the {@link #getMessage()} method).
     */
    public LifecycleException(String message) {
        super(message);
    }

    /**
     * Constructs a new linker exception with the specified detail message and cause.
     *
     * @param message The detail message (which is saved for later retrieval by the {@link #getMessage()} method).
     * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). A {@code null}
     *     value is permitted, and indicates that the cause is nonexistent or unknown.
     */
    public LifecycleException(String message, @Nullable Throwable cause) {
        super(message, cause);
    }
}


text:
function initTask(subTask) {
   var state = {};
   var level;
   var answer = null;
   var data = {
      easy: {

      },
      medium: {

      },
      hard: {

      }
   };
   var names = [
      "Julien",
      "Paul",
      "Émilie",
      "César",
      "Hélène",
      "Rodolf",
      "Yasmine"
   ];
   // var initNames = [ 0, 1, 2, 3, 4, 5, 6 ];
   var initNames = [ 3, 2, 4, 0, 1, 5, 6 ];
   var solution = [ 1, 5, 6, 3, 4, 2, 0 ];
   var noScoreNames = initNames;
   var nbNames = names.length;
   var width = 220;
   var height = 250;
   var margin = 10;
   var heightLabel = (height - margin) / nbNames;
   var widthLabel = 160;
   var dragAndDrop;
   var nameDefs;
   var paper;

   subTask.loadLevel = function(curLevel) {
      level = curLevel;
   };

   subTask.getStateObject = function() {
      return state;
   };

   subTask.reloadAnswerObject = function(answerObj) {
      answer = answerObj;
      if(answer){
      }
   };

   subTask.resetDisplay = function() {
      drawPaper();
      reloadAnswer();
   };

   subTask.getAnswerObject = function() {
      return answer;
   };

   subTask.getDefaultAnswerObject = function() {
      var defaultAnswer = initNames.slice(0);
      return defaultAnswer;
   };

   subTask.unloadLevel = function(callback) {
      callback();
   };

   function getResultAndMessage() {
      var result;
      if (Beav.Object.eq(answer, noScoreNames)) {
         result = { successRate: 0, message: taskStrings.moveNames };
      }else if (Beav.Object.eq(answer, solution)) {
         result = { successRate: 1, message: taskStrings.success };
      } else {
         result = { successRate: 0, message: taskStrings.failure };
      }
      return result;
   }

   subTask.getGrade = function(callback) {
      callback(getResultAndMessage());
   };

   var getNameObject = function(iName) {
      var label = paper.rect(-widthLabel/2, -heightLabel/2, widthLabel, heightLabel, heightLabel/5)
                      .attr({'fill': '#E0E0F8'});
      var text = paper.text(0, 0, names[iName])
                      .attr({'font-size' : 15, 'font-weight' : 'bold'});
      $(text.node).css({
         "-webkit-touch-callout": "none",
         "-webkit-user-select": "none",
         "-khtml-user-select": "none",
         "-moz-user-select": "none",
         "-ms-user-select": "none",
         "user-select": "none",
         "cursor" : "default"
      });
      return [label, text];
   }

   var drawPaper = function() {
      paper = subTask.raphaelFactory.create("anim","anim",width, height);
      dragAndDrop = DragAndDropSystem({
         paper : paper,
         drop : function(srcContId, srcPos, dstContId, dstPos, type) {
            displayHelper.stopShowingResult();
            answer = dragAndDrop.getObjects('seq');
         },
         actionIfDropped : function(srcCont, srcPos, dstCont, dstPos, dropType) {
            return (dstCont != null)
         }
      });
      var backgroundTarget = paper.rect(-widthLabel/2,-heightLabel/2,widthLabel,heightLabel)
         .attr('fill', '#6666FF');
      dragAndDrop.addContainer({
         ident : 'seq',
         cx : 120,
         cy : (height-margin)/2,
         widthPlace : widthLabel,
         heightPlace : heightLabel,
         nbPlaces : nbNames,
         dropMode : 'insertBefore',
         dragDisplayMode : 'preview',
         direction : 'vertical',
         align : 'top',
         placeBackgroundArray : [backgroundTarget]
      });

      nameDefs = [];
      for (var pos = 0; pos < names.length; pos++) {
         var iName = initNames[pos];
         nameDefs[iName] = dragAndDrop.insertObject('seq', pos, {ident : iName, elements : getNameObject(iName)});
         paper.text(18, margin+heightLabel/4 + pos * heightLabel, (pos+1))
              .attr({'font-size': 22, 'font-weight': 'bold'});

      }
   };

   var reloadAnswer = function() {
      dragAndDrop.removeAllObjects('seq');
      dragAndDrop.insertObjects('seq', 0, $.map(answer, function(iName) {
         return { ident : iName, elements: getNameObject(iName) };
         }
      ));
   };
}
initWrapper(initTask, ["easy", "medium", "hard"]);
displayHelper.useFullWidth();


text:
<?php

namespace Lollypop\GearBundle\Entity;

use Doctrine\ORM\Mapping AS ORM;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 * Description of User
 *
 * @author seshachalam
 */
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\EquatableInterface;

/**
 * @ORM\Entity
 * @ORM\Table(name="gear_user")
 */
class User extends BaseUser implements EquatableInterface {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="boolean", nullable=false)
     */
    private $is_password_set;

    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     */
    private $first_name;

    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     */
    private $last_name;

    /**
     * @ORM\OneToMany(targetEntity="GCMRegID", mappedBy="user")
     */
    private $gcm_reg_ids;

    /**
     * @ORM\ManyToMany(targetEntity="Location", inversedBy="users")
     * @ORM\JoinTable(name="users_locations")
     */
    private $locations;

    /**
     * @ORM\OneToOne(targetEntity="Location")
     * @ORM\JoinColumn(name="location", referencedColumnName="id", onDelete="CASCADE")
     * */
    private $current_location;

    /**
     * @ORM\Column(type="boolean")
     */
    private $active;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    private $active_at;

    /**
     * @ORM\Column(type="datetime")
     */
    private $created_at;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    private $updated_at;

    /**
     * Constructor
     */
    public function __construct() {

        parent::__construct();

        $this->gcm_reg_ids = new \Doctrine\Common\Collections\ArrayCollection();
        $this->locations = new \Doctrine\Common\Collections\ArrayCollection();
        $this->created_at = new \DateTime();
        $this->plainPassword = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
        $this->is_password_set = false;
        $this->roles = array('ROLE_USER'); //need to check with rams
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId() {
        return $this->id;
    }

    /**
     * Set first_name
     *
     * @param string $firstName
     *
     * @return User
     */
    public function setFirstName($firstName) {
        $this->first_name = $firstName;

        return $this;
    }

    /**
     * Get first_name
     *
     * @return string
     */
    public function getFirstName() {
        return $this->first_name;
    }

    /**
     * Set last_name
     *
     * @param string $lastName
     *
     * @return User
     */
    public function setLastName($lastName) {
        $this->last_name = $lastName;

        return $this;
    }

    /**
     * Get last_name
     *
     * @return string
     */
    public function getLastName() {
        return $this->last_name;
    }

    /**
     * Set email
     *
     * @param string $email
     *
     * @return User
     */
    public function setEmail($email) {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail() {
        return $this->email;
    }

    /**
     * Add gcm_reg_ids
     *
     * @param \Lollypop\GearBundle\Entity\GCMRegID $gcmRegIds
     *
     * @return User
     */
    public function addGcmRegId(\Lollypop\GearBundle\Entity\GCMRegID $gcmRegIds) {
        $this->gcm_reg_ids[] = $gcmRegIds;

        return $this;
    }

    /**
     * Remove gcm_reg_ids
     *
     * @param \Lollypop\GearBundle\Entity\GCMRegID $gcmRegIds
     */
    public function removeGcmRegId(\Lollypop\GearBundle\Entity\GCMRegID $gcmRegIds) {
        $this->gcm_reg_ids->removeElement($gcmRegIds);
    }

    /**
     * Get gcm_reg_ids
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getGcmRegIds() {
        return $this->gcm_reg_ids;
    }

    /**
     * Add locations
     *
     * @param \Lollypop\GearBundle\Entity\Location $locations
     *
     * @return User
     */
    public function addLocation(\Lollypop\GearBundle\Entity\Location $locations) {
        $this->locations[] = $locations;

        return $this;
    }

    /**
     * Remove locations
     *
     * @param \Lollypop\GearBundle\Entity\Location $locations
     */
    public function removeLocation(\Lollypop\GearBundle\Entity\Location $locations) {
        $this->locations->removeElement($locations);
    }

    /**
     * Get locations
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getLocations() {
        return $this->locations;
    }

    /**
     * Set current_location
     *
     * @param \Lollypop\GearBundle\Entity\Location $currentLocation
     *
     * @return User
     */
    public function setCurrentLocation(\Lollypop\GearBundle\Entity\Location $currentLocation = null) {
        $this->current_location = $currentLocation;

        return $this;
    }

    /**
     * Get current_location
     *
     * @return \Lollypop\GearBundle\Entity\Location
     */
    public function getCurrentLocation() {
        return $this->current_location;
    }

    /**
     * Set active
     *
     * @param boolean $active
     *
     * @return User
     */
    public function setActive($active) {
        $this->active = $active;

        return $this;
    }

    /**
     * Get active
     *
     * @return boolean
     */
    public function getActive() {
        return $this->active;
    }

    /**
     * Set active_at
     *
     * @param \DateTime $activeAt
     *
     * @return User
     */
    public function setActiveAt($activeAt) {
        $this->active_at = $activeAt;

        return $this;
    }

    /**
     * Get active_at
     *
     * @return \DateTime
     */
    public function getActiveAt() {
        return $this->active_at;
    }

    /**
     * Set created_at
     *
     * @param \DateTime $createdAt
     * @return User
     */
    public function setCreatedAt($createdAt) {
        $this->created_at = $createdAt;

        return $this;
    }

    /**
     * Get created_at
     *
     * @return \DateTime
     */
    public function getCreatedAt() {
        return $this->created_at;
    }

    /**
     * Set updated_at
     *
     * @param \DateTime $updatedAt
     * @return User
     */
    public function setUpdatedAt($updatedAt) {
        $this->updated_at = $updatedAt;

        return $this;
    }

    /**
     * Get updated_at
     *
     * @return \DateTime
     */
    public function getUpdatedAt() {
        return $this->updated_at;
    }

    public function setIsPasswordSet($isSet) {
        $this->is_password_set = (Boolean) $isSet;

        return $this;
    }

    public function getIsPasswordSet() {
        return $this->is_password_set;
    }

    public function isEqualTo(UserInterface $user) {

        if (!$user instanceof Lollypop\GearBundle\Entity\User) {
            return false;
        }

        if ($this->password !== $user->getPassword()) {
            return false;
        }

        if ($this->salt !== $user->getSalt()) {
            return false;
        }

        if ($this->username !== $user->getUsername()) {
            return false;
        }

        return true;
    }

}


text:
define([ 'jquery', 'underscore', 'backbone', 'models/place', 'collections/places', 'views/places/place', 'text!templates/place-list.html' ],

	function( $ , _ , Backbone , Place, PlaceCollection, ElementView, Tpl){

	var ListView = Backbone.View.extend({

		tagName: "div",
		className: 'place-list',
		template: _.template( Tpl ),

		events: {
			'click #button-add-place': 'clickAdd'
		},

		initialize: function(options){
			this.views = [];
			this.callbacks = [];
			this._fetched = false;

			if(!this.model) {
				this.placeCollection = new PlaceCollection();
				this.placeCollection.fetch();
			}
			else {
				this.placeCollection = this.model;
			}

			this.listenTo(this.placeCollection, 'all', this.populateViews);
			this.listenTo(this.placeCollection, 'sync', this.doCallbacks);
		},

		getCollectionCoords: function(callback) {
			if(this._fetched) {
				this._getCollectionCoords();
			}
			else {
				this.callbacks.push([this._getCollectionCoords, callback]);
			}
		},

		_getCollectionCoords: function(callback) {
			var coords = this.placeCollection.models.map(function(model) {
				return {
					lat: model.get('lat'),
					lon: model.get('lon'),
					icon: 'place',
					infos: '' + model.get('name') + ''
				};
			});

			callback(coords);
		},

		doCallbacks: function() {
			for(var i = 0; i<this.callbacks.length; i++) {
				var func = this.callbacks[i][0];
				var args = this.callbacks[i][1];

				func.call(this, args);
			}

			this.callbacks.length = 0;

			this._fetched = true;
		},

		populateViews: function(){
			//attached views allready present
			if(this.views.length > 0) {
				_.each(this.views, function(view){
					view.remove();
				}, this);

				//avoid memory leaks
				this.views.length = 0;
			}

			_.each(this.placeCollection.models, function(model){
				this.views.push( new ElementView({model: model}) );
			}, this);

			this.render();
		},

		render: function(){
			this.$el.html('');

			_.each(this.views, function(view){
				this.$el.append( view.el );
				view.render();
			}, this);

			this.$el.append(this.template());
		},

		clickAdd: function() {
			var place = new Place();
			this.placeCollection.add(place);

			Backbone.trigger('place-list:add', place);
		}

	});

	return ListView;
});


text:
///////////////////////////////////////////////////////////////////////////////
// Name:        wx/msw/uxtheme.h
// Purpose:     wxUxThemeEngine class: support for XP themes
// Author:      John Platts, Vadim Zeitlin
// Modified by:
// Created:     2003
// Copyright:   (c) 2003 John Platts, Vadim Zeitlin
// Licence:     wxWindows licence
///////////////////////////////////////////////////////////////////////////////

#ifndef _WX_UXTHEME_H_
#define _WX_UXTHEME_H_

#include "wx/defs.h"

#if wxUSE_UXTHEME

#include "wx/msw/private.h"     // we use GetHwndOf()
#include <uxtheme.h>

#if defined(DTPB_WINDOWDC)
// DTPB_WINDOWDC has been added for Vista so it's save to assume that an SDK
// including it has vssym32.h available
#define HAVE_VSSYM32
#endif

#if defined(HAVE_VSSYM32)
#include <vssym32.h>
#else
#include <tmschema.h>
#endif

// ----------------------------------------------------------------------------
// Definitions for legacy Windows SDKs
// ----------------------------------------------------------------------------
// Some definitions introduced with Windows Vista might be missing in older SDKs
// Missing definitions are added here for compatibility

#ifndef VSCLASS_LISTVIEW
#define LISS_NORMAL 1
#define LISS_HOT 2
#define LISS_SELECTED 3
#define LISS_DISABLED 4
#define LISS_SELECTEDNOTFOCUS 5
#define LISS_HOTSELECTED 6
#endif

#ifndef DTT_TEXTCOLOR
#define DTT_TEXTCOLOR       (1UL << 0)      // crText has been specified
#define DTT_STATEID         (1UL << 8)      // IStateId has been specified
#endif

#ifndef DSS_HIDEPREFIX
#define DSS_HIDEPREFIX  0x0200
#define DSS_PREFIXONLY  0x0400
#endif

#ifndef TMT_FONT
#define TMT_FONT	210
#endif

#ifndef HAVE_VSSYM32
enum EXPANDOBUTTONSTATES {
    TDLGEBS_NORMAL = 1,
    TDLGEBS_HOVER = 2,
    TDLGEBS_PRESSED = 3,
    TDLGEBS_EXPANDEDNORMAL = 4,
    TDLGEBS_EXPANDEDHOVER = 5,
    TDLGEBS_EXPANDEDPRESSED = 6,
    TDLGEBS_NORMALDISABLED = 7,
    TDLGEBS_EXPANDEDDISABLED = 8,
};

enum TASKDIALOGPARTS {
    TDLG_PRIMARYPANEL = 1,
    TDLG_MAININSTRUCTIONPANE = 2,
    TDLG_MAINICON = 3,
    TDLG_CONTENTPANE = 4,
    TDLG_CONTENTICON = 5,
    TDLG_EXPANDEDCONTENT = 6,
    TDLG_COMMANDLINKPANE = 7,
    TDLG_SECONDARYPANEL = 8,
    TDLG_CONTROLPANE = 9,
    TDLG_BUTTONSECTION = 10,
    TDLG_BUTTONWRAPPER = 11,
    TDLG_EXPANDOTEXT = 12,
    TDLG_EXPANDOBUTTON = 13,
    TDLG_VERIFICATIONTEXT = 14,
    TDLG_FOOTNOTEPANE = 15,
    TDLG_FOOTNOTEAREA = 16,
    TDLG_FOOTNOTESEPARATOR = 17,
    TDLG_EXPANDEDFOOTERAREA = 18,
    TDLG_PROGRESSBAR = 19,
    TDLG_IMAGEALIGNMENT = 20,
    TDLG_RADIOBUTTONPANE = 21,
};

#define CP_BACKGROUND 2
#define CP_TRANSPARENTBACKGROUND 3
#define CP_BORDER 4
#define CP_READONLY 5
#define CP_DROPDOWNBUTTONRIGHT 6
#define CP_DROPDOWNBUTTONLEFT 7
#define CP_CUEBANNER 8

#define RP_BACKGROUND 6
#define RP_SPLITTER 7
#define RP_SPLITTERVERT 8

enum BORDERSTATES {
    CBB_NORMAL = 1,
    CBB_HOT = 2,
    CBB_FOCUSED = 3,
    CBB_DISABLED = 4,
};

// The MENUPARTS enum is defined in MSVS 2005 SDK, even though it doesn't have
// vssym32.h, but it doesn't define the constants we use, so still define them,
// but make the enum unnamed for compatibility.
enum /* MENUPARTS -- FIXME-VC8: uncomment this when support for it is dropped */
{
    MENU_MENUITEM_TMSCHEMA = 1,
    MENU_SEPARATOR_TMSCHEMA = 6,
    MENU_POPUPBACKGROUND = 9,
    MENU_POPUPBORDERS = 10,
    MENU_POPUPCHECK = 11,
    MENU_POPUPCHECKBACKGROUND = 12,
    MENU_POPUPGUTTER = 13,
    MENU_POPUPITEM = 14,
    MENU_POPUPSEPARATOR = 15,
    MENU_POPUPSUBMENU = 16,
};

enum POPUPITEMSTATES
{
    MPI_NORMAL = 1,
    MPI_HOT = 2,
    MPI_DISABLED = 3,
    MPI_DISABLEDHOT = 4,
};

enum POPUPCHECKBACKGROUNDSTATES
{
    MCB_DISABLED = 1,
    MCB_NORMAL = 2,
    MCB_BITMAP = 3,
};

enum POPUPCHECKSTATES
{
    MC_CHECKMARKNORMAL = 1,
    MC_CHECKMARKDISABLED = 2,
    MC_BULLETNORMAL = 3,
    MC_BULLETDISABLED = 4,
};

#endif

// ----------------------------------------------------------------------------
// End definitions for legacy Windows SDKs
// ----------------------------------------------------------------------------

// Amazingly, GetThemeFont() and GetThemeSysFont() functions use LOGFONTA under
// XP but LOGFONTW (even in non-Unicode build) under later versions of Windows.
// If we declare them as taking LOGFONT below, the code would be able to
// silently pass LOGFONTA to them in ANSI build and would crash at run-time
// under Windows Vista/7 because of a buffer overrun (LOGFONTA being smaller
// than LOGFONTW expected by these functions). If we we declare them as taking
// LOGFONTW, the code wouldn't work correctly under XP. So we use a special
// wxUxThemeFont class to encapsulate this and intentionally change the LOGFONT
// output parameters of the theme functions to take it instead.

class wxUxThemeFont
{
public:
    // Trivial default ctor.
    wxUxThemeFont() { }

#if wxUSE_UNICODE
    // In Unicode build we always use LOGFONT anyhow so this class is
    // completely trivial.
    LPLOGFONTW GetPtr() { return &m_lfW; }
    const LOGFONTW& GetLOGFONT() { return m_lfW; }
#else // !wxUSE_UNICODE
    // Return either LOGFONTA or LOGFONTW pointer as required by the current
    // Windows version.
    LPLOGFONTW GetPtr()
    {
        return UseLOGFONTW() ? &m_lfW
                             : reinterpret_cast<LPLOGFONTW>(&m_lfA);
    }

    // This method returns LOGFONT (i.e. LOGFONTA in ANSI build and LOGFONTW in
    // Unicode one) which can be used with other, normal, Windows or wx
    // functions. Internally it may need to transform LOGFONTW to LOGFONTA.
    const LOGFONTA& GetLOGFONT()
    {
        if ( UseLOGFONTW() )
        {
            // Most of the fields are the same in LOGFONTA and LOGFONTW so just
            // copy everything by default.
            memcpy(&m_lfA, &m_lfW, sizeof(m_lfA));

            // But the face name must be converted from Unicode.
            WideCharToMultiByte(CP_ACP, 0, m_lfW.lfFaceName, -1,
                                m_lfA.lfFaceName, sizeof(m_lfA.lfFaceName),
                                NULL, NULL);
        }

        return m_lfA;
    }

private:
    static bool UseLOGFONTW()
    {
        return wxGetWinVersion() >= wxWinVersion_Vista;
    }

    LOGFONTA m_lfA;
#endif // wxUSE_UNICODE/!wxUSE_UNICODE

private:
    LOGFONTW m_lfW;

    wxDECLARE_NO_COPY_CLASS(wxUxThemeFont);
};

WXDLLIMPEXP_CORE bool wxUxThemeIsActive();

// ----------------------------------------------------------------------------
// wxUxThemeHandle: encapsulates ::Open/CloseThemeData()
// ----------------------------------------------------------------------------

class wxUxThemeHandle
{
public:
    wxUxThemeHandle(const wxWindow *win, const wchar_t *classes)
    {
        m_hTheme = (HTHEME)::OpenThemeData(GetHwndOf(win), classes);
    }

    operator HTHEME() const { return m_hTheme; }

    ~wxUxThemeHandle()
    {
        if ( m_hTheme )
        {
            ::CloseThemeData(m_hTheme);
        }
    }

private:
    HTHEME m_hTheme;

    wxDECLARE_NO_COPY_CLASS(wxUxThemeHandle);
};

#else // !wxUSE_UXTHEME

inline bool wxUxThemeIsActive() { return false; }

#endif // wxUSE_UXTHEME/!wxUSE_UXTHEME

#endif // _WX_UXTHEME_H_


text:
import unittest

from tornadowebapi.transports.basic_rest_transport import BasicRESTTransport

class TestBasicRESTTransport(unittest.TestCase):
    def test_init(self):
        transport = BasicRESTTransport()
        self.assertIsNotNone(transport.renderer)
        self.assertIsNotNone(transport.parser)
        self.assertIsNotNone(transport.serializer)
        self.assertIsNotNone(transport.deserializer)


text:
"""This module is deprecated. Please use `airflow.sensors.python`."""

import warnings

# pylint: disable=unused-import
from airflow.sensors.python import PythonSensor  # noqa

warnings.warn(
    "This module is deprecated. Please use `airflow.sensors.python`.",
    DeprecationWarning, stacklevel=2
)


text:
import Ember from 'ember';
import config from './config/environment';

const Router = Ember.Router.extend({
  location: config.locationType,
  rootURL: config.rootURL
});

Router.map(function() {
  this.route('gist', {path: '/'}, function() {
    this.route('new', {path: '/'});
    // eslint-disable-next-line
    this.route('edit', {path: '/:gistId'}, function() {
      this.route('copy');
      // eslint-disable-next-line
      this.route('revision', {path: '/:revId'});
    });
  });
  this.route('twiddles');
});

export default Router;


text:
package com.common.manager;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.common.app.AbstractRenrenApplication;
import com.common.mcs.HttpProxy;
import com.common.messagecenter.HttpConnection;
import com.common.messagecenter.NewSocketConnection;
import com.common.messagecenter.ReconnectStrategyImpl;
import com.common.messagecenter.base.Connection;
import com.common.messagecenter.base.GetConnectionStateImpl;
import com.common.messagecenter.base.IConnectionManager;
import com.common.messagecenter.base.IMessage;
import com.common.messagecenter.base.Utils;
import com.common.statistics.LocalStatisticsManager;
import com.core.util.CommonUtil;
import com.core.util.SystemService;

public final class ConnectionManager implements IConnectionManager {
	private static final ConnectionManager mConnectionManager = new ConnectionManager();
	private static Connection sConnection = null;
	public static int sNetworkInfo;

	public static ConnectionManager getInstance() {
		return mConnectionManager;
	}

	private ConnectionManager() {
		sGetConnectionState.add(true, GetConnectionStateImpl.instance);
		Connection.setReconnectStrategy(ReconnectStrategyImpl.getInstance());
	}

	/**
	 * 根据网络情况发起连接
	 */
	public void start(Context context) {
		Utils.l("||||\n" + CommonUtil.printStackElements() + "\n||||");
		LocalStatisticsManager.getInstance().uploadBackgroundRunStatistics();

		if(LoginManager.getInstance().isLogoutWithoutReset()){
			return;
		}
		NetworkInfo mobileInfo = SystemService.sConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		NetworkInfo wifiInfo = SystemService.sConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

		/** 需要建立的网络连接类型(socket/http) **/
		final int connType = getNetworkType(mobileInfo, wifiInfo, context);
		/** 当前网络连接情况 **/
		int connInfo = getNetworkInfo(mobileInfo, wifiInfo, context);
		// 当前网络全部断掉时,关闭连接.
		if (connType == Connection.NONETWORK) {
			if (sConnection != null) {
				Utils.log("===============ConnectionManager start disconnect=======================");
				sConnection.disconnect(false);
			}
			sConnection = null;
			return;
		}
		// 假如 1.Connection已连接成功或正在连接 或者 2.Connection连接的时候使用的方式和当前的网络状态一致
		// 不做任何处理。
		if(sConnection != null){
			if (((sConnection.Status == Connection.CONNECTED || sConnection.Status == Connection.CONNECTING)
					&& connType == sConnection.Type && connInfo == sNetworkInfo) && !VpnManager.getInstance().isVpnStateChanged()) {
				Utils.log("do nothing");
				return;
			}
		}
		if(Connection.sIsStopBySingleLogin){
			return;
		}
		sNetworkInfo = connInfo;
		VpnManager.getInstance().refreshVpnState();
		// 网络发生变化,假如有连接,断掉。
		checkConnection();

		if(sConnection != null)
			Connection.sIsChangedByNetwork.set(sConnection.Type != Connection.HTTP);
		else
			Connection.sIsChangedByNetwork.set(true);
		sConnection = null;
		Utils.l("Begin New Connection Object");
		if (connType == Connection.HTTP && "com.renren.mobile.chat".equals(AbstractRenrenApplication.PACKAGE_NAME)) {
			sConnection = new HttpConnection(this);
		} else {
			sConnection = new NewSocketConnection(this);
		}
		sConnection.Type = connType;
		sConnection.start();
	}

	/**
	 * 发送消息
	 *
	 * @param msg
	 */
	public synchronized void sendMessage(IMessage msg) {
		if (sConnection != null) {
			Utils.log(msg.getContent());
			sConnection.sendMessage(msg);
		} else {
			Utils.log("===============connectionManager sendMessage connection is null");
			start(AbstractRenrenApplication.getAppContext());
			if (sConnection != null)
				sConnection.sendMessage(msg);
			else
				msg.onSendFailed("connectionManager sendMessage connection is null");
		}
	}

	/**
	 * 断开连接
	 */
	public synchronized void disConnect() {
		disConnect(true);
	}

	public synchronized void disConnect(boolean isLogout) {
		if (sConnection != null) {
			sConnection.disconnect(isLogout);
		}
	}

	/**
	 * 判断是否连接建立成功
	 *
	 * @return true:建立成功 false:建立失败
	 */
	public synchronized boolean isConnected() {
		if (sConnection == null) {
			return false;
		} else {
			return Connection.isReady.get()
					&& sConnection.Status == Connection.CONNECTED;
		}
	}

	private synchronized void checkConnection() {
		if (sConnection != null && sConnection.Status != Connection.DISCONNECTED) {
			sConnection.disconnect(true);
			sConnection.cleanBeforeReconnect();
		}
	}

	/**
	 * 根据网络情况判断需要建立的连接
	 *
	 * @return Connection.NONETWORK:当前无可用网络 Connection.HTTP:建立HTTP连接
	 *         Connection.SOCKET:建立Socket连接
	 */
	private static int getNetworkType(NetworkInfo mobile, NetworkInfo wifi,
			Context context) {
		if ((mobile == null || !mobile.isConnected()) && (wifi == null || !wifi.isConnected())) {
			return Connection.NONETWORK;
		}

		if (!wifi.isConnected() && mobile.isConnected()
				&& HttpProxy.getProxyNetProxy(context) != null) {
			return Connection.HTTP;
		}
		return Connection.SOCKET;
	}

	private static int getNetworkInfo(NetworkInfo mobile, NetworkInfo wifi,
			Context context) {
		int mobileType = 0;
		int wifiType = 0;
		if (mobile != null && mobile.isConnected()) {
			mobileType = 1;
		}
		if (wifi != null && wifi.isConnected()) {
			wifiType = 2;
		}
		return wifiType | mobileType;
	}
}


text:
package org.lwjgl.opengl;

import org.lwjgl.util.generator.opengl.GLenum;

public interface EXT_blend_equation_separate {

	/**
	 * Accepted by the <pname> parameter of GetBooleanv, GetIntegerv,
	 * GetFloatv, and GetDoublev:
	 */
	int GL_BLEND_EQUATION_RGB_EXT = 0x8009;
	int GL_BLEND_EQUATION_ALPHA_EXT = 0x883D;

	void glBlendEquationSeparateEXT(@GLenum int modeRGB, @GLenum int modeAlpha);
}


text:
'use strict';

import * as mocha from 'mocha';
import { X12Parser, X12Interchange, X12Segment } from '../core';

let fs = require('fs');

describe('X12Parser', () => {

    it('should parse a valid X12 document without throwing an error', () => {
        let edi = fs.readFileSync('tests/test-data/850.edi', 'utf8');
        let parser = new X12Parser(true);
        parser.parseX12(edi);
    });

    it('should produce accurate line numbers for files with line breaks', () => {
        let edi = fs.readFileSync('tests/test-data/850_3.edi', 'utf8');
        let parser = new X12Parser(true);
        let interchange = parser.parseX12(edi);

        let segments = [].concat(
            [interchange.header, interchange.functionalGroups[0].header, interchange.functionalGroups[0].transactions[0].header],
            interchange.functionalGroups[0].transactions[0].segments,
            [interchange.functionalGroups[0].transactions[0].trailer, interchange.functionalGroups[0].trailer, interchange.trailer]
        );

        for (let i = 0; i < segments.length; i++) {
            let segment: X12Segment = segments[i];

            if (i !== segment.range.start.line) {
                throw new Error(`Segment line number incorrect. Expected ${i}, found ${segment.range.start.line}.`);
            }
        }
    });

});


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

using PagedList;

namespace CarService.Web.ViewModels
{
    public class EmployeeDetails : EmployeeIndex
    {
        [Display(Name="Phone number")]
        [DataType(DataType.PhoneNumber)]
        public string PhoneNumber { get; set; }

        [Display(Name="Created documents")]
        public IEnumerable<RepairDocumentSearch> CreatedRepairDocuments { get; set; }

        [Display(Name="Served documents")]
        public IEnumerable<RepairDocumentSearch> ServedRepairDocuments { get; set; }
    }
}


text:
; Test 3: Learning even more about the board: timer in polling mode
; New things to learn:
; - Timer in polling mode
; - MOV-command
; Again my special DEVICE-command
.NOLIST
.INCLUDE "8515def.inc"
.LIST
; universal register definition
.DEF	mp = R16
; Counter for the number of timeouts
.DEF	z1 = R0
; Reset-Vector on adress 0000
	rjmp	main
; Main program starts here
main:
	ldi	mp,LOW(RAMEND) ;Initiate Stackpointer (Subroutines!)
	out	SPL,mp
	ldi	mp,HIGH(RAMEND)
	out	SPH,mp
; Software-Counter-Register to zero
	ldi	mp,0 ; z1 cannot directly be set to zero as it is below R16
	mov	z1,mp ; So set mp to zero and copy to R0
; Prescaler of the timer = 1024, 4 MHz/1024 = 3906,25 Hz
; that equals a timer tick every 256 µs.
	ldi	mp,0x05 ;Initiate Timer/Counter 0 Prescaler
	out	TCCR0,mp ; to Timer 0 Control Register
; Port B is LED-port
	ldi	mp,0xFF ; all bits as output
	out	DDRB,mp ; to data direction register
; Main program loop reads the counter until he reaches zero, increments
; software counter and displays result on the LEDs.
; 256 timer ticks need 65.536 ms, resulting in a frequency of 15.25878906 Hz.
loop:
	in	mp,TCNT0 ; read the 8-bit timer 0
	cpi	mp,0 ; test for zero
	brne	loop ; if not zero branch to loop start
	rcall	IncZ1 ; call subroutine software-timer-increment
	rcall	Display ; call subroutine display-software-counter
warte:
	in	mp,TCNT0 ; again read timer 0
	cpi	mp,0 ; test for zero
	breq	warte ; wait until not zero any more
	rjmp	loop ; start next round
IncZ1:
	inc	z1 ; increment software counter
	ret ; return to the main program
Display:
	mov	mp,z1 ; copy software counter to universal register
	com	mp ; One-complement = XOR(FF) due to reverse LEDs
	out	PORTB,mp ; send to LED port
	ret ; return to the main program