text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateLessonsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('lessons', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('name');
			$table->integer('rankId')->unsigned();
			$table->foreign('rankId')->references('id')->on('rank')->onDelete('cascade');
			$table->string('coverPhoto')->nullable();
			$table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('lessons');
	}

}

redpajama_set_name: RedPajamaGithub


text:
$(function () {
    var $el = $('.b-suggestions');
    $el.find('.js-suggestions-more').click(function () {
        $el.find('.i-hidden').removeClass('i-hidden');
        $(this).remove();
        return false;
    });
});


text:
#pragma once
#include <aws/lightsail/Lightsail_EXPORTS.h>
#include <aws/lightsail/LightsailRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Lightsail
{
namespace Model
{

  /**
   */
  class AWS_LIGHTSAIL_API UpdateBucketBundleRequest : public LightsailRequest
  {
  public:
    UpdateBucketBundleRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "UpdateBucketBundle"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The name of the bucket for which to update the bundle.

     */
    inline const Aws::String& GetBucketName() const{ return m_bucketName; }

    /**
     *
The name of the bucket for which to update the bundle.

     */
    inline bool BucketNameHasBeenSet() const { return m_bucketNameHasBeenSet; }

    /**
     *
The name of the bucket for which to update the bundle.

     */
    inline void SetBucketName(const Aws::String& value) { m_bucketNameHasBeenSet = true; m_bucketName = value; }

    /**
     *
The name of the bucket for which to update the bundle.

     */
    inline void SetBucketName(Aws::String&& value) { m_bucketNameHasBeenSet = true; m_bucketName = std::move(value); }

    /**
     *
The name of the bucket for which to update the bundle.

     */
    inline void SetBucketName(const char* value) { m_bucketNameHasBeenSet = true; m_bucketName.assign(value); }

    /**
     *
The name of the bucket for which to update the bundle.

     */
    inline UpdateBucketBundleRequest& WithBucketName(const Aws::String& value) { SetBucketName(value); return *this;}

    /**
     *
The name of the bucket for which to update the bundle.

     */
    inline UpdateBucketBundleRequest& WithBucketName(Aws::String&& value) { SetBucketName(std::move(value)); return *this;}

    /**
     *
The name of the bucket for which to update the bundle.

     */
    inline UpdateBucketBundleRequest& WithBucketName(const char* value) { SetBucketName(value); return *this;}

    /**
     *
The ID of the new bundle to apply to the bucket.

Use the GetBucketBundles
     * action to get a list of bundle IDs that you can specify.

     */
    inline const Aws::String& GetBundleId() const{ return m_bundleId; }

    /**
     *
The ID of the new bundle to apply to the bucket.

Use the GetBucketBundles
     * action to get a list of bundle IDs that you can specify.

     */
    inline bool BundleIdHasBeenSet() const { return m_bundleIdHasBeenSet; }

    /**
     *
The ID of the new bundle to apply to the bucket.

Use the GetBucketBundles
     * action to get a list of bundle IDs that you can specify.

     */
    inline void SetBundleId(const Aws::String& value) { m_bundleIdHasBeenSet = true; m_bundleId = value; }

    /**
     *
The ID of the new bundle to apply to the bucket.

Use the GetBucketBundles
     * action to get a list of bundle IDs that you can specify.

     */
    inline void SetBundleId(Aws::String&& value) { m_bundleIdHasBeenSet = true; m_bundleId = std::move(value); }

    /**
     *
The ID of the new bundle to apply to the bucket.

Use the GetBucketBundles
     * action to get a list of bundle IDs that you can specify.

     */
    inline void SetBundleId(const char* value) { m_bundleIdHasBeenSet = true; m_bundleId.assign(value); }

    /**
     *
The ID of the new bundle to apply to the bucket.

Use the GetBucketBundles
     * action to get a list of bundle IDs that you can specify.

     */
    inline UpdateBucketBundleRequest& WithBundleId(const Aws::String& value) { SetBundleId(value); return *this;}

    /**
     *
The ID of the new bundle to apply to the bucket.

Use the GetBucketBundles
     * action to get a list of bundle IDs that you can specify.

     */
    inline UpdateBucketBundleRequest& WithBundleId(Aws::String&& value) { SetBundleId(std::move(value)); return *this;}

    /**
     *
The ID of the new bundle to apply to the bucket.

Use the GetBucketBundles
     * action to get a list of bundle IDs that you can specify.

     */
    inline UpdateBucketBundleRequest& WithBundleId(const char* value) { SetBundleId(value); return *this;}

  private:

    Aws::String m_bucketName;
    bool m_bucketNameHasBeenSet = false;

    Aws::String m_bundleId;
    bool m_bundleIdHasBeenSet = false;
  };

} // namespace Model
} // namespace Lightsail
} // namespace Aws


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');$config['module_config'] = array(
	'description'	=> 'Module Invitation',
	'name'		    => 'Invitation',
	'version'		=> '0.0.1',
	'author'		=> 'Jepri Torang Sinaga'
);


text:
/* Kernbauer Version: 2.16 Konfiguration: RH850 Erzeugungsgangnummer: 214 Zweig: 1 */

/*****************************************************************************
| Project Name: MICROSAR OS
|    File Name: osekasm.h
|
|  General code: @Version: 9.01.04@
|  Module version: $vv$=1.01
|
|  Description: contains osek assembler macros
|
|-----------------------------------------------------------------------------
|               C O P Y R I G H T
|-----------------------------------------------------------------------------
| Copyright (c) 2000-2015 Vector Informatik GmbH          All rights reserved.
|****************************************************************************/

/* CovComment 0:  file: osekasm.h */
/* MISRA RULE 19.15 VIOLATION: The QAC-Tool states a violation of rule 19.15 with
 * message 0883 below. Anyhow, there is a double include prevention and therefore,
 * the message is considered to be wrong. */
/* double include preventer */
#ifndef _OSEKASM_H      /* PRQA S 0883 EOF */ /* see MISRA comment above */
#define _OSEKASM_H

/*lint -save Messages inhibited in this file, will be re-enabled at the end of file */
/*lint -e539 Did not expect positive indentation */

#if defined __cplusplus
extern "C"
{
#endif

/* Vector release management */
#if defined USE_QUOTE_INCLUDES
 #include "vrm.h"
#else
 #include <vrm.h>
#endif
/* KB begin vrmReleaseNumber (overwritten) */
/* Source release number */
#define osdVrmMajRelNum 1
#define osdVrmMinRelNum 6
/* KB end vrmReleaseNumber */
#if defined USE_QUOTE_INCLUDES
 #include "vrm.h"
#else
 #include <vrm.h>
#endif

/* KB begin osekStartOfHModule (overwritten) */
/* KB end osekStartOfHModule */

/* KB begin osHWCtrlVarStructAsm (overwritten) */
/* KB end osHWCtrlVarStructAsm */

/* KB begin osekHwOsekGlobalPrototypesAsm (overwritten) */
/* KB end osekHwOsekGlobalPrototypesAsm */

/* KB begin osekHwPrototypesAsm (overwritten) */
#ifndef osdNOASM

#pragma asm
   .macro _osGetCoreSystemStackBottomAddr
   mov    _oskStackTop_SYS_c0, r11 -- r11 = oskStackTop_SYS_c0
   ld.w   0[r11], r11   -- r11 = *(uint32*)r11
   ld.w   0[r11], r11   -- r11 = *(uint32*)r11
   .endm

   .macro _osSwitchToCoreSystemStack
   mov    _oskStackTop_SYS_c0, r11 -- r11 = oskStackTop_SYS_c0
   ld.w   0[r11], r11              -- r11 = *(uint32*)r11
   ld.w   4[r11], sp    -- sp = *(uint32*)(r11+4)
   ld.w   0[r11], r11   -- r11 = *(uint32*)r11
   ldsr   r11, MPLA0    -- MPLA0 = r11
   addi   -4, sp, r11   -- r11 = sp - 4
   ldsr   r11, MPUA0    -- MPUA0 = r11 = osdSystemStack_c0_TOP - 4
   .endm

   .macro _osDisableFEINT
   #if osdUseFEINT==1
   stsr    PSW, r13        -- r13 = PSW
   ori     0x80, r13, r11  -- r11 = r13 | 0x80
   ldsr    r11, PSW        -- PSW = r11 -> disable FE level interrupts
   #endif
   .endm
   .macro _osEnableFEINT
   #if osdUseFEINT==1
   ldsr    r13, PSW        -- PSW = r13 -> enable FE level interrupts
   #endif
   .endm
#pragma endasm

#ifdef osdSoftwareStackCheck
/* MISRA RULE 8.5 VIOLATION: osCheckStackPattern is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osCheckStackPattern is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm void osCheckStackPattern(void) /* PRQA S 1503 */
{                                  /* PRQA S 3406 */
%lab _osCheckStackPatternReturn
   stsr  MPLA0, r11                    -- r11 = MPLA0
   ld.w  0[r11], r11                   -- r11 = *(uint32*)r11 -> get value at stack bottom address given by MPLA0
   mov   osdStackCheckPattern, r12     -- r12 = osdStackCheckPattern
   cmp   r11, r12                      -- compare r11 and r12
   be    _osCheckStackPatternReturn    -- if r11 != r12 then branch to _osCheckStackPatternReturn
   jarl  _osStackOverflowDetected, lp  -- else branch to _osStackOverflowDetected
_osCheckStackPatternReturn:
}

/* MISRA RULE 8.5 VIOLATION: osCheckCurrentStack is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osCheckCurrentStack is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm void osCheckCurrentStack(void) /* PRQA S 1503 */
{                                  /* PRQA S 3406 */
%lab _osStackErrorDetected _osStackCheckReturn
   stsr  MPLA0, r11                 -- r11 = MPLA0
   cmp   r11, sp                    -- compare sp and r11
   bl    _osStackErrorDetected      -- if sp < r11 then branch to _osStackErrorDetected
   ld.w  0[r11], r11                -- r11 = *(uint32*)r11
   mov   osdStackCheckPattern, r12  -- r12 = osdStackCheckPattern
   cmp   r11, r12                   -- compare r11 and r12
   bne   _osStackErrorDetected      -- if r11 == r12 then branch to _osStackErrorDetected
   stsr  MPUA0, r11                 -- r11 = MPUA0
   cmp   r11, sp                    -- compare r11 and sp
   bh    _osStackErrorDetected      -- if sp > r11 then branch to _osStackErrorDetected
   br    _osStackCheckReturn        -- branch to _osStackCheckReturn
_osStackErrorDetected:
   jarl   _osStackOverflowDetected, lp  -- branch to _osStackOverflowDetected
_osStackCheckReturn:
}
#endif

/* MISRA RULE 8.5 VIOLATION: osCheckIntDisabled is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osCheckIntDisabled is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm osuint32 osCheckIntDisabled(void) /* PRQA S 1503 */
{                                     /* PRQA S 3406 */
%lab _osCheckIntDisabledExit
   stsr  PSW, r10                 -- r10 = PSW
   andi  0x20, r10, r10           -- r10 = r10 & 0x20
   cmp   r0, r10                  -- compare r10 != 0
   bne   _osCheckIntDisabledExit  -- if r10 != 0 then branch to _osCheckIntDisabledExit
   stsr  PMR, r10                 -- r10 = PMR
   mov   osdSystemLevelMask, r11  -- r11 = osdSystemLevelMask
   cmp   r11, r10                 -- compare r10 >= r11
   bnl   _osCheckIntDisabledExit  -- if r10 >= r11 then branch to _osCheckIntDisabledExit
   mov   r0, r10                  -- r10 = 0
_osCheckIntDisabledExit:
}

/* MISRA RULE 8.5 VIOLATION: osSetICRxMask is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osSetICRxMask is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm void osSetICRxMask(osuint32 addr) /* PRQA S 1503 */
{                                     /* PRQA S 3406 */
%con addr
   stsr    PSW, r12    -- r12 = PSW
   di                  -- disable interrupts
   mov     addr, r11   -- r11 = addr
   set1    7, 0[r11]   -- set bit 7 at address = r11
   ld.bu   0[r11], r11 -- dummy read
   syncm               -- sync memory
   ldsr    r12, PSW    -- PSW = r12
%reg addr
   stsr    PSW, r12    -- r12 = PSW
   di                  -- disable interrupts
   set1    7, 0[addr]  -- set bit 7 at address = addr
   ld.bu   0[addr], addr -- dummy read
   syncm               -- sync memory
   ldsr    r12, PSW    -- PSW = r12
%error
}

/* MISRA RULE 8.5 VIOLATION: osClearICRxMask is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osClearICRxMask is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm void osClearICRxMask(osuint32 addr) /* PRQA S 1503 */
{                                       /* PRQA S 3406 */
%con addr
   stsr    PSW, r12    -- r12 = PSW
   di                  -- disable interrupts
   mov     addr, r11   -- r11 = addr
   clr1    7, 0[r11]   -- clear bit 7 at address = r11
   ld.bu   0[r11], r11 -- dummy read
   syncm               -- sync memory
   ldsr    r12, PSW    -- PSW = r12
%reg addr
   stsr    PSW, r12    -- r12 = PSW
   di                  -- disable interrupts
   clr1    7, 0[addr]  -- clear bit 7 at address = addr
   ld.bu   0[addr], addr -- dummy read
   syncm               -- sync memory
   ldsr    r12, PSW    -- PSW = r12
%error
}

/* MISRA RULE 8.5 VIOLATION: osGetSPR is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osGetSPR is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm osuint32 osGetSPR(osuint32 regID, osuint32 groupID) /* PRQA S 1503 */
{                                                       /* PRQA S 3406 */
%con regID %con groupID
   stsr   regID, r10, groupID  -- r10 = SPR
%error
}

/* MISRA RULE 8.5 VIOLATION: osSetSPR is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osSetSPR is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm void osSetSPR(osuint32 regID, osuint32 groupID, osuint32 value) /* PRQA S 1503 */
{                                                                   /* PRQA S 3406 */
%con regID %con groupID %con value
   mov    value, r11                -- r11 = value
   ldsr   r11, regID, groupID       -- SPR = r11
%con regID %con groupID %reg value
   ldsr   value, regID, groupID     -- SPR = value
%error
}

/* MISRA RULE 8.5 VIOLATION: osGetPSW is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osGetPSW is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm osuint32 osGetPSW(void) /* PRQA S 1503 */
{                           /* PRQA S 3406 */
   stsr   PSW, r10  -- r10 = PSW
}

/* MISRA RULE 8.5 VIOLATION: osSetPSW is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osSetPSW is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm void osSetPSW(osuint32 value) /* PRQA S 1503 */
{                                 /* PRQA S 3406 */
%reg value
   ldsr   value, PSW  -- PSW = value
%con value
   mov    value, r11  -- r11 = value
   ldsr   r11, PSW    -- PSW = r11
%error
}

/* MISRA RULE 8.5 VIOLATION: osGetEIPSW is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osGetEIPSW is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm osuint32 osGetEIPSW(void) /* PRQA S 1503 */
{                             /* PRQA S 3406 */
   stsr   EIPSW, r10  -- r10 = EIPSW
}

/* MISRA RULE 8.5 VIOLATION: osSetEIPSW is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osSetEIPSW is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm void osSetEIPSW(osuint32 value) /* PRQA S 1503 */
{                                   /* PRQA S 3406 */
%reg value
   ldsr   value, EIPSW  -- EIPSW = value
%con value
   mov    value, r11    -- r11 = value
   ldsr   r11, EIPSW    -- EIPSW = r11
%error
}

/* MISRA RULE 8.5 VIOLATION: osDispatch is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osDispatch is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm void osDispatch(void) /* PRQA S 1503 */
{                         /* PRQA S 3406 */
   nop                          -- improve interrupt latency
   trap 0                       -- trap exception
}

/* MISRA RULE 8.5 VIOLATION: osGetHighPrioBit is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osGetHighPrioBit is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm osuint8 osGetHighPrioBit(osuint32 pattern) /* PRQA S 1503 */
{                                              /* PRQA S 3406 */
%con pattern
   mov    pattern, r10  -- r10 = pattern
   sch1l  r10, r10      -- get first bit from left which is set
   addi   -1, r10, r10  -- adjust position
%mem pattern
   ld.w   pattern, r10  -- r10 = pattern
   sch1l  r10, r10      -- get first bit from left which is set
   addi   -1, r10, r10  -- adjust position
%reg pattern
   sch1l  pattern, r10  -- get first bit from left which is set
   addi   -1, r10, r10  -- adjust position
%error
}

/* MISRA RULE 8.5 VIOLATION: osGetCurrentSP is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osGetCurrentSP is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm osuint32 osGetCurrentSP(void) /* PRQA S 1503 */
{                                 /* PRQA S 3406 */
   mov   sp, r10  -- r10 = sp -> return value = sp
}

/* MISRA RULE 8.5 VIOLATION: osGetDisableGlobal is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osGetDisableGlobal is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm osuint32 osGetDisableGlobal(void) /* PRQA S 1503 */
{                                     /* PRQA S 3406 */
   stsr  PSW, r10        -- r10 = PSW
   di                    -- disable global interrupts
   andi  0x20, r10, r10  -- r10 = r10 & 0x20
}

/* MISRA RULE 8.5 VIOLATION: osGetIntDisableFlag is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osGetIntDisableFlag is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm osuint32 osGetIntDisableFlag(void) /* PRQA S 1503 */
{                                      /* PRQA S 3406 */
   stsr  PSW, r10        -- r10 = PSW
   andi  0x20, r10, r10  -- r10 = r10 & 0x20
}

/* MISRA RULE 8.5 VIOLATION: osGetIntDisableFlagEIPSW is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osGetIntDisableFlagEIPSW is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm osuint32 osGetIntDisableFlagEIPSW(void) /* PRQA S 1503 */
{                                           /* PRQA S 3406 */
   stsr  EIPSW, r10      -- r10 = EIPSW
   andi  0x20, r10, r10  -- r10 = r10 & 0x20
}

/* MISRA RULE 8.5 VIOLATION: osGetDisableGlobalEIPSW is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osGetDisableGlobalEIPSW is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm osuint32 osGetDisableGlobalEIPSW(void) /* PRQA S 1503 */
{                                          /* PRQA S 3406 */
   stsr  EIPSW, r11      -- r11 = EIPSW
   andi  0x20, r11, r10  -- r10 = r11 & 0x20
   ori   0x20, r11, r11  -- r11 = r11 | 0x20
   ldsr  r11, EIPSW      -- EIPSW = r11
}

/* MISRA RULE 8.5 VIOLATION: osEnableGlobalEIPSW is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osEnableGlobalEIPSW is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm void osEnableGlobalEIPSW(void) /* PRQA S 1503 */
{                                  /* PRQA S 3406 */
   stsr  EIPSW, r11       -- r11 = EIPSW
   mov   0xFFFFFFDF, r12  -- r12 = 0xFFFFFFDF
   and   r12, r11         -- r11 = r11 & r12
   ldsr  r11, EIPSW       -- EIPSW = r11
}

/* MISRA RULE 8.5 VIOLATION: osAsmGetISPR is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osAsmGetISPR is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm osuint8 osAsmGetISPR(void) /* PRQA S 1503 */
{                           /* PRQA S 3406 */
   stsr   ISPR, r10  -- r10 = ISPR
}

/* MISRA RULE 8.5 VIOLATION: osSetPMR is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osSetPMR is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm void osSetPMR(osIntLevelType pattern) /* PRQA S 1503 */
{                                         /* PRQA S 3406 */
%reg pattern
   stsr    PSW, r12      -- r12 = PSW
   di                    -- disable interrupts
   ldsr    pattern, PMR  -- PMR = pattern
   ldsr    r12, PSW      -- PSW = r12
%mem pattern
   stsr    PSW, r12      -- r12 = PSW
   di                    -- disable interrupts
   ld.w    pattern, r11  -- r11 = pattern
   ldsr    r11, PMR      -- PMR = r11
   ldsr    r12, PSW      -- PSW = r12
%error
}

/* MISRA RULE 8.5 VIOLATION: osGetLevelPMR is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osGetLevelPMR is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm osIntLevelType osGetLevelPMR(void) /* PRQA S 1503 */
{                                      /* PRQA S 3406 */
   stsr    PSW, r12          -- r12 = PSW
   di                        -- disable interrupts
   stsr    PMR, r10          -- r10 = PMR
   mov     osdPMRHiBit, r11  -- r11 = osdPMRHiBit
   or      r11, r10          -- r10 = r10 | r11
   sch1r   r10, r10          -- get first bit from right which is set
   addi    -1, r10, r10      -- adjust position
   ldsr    r12, PSW          -- PSW = r12
}

/* MISRA RULE 8.5 VIOLATION: osGetLevelISPR is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osGetLevelISPR is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm osIntLevelType osGetLevelISPR(void) /* PRQA S 1503 */
{                                       /* PRQA S 3406 */
   stsr    PSW, r12          -- r12 = PSW
   di                        -- disable interrupts
   stsr    ISPR, r10         -- r10 = ISPR
   mov     osdPMRHiBit, r11  -- r11 = osdPMRHiBit
   or      r11, r10          -- r10 = r10 | r11
   sch1r   r10, r10          -- get first bit from right which is set
   addi    -1, r10, r10      -- adjust position
   ldsr    r12, PSW          -- PSW = r12
}

/* MISRA RULE 8.5 VIOLATION: osSetLevelPMR is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osSetLevelPMR is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm void osSetLevelPMR(osIntLevelType prioLevel) /* PRQA S 1503 */
{                                                /* PRQA S 3406 */
%reg prioLevel
   stsr    PSW, r12        -- r12 = PSW
   di                      -- disable interrupts
   mov     osdPMRMask, r11 -- r11 = osdPMRMask
   shr     prioLevel, r11  -- r11 = r11 >> prioLevel
   shl     prioLevel, r11  -- r11 = r11 << prioLevel
   ldsr    r11, PMR        -- PMR = prioLevel
   ldsr    r12, PSW        -- PSW = r12
%mem prioLevel
   stsr    PSW, r12        -- r12 = PSW
   di                      -- disable interrupts
   mov     osdPMRMask, r11 -- r11 = osdPMRMask
   ld.w    prioLevel, r10  -- r10 = prioLevel
   shr     r10, r11        -- r11 = r11 >> prioLevel
   shl     r10, r11        -- r11 = r11 << prioLevel
   ldsr    r11, PMR        -- PMR = r11
   ldsr    r12, PSW        -- PSW = r12
%error
}

/* MISRA RULE 8.5 VIOLATION: osEnableLevel is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osEnableLevel is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm void osEnableLevel(void) /* PRQA S 1503 */
{                            /* PRQA S 3406 */
   stsr    PSW, r12  -- r12 = PSW
   di                -- disable interrupts
   ldsr    r0, PMR   -- PMR = r0 = 0
   ldsr    r12, PSW  -- PSW = r12
}

/* MISRA RULE 8.5 VIOLATION: osDisableLevel is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osDisableLevel is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm void osDisableLevel(void) /* PRQA S 1503 */
{                             /* PRQA S 3406 */
   stsr    PSW, r12                 -- r12 = PSW
   di                               -- disable interrupts
   mov     osdSystemLevelMask, r11  -- r11 = osdSystemLevelMask
   ldsr    r11, PMR                 -- PMR = r11
   ldsr    r12, PSW                 -- PSW = r12
}

/* MISRA RULE 8.5 VIOLATION: osGetDisableLevel is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osGetDisableLevel is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm osuint32 osGetDisableLevel(void) /* PRQA S 1503 */
{                                    /* PRQA S 3406 */
   stsr    PSW, r12                 -- r12 = PSW
   di                               -- disable interrupts
   stsr    PMR, r10                 -- r10 = PMR
   mov     osdSystemLevelMask, r11  -- r11 = osdSystemLevelMask
   ldsr    r11, PMR                 -- PMR = r11
   ldsr    r12, PSW                 -- PSW = r12
}

/* MISRA RULE 8.5 VIOLATION: osRestoreLevel is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osRestoreLevel is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm void osRestoreLevel(void) /* PRQA S 1503 */
{                             /* PRQA S 3406 */
   stsr    PSW, r12     -- r12 = PSW
   di                   -- disable interrupts
   mov     _ptrToSavedIntLevel_c0, r11  -- r11 = ptrToSavedIntLevel_c0
   ld.w    0[r11], r11  -- r11 = *(uint32)r11 = &osCtrlVarsCore0.LockIsNotNeeded.ossSavedIntLevel
   ld.w    0[r11], r11  -- r11 = *(uint32)r11 = osCtrlVarsCore0.LockIsNotNeeded.ossSavedIntLevel
   ldsr    r11, PMR     -- PMR = r11
   ldsr    r12, PSW     -- PSW = r12
}

/* MISRA RULE 8.5 VIOLATION: osRestoreLevelNested is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osRestoreLevelNested is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm void osRestoreLevelNested(void) /* PRQA S 1503 */
{                                   /* PRQA S 3406 */
   stsr    PSW, r12     -- r12 = PSW
   di                   -- disable interrupts
   mov     _ptrToSavedIntLevelNested_c0, r11  -- r11 = ptrToSavedIntLevelNested_c0
   ld.w    0[r11], r11  -- r11 = *(uint32*)r11 = &osCtrlVarsCore0.LockIsNotNeeded.ossSavedIntLevelNested
   ld.w    0[r11], r11  -- r11 = *(uint32*)r11 = osCtrlVarsCore0.LockIsNotNeeded.ossSavedIntLevelNested
   ldsr    r11, PMR     -- PMR = r11
   ldsr    r12, PSW     -- PSW = r12
}

/* MISRA RULE 8.5 VIOLATION: osGetStackPattern is an assembler macro which is used in
   several modules and therefore the definition has to be given in the header file. */
/* MISRA RULE 14.1 not violated: osGetStackPattern is only used in some configurations.
 * As it is implemented as asm macro it does not harm in the other configurations. */
asm osuint32 osGetStackPattern(void) /* PRQA S 1503 */
{                                    /* PRQA S 3406 */
   stsr   MPLA0, r10   -- r10 = MPLA0         -> get stack bottom address
   ld.w   0[r10], r10  -- r10 = *(uint32*)r10 -> get value at stack bottom address
}

#endif
/* KB end osekHwPrototypesAsm */

/* KB begin osekEndOfHModule (overwritten) */
/* KB end osekEndOfHModule */

#if defined __cplusplus
} /* ENDOF extern "C" */
#endif

/*lint -restore re-enable messages*/

#endif/* double include preventer */

/* END OF HEADER osek.h */


text:
outFile = open('sample3.txt', 'w')
outFile.write('A revised output file!\n')
outFile.write('Write some more.\n')
outFile.close()


text:
package uk.co.fivium.dmda.Server.Enumerations;

public enum LoggingLevels {
    DEBUG("debug")
  , INFO("info")
  , ERROR("error");

  private final String mLevel;

  private LoggingLevels(String pLevel) {
    mLevel = pLevel;
  }

  public String getText(){
    return mLevel;
  }
}


text:
package org.dcm4chex.archive.dcm.storescp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.rmi.RemoteException;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.ejb.CreateException;
import javax.ejb.ObjectNotFoundException;
import javax.xml.transform.Templates;

import org.dcm4che.data.Command;
import org.dcm4che.data.Dataset;
import org.dcm4che.data.DcmDecodeParam;
import org.dcm4che.data.DcmElement;
import org.dcm4che.data.DcmEncodeParam;
import org.dcm4che.data.DcmParser;
import org.dcm4che.data.DcmParserFactory;
import org.dcm4che.dict.Status;
import org.dcm4che.dict.Tags;
import org.dcm4che.dict.VRs;
import org.dcm4che.net.ActiveAssociation;
import org.dcm4che.net.Association;
import org.dcm4che.net.AssociationListener;
import org.dcm4che.net.DcmServiceBase;
import org.dcm4che.net.DcmServiceException;
import org.dcm4che.net.Dimse;
import org.dcm4che.net.PDU;
import org.dcm4che.util.BufferedOutputStream;
import org.dcm4che.util.DAFormat;
import org.dcm4che.util.TMFormat;
import org.dcm4cheri.util.StringUtils;
import org.dcm4chex.archive.codec.CompressCmd;
import org.dcm4chex.archive.common.PrivateTags;
import org.dcm4chex.archive.common.SeriesStored;
import org.dcm4chex.archive.config.CompressionRules;
import org.dcm4chex.archive.config.IssuerOfPatientIDRules;
import org.dcm4chex.archive.ejb.interfaces.FileDTO;
import org.dcm4chex.archive.ejb.interfaces.FileSystemDTO;
import org.dcm4chex.archive.ejb.interfaces.MPPSManager;
import org.dcm4chex.archive.ejb.interfaces.MPPSManagerHome;
import org.dcm4chex.archive.ejb.interfaces.Storage;
import org.dcm4chex.archive.ejb.interfaces.StorageHome;
import org.dcm4chex.archive.ejb.jdbc.QueryFilesCmd;
import org.dcm4chex.archive.util.EJBHomeFactory;
import org.dcm4chex.archive.util.FileUtils;
import org.dcm4chex.archive.util.HomeFactoryException;
import org.dcm4chex.archive.util.XSLTUtils;
import org.jboss.logging.Logger;

/**
 * @author Gunter.Zeilinger@tiani.com
 * @version $Revision: 2514 $
 * @since 03.08.2003
 */
public class StoreScp extends DcmServiceBase implements AssociationListener {

    private static final String STORE_XSL = "cstorerq.xsl";
    private static final String STORE_XML = "-cstorerq.xml";
    private static final String RECEIVE_BUFFER = "RECEIVE_BUFFER";
    private static final String ASSOC_PK = "ASSOC_PK";

	private static final int[] TYPE1_ATTR = { Tags.StudyInstanceUID,
            Tags.SeriesInstanceUID, Tags.SOPInstanceUID, Tags.SOPClassUID, };

    final StoreScpService service;

    private final Logger log;

	private boolean studyDateInFilePath = false;
	private boolean yearInFilePath = true;
	private boolean monthInFilePath = true;
	private boolean dayInFilePath = true;
	private boolean hourInFilePath = false;

	private boolean acceptMissingPatientID = true;
	private boolean acceptMissingPatientName = true;
	private String[] generatePatientID = null;
	private IssuerOfPatientIDRules issuerOfPatientIDRules =
			new IssuerOfPatientIDRules("PACS-:TIANI");

	private boolean serializeDBUpdate = false;
    private int updateDatabaseMaxRetries = 2;
    private int maxCountUpdateDatabaseRetries = 0;

    private boolean storeDuplicateIfDiffMD5 = true;
    private boolean storeDuplicateIfDiffHost = true;
    private long updateDatabaseRetryInterval = 0L;

    private CompressionRules compressionRules = new CompressionRules("");

    private String[] coerceWarnCallingAETs = {};
	private String[] ignorePatientIDCallingAETs = {};

    private boolean checkIncorrectWorklistEntry = true;

	public StoreScp(StoreScpService service) {
        this.service = service;
        this.log = service.getLog();
    }

	public final boolean isAcceptMissingPatientID() {
		return acceptMissingPatientID;
	}

	public final void setAcceptMissingPatientID(boolean accept) {
		this.acceptMissingPatientID = accept;
	}

	public final boolean isAcceptMissingPatientName() {
		return acceptMissingPatientName;
	}

	public final void setAcceptMissingPatientName(boolean accept) {
		this.acceptMissingPatientName = accept;
	}

	public final boolean isSerializeDBUpdate() {
		return serializeDBUpdate;
	}

	public final void setSerializeDBUpdate(boolean serialize) {
		this.serializeDBUpdate = serialize;
	}

    public final String getGeneratePatientID() {
    	if (generatePatientID == null)
    		return "NONE";
    	StringBuffer sb = new StringBuffer();
    	for (int i = 0; i < generatePatientID.length; i++) {
			sb.append(generatePatientID[i]);
		}
		return sb.toString();
	}

	public final void setGeneratePatientID(String pattern) {
		if (pattern.equalsIgnoreCase("NONE"))
		{
			this.generatePatientID = null;
			return;
		}
		int pl = pattern.indexOf('#');
		int pr = pl != -1 ? pattern.lastIndexOf('#') : -1;
		int sl = pattern.indexOf('$');
		int sr = sl != -1 ? pattern.lastIndexOf('$') : -1;
		if (pl == -1 && sl == -1)
		{
			this.generatePatientID = new String[] { pattern };
		} else if (pl != -1 && sl != -1)
		{
			this.generatePatientID = pl < sl
				? split(pattern, pl, pr, sl, sr)
				: split(pattern, sl, sr, pl, pr);

		} else {
			this.generatePatientID = pl != -1
				? split(pattern, pl, pr)
				: split(pattern, sl, sr);
		}

	}

	private String[] split(String pattern, int l1, int r1) {
		return new String[] { pattern.substring(0, l1),
				pattern.substring(l1, r1 + 1), pattern.substring(r1 + 1), };
	}

	private String[] split(String pattern, int l1, int r1, int l2, int r2) {
		if (r1 > l2)
			throw new IllegalArgumentException(pattern);
		return new String[] { pattern.substring(0, l1),
				pattern.substring(l1, r1 + 1), pattern.substring(r1 + 1, l2),
				pattern.substring(l2, r2 + 1), pattern.substring(r2 + 1) };
	}

	public final String getIssuerOfPatientIDRules() {
		return issuerOfPatientIDRules.toString();
	}

	public final void setIssuerOfPatientIDRules(String rules) {
		this.issuerOfPatientIDRules = new IssuerOfPatientIDRules(rules);
	}

    public final String getIgnorePatientIDCallingAETs() {
        return StringUtils.toString(ignorePatientIDCallingAETs, '\\');
	}

	public final void setIgnorePatientIDCallingAETs(String aets) {
        ignorePatientIDCallingAETs = StringUtils.split(aets, '\\');
	}

	public final String getCoerceWarnCallingAETs() {
        return StringUtils.toString(coerceWarnCallingAETs, '\\');
    }

    public final void setCoerceWarnCallingAETs(String aets) {
        coerceWarnCallingAETs = StringUtils.split(aets, '\\');
    }

	public final boolean isStudyDateInFilePath() {
		return studyDateInFilePath;
	}

	public final void setStudyDateInFilePath(boolean studyDateInFilePath) {
		this.studyDateInFilePath = studyDateInFilePath;
	}

	public final boolean isYearInFilePath() {
		return yearInFilePath;
	}

	public final void setYearInFilePath(boolean yearInFilePath) {
		this.yearInFilePath = yearInFilePath;
	}

	public final boolean isMonthInFilePath() {
		return monthInFilePath;
	}

	public final void setMonthInFilePath(boolean monthInFilePath) {
		this.monthInFilePath = monthInFilePath;
	}

    public final boolean isDayInFilePath() {
		return dayInFilePath;
	}

	public final void setDayInFilePath(boolean dayInFilePath) {
		this.dayInFilePath = dayInFilePath;
	}

	public final boolean isHourInFilePath() {
		return hourInFilePath;
	}

	public final void setHourInFilePath(boolean hourInFilePath) {
		this.hourInFilePath = hourInFilePath;
	}

	public final boolean isStoreDuplicateIfDiffHost() {
        return storeDuplicateIfDiffHost;
    }

    public final void setStoreDuplicateIfDiffHost(boolean storeDuplicate) {
        this.storeDuplicateIfDiffHost = storeDuplicate;
    }

    public final boolean isStoreDuplicateIfDiffMD5() {
        return storeDuplicateIfDiffMD5;
    }

    public final void setStoreDuplicateIfDiffMD5(boolean storeDuplicate) {
        this.storeDuplicateIfDiffMD5 = storeDuplicate;
    }

    public final CompressionRules getCompressionRules() {
        return compressionRules;
    }

    public final void setCompressionRules(CompressionRules compressionRules) {
        this.compressionRules = compressionRules;
    }

    public final int getUpdateDatabaseMaxRetries() {
        return updateDatabaseMaxRetries;
    }

    public final void setUpdateDatabaseMaxRetries(int updateDatabaseMaxRetries) {
        this.updateDatabaseMaxRetries = updateDatabaseMaxRetries;
    }

    public final int getMaxCountUpdateDatabaseRetries() {
        return maxCountUpdateDatabaseRetries;
    }

    public final void setMaxCountUpdateDatabaseRetries(int count) {
        this.maxCountUpdateDatabaseRetries = count;
    }

    public final long getUpdateDatabaseRetryInterval() {
        return updateDatabaseRetryInterval;
    }

    public final void setUpdateDatabaseRetryInterval(long interval) {
        this.updateDatabaseRetryInterval = interval;
    }

	/**
	 * @return Returns the checkIncorrectWorklistEntry.
	 */
	public boolean isCheckIncorrectWorklistEntry() {
		return checkIncorrectWorklistEntry;
	}

	/**
	 * @param checkIncorrectWorklistEntry The checkIncorrectWorklistEntry to set.
	 */
	public void setCheckIncorrectWorklistEntry(
			boolean checkIncorrectWorklistEntry) {
		this.checkIncorrectWorklistEntry = checkIncorrectWorklistEntry;
	}

    protected void doCStore(ActiveAssociation activeAssoc, Dimse rq,
            Command rspCmd) throws IOException, DcmServiceException {
        Command rqCmd = rq.getCommand();
        String iuid = rqCmd.getAffectedSOPInstanceUID();
        String cuid = rqCmd.getAffectedSOPClassUID();
        InputStream in = rq.getDataAsStream();
        Association assoc = activeAssoc.getAssociation();
        String callingAET = assoc.getCallingAET();
        File file = null;
        try {
            List duplicates = new QueryFilesCmd(iuid).getFileDTOs();
            if (!(duplicates.isEmpty() || storeDuplicateIfDiffMD5
                    || storeDuplicateIfDiffHost && !containsLocal(duplicates))) {
                log.info("Received Instance[uid=" + iuid
                        + "] already exists - ignored");
                return;
            }

            DcmDecodeParam decParam = DcmDecodeParam.valueOf(rq
                    .getTransferSyntaxUID());
            Dataset ds = objFact.newDataset();
            DcmParser parser = DcmParserFactory.getInstance().newDcmParser(in);
            parser.setDcmHandler(ds.getDcmHandler());
            parser.parseDataset(decParam, Tags.PixelData);
			log.debug("Dataset:\n");
			log.debug(ds);
            service.logDIMSE(assoc, STORE_XML, ds);
            checkDataset(assoc, rqCmd, ds);
            if ( isCheckIncorrectWorklistEntry() && checkIncorrectWorklistEntry(ds) ) {
                log.info("Received Instance[uid=" + iuid
                        + "] ignored! Reason: Incorrect Worklist entry selected!");
                return;
            }
            FileSystemDTO fsDTO = service.selectStorageFileSystem();
            File baseDir = FileUtils.toFile(fsDTO.getDirectoryPath());
            file = makeFile(baseDir, ds);
            String compressTSUID = parser.getReadTag() == Tags.PixelData
                    && parser.getReadLength() != -1 ? compressionRules
                    .getTransferSyntaxFor(assoc, ds) : null;
            String tsuid = compressTSUID != null ? compressTSUID : rq
                    .getTransferSyntaxUID();
			ds.setFileMetaInfo(objFact.newFileMetaInfo(
					rqCmd.getAffectedSOPClassUID(),
					rqCmd.getAffectedSOPInstanceUID(),
                    tsuid ));

            byte[] md5sum = storeToFile(parser, ds, file, getByteBuffer(assoc));
            if (md5sum != null && ignoreDuplicate(duplicates, md5sum)) {
                log.info("Received Instance[uid=" + iuid
                        + "] already exists - ignored");
                deleteFailedStorage(file);
                return;
            }

            final int baseDirPathLength = baseDir.getPath().length();
            final String filePath = file.getPath().substring(
                    baseDirPathLength + 1).replace(File.separatorChar, '/');
            ds.setPrivateCreatorID(PrivateTags.CreatorID);
            ds.putAE(PrivateTags.CallingAET, assoc.getCallingAET());
            ds.putAE(PrivateTags.CalledAET, assoc.getCalledAET());
            ds.putAE(Tags.RetrieveAET, fsDTO.getRetrieveAET());
            Dataset coerced = null;
    		try {
    			Templates stylesheet = service.getCoercionTemplatesFor(callingAET, STORE_XSL);
    			if (stylesheet != null)
    			{
    				coerced = XSLTUtils.coerce(ds, stylesheet,
    						toXsltParam(assoc, new Date()));
    			}
    		} catch (Exception e) {
    			log.warn("Coercion of attributes failed:", e);
    		}
            Storage store = getStorage(assoc);
            Long assocpk = (Long) assoc.getProperty(ASSOC_PK);
            if (assocpk == null) {
                assocpk = store.initAssociation(assoc.getCallingAET(),
                        assoc.getCalledAET(), fsDTO.getRetrieveAET());
                assoc.putProperty(ASSOC_PK, assocpk);
            } else {
                String seriuid = ds.getString(Tags.SeriesInstanceUID);
                SeriesStored seriesStored = store.checkSeriesStored(assocpk,
                        seriuid);
                if (seriesStored != null) {
                    log.debug("Send SeriesStoredNotification - series changed");
                    doAfterSeriesIsStored(store, assoc.getSocket(), seriesStored);
                    store.resetAssociation(assocpk);
                }
            }
            Dataset coercedElements = updateDB(store, assocpk , ds,
                    fsDTO.getDirectoryPath(), filePath, file, md5sum);
            ds.putAll(coercedElements, Dataset.MERGE_ITEMS);
            if (coerced == null)
            	coerced = coercedElements;
            else
            	coerced.putAll(coercedElements, Dataset.MERGE_ITEMS);
            if (coerced.isEmpty()
                    || !contains(coerceWarnCallingAETs, assoc.getCallingAET())) {
                rspCmd.putUS(Tags.Status, Status.Success);
            } else {
                int[] coercedTags = new int[coerced.size()];
                Iterator it = coerced.iterator();
                for (int i = 0; i < coercedTags.length; i++) {
                    coercedTags[i] = ((DcmElement) it.next()).tag();
                }
                rspCmd.putAT(Tags.OffendingElement, coercedTags);
                rspCmd.putUS(Tags.Status, Status.CoercionOfDataElements);
            }
        } catch (DcmServiceException e) {
            log.warn(e.getMessage(), e);
            deleteFailedStorage(file);
            throw e;
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            deleteFailedStorage(file);
            throw new DcmServiceException(Status.ProcessingFailure, e);
        }
    }

    private boolean checkIncorrectWorklistEntry(Dataset ds) throws Exception {
        Dataset refPPS = ds.getItem(Tags.RefPPSSeq);
        if (refPPS == null) {
            return false;
        }
        String ppsUID = refPPS.getString(Tags.RefSOPInstanceUID);
        if ( ppsUID == null ) {
            return false;
        }
        Dataset mpps;
        try {
            mpps = getMPPSManager().getMPPS(ppsUID);
        } catch (ObjectNotFoundException e) {
            return false;
        }
        Dataset item = mpps.getItem(Tags.PPSDiscontinuationReasonCodeSeq);
        return item != null && "110514".equals(item.getString(Tags.CodeValue)) &&
                "DCM".equals(item.getString(Tags.CodingSchemeDesignator));
    }

    private MPPSManager getMPPSManager() throws CreateException,
            RemoteException, HomeFactoryException {
        return ((MPPSManagerHome) EJBHomeFactory.getFactory().lookup(
                MPPSManagerHome.class, MPPSManagerHome.JNDI_NAME)).create();
    }

	private Map toXsltParam(Association a, Date now) {
		HashMap param = new HashMap();
		param.put("calling", a.getCallingAET());
		param.put("called", a.getCalledAET());
		param.put("date", new DAFormat().format(now));
		param.put("time", new TMFormat().format(now));
		return null;
	}

	private byte[] getByteBuffer(Association assoc) {
		byte[] buf = (byte[]) assoc.getProperty(RECEIVE_BUFFER);
		if (buf == null) {
			buf = new byte[service.getBufferSize()];
			assoc.putProperty(RECEIVE_BUFFER, buf);
		}
		return buf;
	}

	private boolean containsLocal(List duplicates) {
        for (int i = 0, n = duplicates.size(); i < n; ++i) {
            FileDTO dto = (FileDTO) duplicates.get(i);
            if (service.isLocalRetrieveAET(dto.getRetrieveAET()))
                return true;
        }
        return false;
    }

    private boolean ignoreDuplicate(List duplicates, byte[] md5sum) {
        for (int i = 0, n = duplicates.size(); i < n; ++i) {
            FileDTO dto = (FileDTO) duplicates.get(i);
            if (storeDuplicateIfDiffMD5
                    && !Arrays.equals(md5sum, dto.getFileMd5()))
                continue;
            if (storeDuplicateIfDiffHost
                    && !service.isLocalRetrieveAET(dto.getRetrieveAET()))
                continue;
            return true;
        }
        return false;
    }

    private void deleteFailedStorage(File file) {
        if (file == null)
            return;
        log.info("M-DELETE file:" + file);
        file.delete();
        // purge empty series and study directory
        File seriesDir = file.getParentFile();
        if (seriesDir.delete())
            seriesDir.getParentFile().delete();
    }

    protected Dataset updateDB(Storage storage, Long assocpk, Dataset ds,
            String baseDir, String filePath, File file, byte[] md5)
            throws DcmServiceException, CreateException, HomeFactoryException,
            IOException {
        int retry = 0;
        for (;;) {
            try {
                if (serializeDBUpdate) {
                    synchronized (storage) {
                        return storage.store(assocpk, ds, baseDir, filePath,
                                (int) file.length(), md5);
                    }
                } else {
                    return storage.store(assocpk, ds, baseDir, filePath,
                            (int) file.length(), md5);
                }
            } catch (Exception e) {
                ++retry;
                if (retry > updateDatabaseMaxRetries) {
                    service.getLog().error(
                            "failed to update DB with entries for received "
                                    + file, e);
                    throw new DcmServiceException(Status.ProcessingFailure, e);
                }
                maxCountUpdateDatabaseRetries = Math.max(retry,
                        maxCountUpdateDatabaseRetries);
                service.getLog().warn(
                        "failed to update DB with entries for received " + file
                                + " - retry", e);
                try {
                    Thread.sleep(updateDatabaseRetryInterval);
                } catch (InterruptedException e1) {
                    log.warn("update Database Retry Interval interrupted:", e1);
                }
            }
        }
    }

    Storage getStorage(Association assoc) throws RemoteException, CreateException,
            HomeFactoryException {
        Storage store = (Storage) assoc.getProperty(StorageHome.JNDI_NAME);
        if (store == null) {
            store = service.getStorage();
            assoc.putProperty(StorageHome.JNDI_NAME, store);
        }
        return store;
    }

    private File makeFile(File basedir, Dataset ds) throws IOException {
        Calendar date = Calendar.getInstance();
		if (studyDateInFilePath) {
			Date studyDate = ds.getDate(Tags.StudyDate, Tags.StudyTime);
			if (studyDate != null)
				date.setTime(studyDate);
		}
		StringBuffer filePath = new StringBuffer();
		if (yearInFilePath) {
			filePath.append(String.valueOf(date.get(Calendar.YEAR)));
			filePath.append(File.separatorChar);
		}
		if (monthInFilePath) {
			filePath.append(String.valueOf(date.get(Calendar.MONTH) + 1));
			filePath.append(File.separatorChar);
		}
		if (dayInFilePath) {
			filePath.append(String.valueOf(date.get(Calendar.DAY_OF_MONTH)));
			filePath.append(File.separatorChar);
		}
		if (hourInFilePath) {
			filePath.append(String.valueOf(date.get(Calendar.HOUR_OF_DAY)));
			filePath.append(File.separatorChar);
		}
		filePath.append(toHex(ds.getString(Tags.StudyInstanceUID).hashCode()));
		filePath.append(File.separatorChar);
		filePath.append(toHex(ds.getString(Tags.SeriesInstanceUID).hashCode()));
        File dir = new File(basedir, filePath.toString());
        if (!dir.exists()) {
            dir.mkdirs();
        }
		return FileUtils.createNewFile(dir, ds.getString(Tags.SOPInstanceUID).hashCode());
    }

    private byte[] storeToFile(DcmParser parser, Dataset ds, File file, byte[] buffer)
    		throws Exception {
        log.info("M-WRITE file:" + file);
        MessageDigest md = null;
        BufferedOutputStream bos = null;
        if (service.isMd5sum()) {
            md = MessageDigest.getInstance("MD5");
            DigestOutputStream dos = new DigestOutputStream(
                    new FileOutputStream(file), md);
            bos = new BufferedOutputStream(dos, buffer);
        } else {
            bos = new BufferedOutputStream(new FileOutputStream(file), buffer);
        }
        try {
            DcmDecodeParam decParam = parser.getDcmDecodeParam();
            String tsuid = ds.getFileMetaInfo().getTransferSyntaxUID();
			DcmEncodeParam encParam = DcmEncodeParam.valueOf(tsuid);
            CompressCmd compressCmd = null;
            if (!decParam.encapsulated && encParam.encapsulated) {
                compressCmd = CompressCmd.createCompressCmd(ds, tsuid);
                compressCmd.coerceDataset(ds);
            }
            ds.writeFile(bos, encParam);
            if (parser.getReadTag() == Tags.PixelData) {
	            int len = parser.getReadLength();
	            InputStream in = parser.getInputStream();
	            if (encParam.encapsulated) {
	                ds.writeHeader(bos, encParam, Tags.PixelData, VRs.OB, -1);
	                if (decParam.encapsulated) {
	                    parser.parseHeader();
	                    while (parser.getReadTag() == Tags.Item) {
	                        len = parser.getReadLength();
	                        ds.writeHeader(bos, encParam, Tags.Item, VRs.NONE, len);
	                        bos.copyFrom(in, len);
	                        parser.parseHeader();
	                    }
	                } else {
	                    int read = compressCmd.compress(decParam.byteOrder, parser
	                            .getInputStream(), bos);
	                    in.skip(parser.getReadLength() - read);
	                }
	                ds.writeHeader(bos, encParam, Tags.SeqDelimitationItem,
	                        VRs.NONE, 0);
	            } else {
	                ds.writeHeader(bos, encParam, Tags.PixelData, parser
	                        .getReadVR(), len);
	                bos.copyFrom(in, len);
	            }
	            parser.parseDataset(decParam, -1);
	            ds.subSet(Tags.PixelData, -1).writeDataset(bos, encParam);
            }
        } finally {
            // We don't want to ignore the IOException since in rare cases the close() may cause
            // exception due to running out of physical space while the File System still holds
            // some internally cached data. In this case, we do want to fail this C-STORE.
            bos.close();
        }
        return md != null ? md.digest(): null;
    }

    private void checkDataset(Association assoc, Command rqCmd, Dataset ds)
            throws DcmServiceException {
        for (int i = 0; i < TYPE1_ATTR.length; ++i) {
            if (ds.vm(TYPE1_ATTR[i]) <= 0) {
                throw new DcmServiceException(
                        Status.DataSetDoesNotMatchSOPClassError,
                        "Missing Type 1 Attribute "
                                + Tags.toString(TYPE1_ATTR[i]));
            }
        }
        if (!rqCmd.getAffectedSOPInstanceUID().equals(
                ds.getString(Tags.SOPInstanceUID))) {
            throw new DcmServiceException(
                    Status.DataSetDoesNotMatchSOPClassError,
                    "SOP Instance UID in Dataset differs from Affected SOP Instance UID");
        }
        if (!rqCmd.getAffectedSOPClassUID().equals(
                ds.getString(Tags.SOPClassUID))) {
            throw new DcmServiceException(
                    Status.DataSetDoesNotMatchSOPClassError,
                    "SOP Class UID in Dataset differs from Affected SOP Class UID");
        }
		String pid = ds.getString(Tags.PatientID);
		String pname = ds.getString(Tags.PatientName);
		if (pid == null && !acceptMissingPatientID) {
            throw new DcmServiceException(
                    Status.DataSetDoesNotMatchSOPClassError,
                    "Acceptance of objects without Patient ID is disabled");
		}
		if (pname == null && !acceptMissingPatientName) {
            throw new DcmServiceException(
                    Status.DataSetDoesNotMatchSOPClassError,
                    "Acceptance of objects without Patient Name is disabled");
		}
		if (contains(ignorePatientIDCallingAETs, assoc.getCallingAET())) {
			log.info("Ignore Patient ID " + pid
					+ " for Patient Name " + pname
					+ " in object received from " + assoc.getCallingAET());
			pid = null;
			ds.putLO(Tags.PatientID, pid);
		}
		if (pid == null && generatePatientID != null) {
			if (generatePatientID != null) {
				pid = generatePatientID(ds);
				ds.putLO(Tags.PatientID, pid);
				log.info("Add generated Patient ID " + pid
						+ " for Patient Name " + pname);
			}
		}
		if (pid != null) {
			String issuer = ds.getString(Tags.IssuerOfPatientID);
			if (issuer == null) {
				issuer = issuerOfPatientIDRules.issuerOf(pid);
				if (issuer != null) {
					ds.putLO(Tags.IssuerOfPatientID, issuer);
					log.info("Add missing Issuer Of Patient ID " + issuer
							+ " for Patient ID " + pid
							+ " and Patient Name " + pname);
				}
			}
		}
    }

    private boolean contains(Object[] a, Object e) {
        for (int i = 0; i < a.length; i++) {
            if (a[i].equals(e)) {
                return true;
            }
        }
        return false;
    }

    private String generatePatientID(Dataset ds) {
    	if (generatePatientID.length == 1)
    		return generatePatientID[0];

    	int suidHash = ds.getString(Tags.StudyInstanceUID).hashCode();
    	String pname = ds.getString(Tags.PatientName);
    	// generate different Patient IDs for different studies
    	// if no Patient Name
    	int pnameHash = pname == null || pname.length() == 0 ? suidHash
    			:  37 * ds.getString(Tags.PatientName).hashCode()
    					+ ds.getString(Tags.PatientBirthDate, "").hashCode();

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < generatePatientID.length; i++) {
			append(sb, generatePatientID[i], pnameHash, suidHash);
		}
		return sb.toString();
	}

	private void append(StringBuffer sb, String s, int pnameHash, int suidHash) {
		final int l = s.length();
		if (l == 0)
			return;
		char c = s.charAt(0);
		if (c != '#' && c != '$')
		{
			sb.append(s);
			return;
		}
		String v = Long.toString((c == '#' ? pnameHash : suidHash) & 0xffffffffL);
		for (int i = v.length() - l; i < 0; i++)
			sb.append('0');
		sb.append(v);
	}

	private static char[] HEX_DIGIT = { '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    private String toHex(int val) {
        char[] ch8 = new char[8];
        for (int i = 8; --i >= 0; val >>= 4) {
            ch8[i] = HEX_DIGIT[val & 0xf];
        }
        return String.valueOf(ch8);
    }

    // Implementation of AssociationListener

    public void write(Association src, PDU pdu) {
    }

    public void received(Association src, PDU pdu) {
    }

    public void write(Association src, Dimse dimse) {
    }

    public void received(Association src, Dimse dimse) {
    }

    public void error(Association src, IOException ioe) {
    }

    public void closing(Association assoc) {
    }

    public void closed(Association assoc) {
        Long assocpk = (Long) assoc.getProperty(ASSOC_PK);
        if (assocpk != null) {
            try {
                Storage store = getStorage(assoc);
                SeriesStored seriesStored = store.checkSeriesStored(assocpk,
                        null);
                if (seriesStored != null) {
                    log.debug("Send SeriesStoredNotification - association closed");
                    doAfterSeriesIsStored(store, assoc.getSocket(), seriesStored);
                }
                store.removeAssociation(assocpk);
                store.remove();
            } catch (Exception e) {
                log.error("Clean up on Association close failed:", e);
            }
        }
        if ( service.isFreeDiskSpaceOnDemand() ) {
        	service.callFreeDiskSpace();
        }
    }

	/**
	 * Finalize a stored series.
	 * <p>
	 * <dl>
	 * <dd>1) update database</dd>
	 * <dd>2) update study access time.</dd>
	 * <dd>3) Create Audit log entries for instances stored</dd>
	 * <dd>4) send SeriesStored JMX notification</dd>
	 * </dl>
	 *
	 * @param s	The Association socket or null if series is stored local (e.g. undelete)
	 * @param seriesStored
	 */
	protected void doAfterSeriesIsStored(Storage store, Socket s,
            SeriesStored seriesStored) {
        Dataset ian = seriesStored.getIAN();
        updateDBSeries(store,
                ian.getItem(Tags.RefSeriesSeq).getString(Tags.SeriesInstanceUID));
        updateDBStudy(store, ian.getString(Tags.StudyInstanceUID));
		service.logInstancesStored(s, seriesStored);
		service.sendJMXNotification(seriesStored);
	}

    private void updateDBStudy(Storage store, final String suid) {
        int retry = 0;
        for (;;) {
            try {
				if (serializeDBUpdate) {
	                synchronized (store) {
	                    store.updateStudy(suid);
	                }
				} else {
                    store.updateStudy(suid);
				}
                return;
            } catch (Exception e) {
                ++retry;
                if (retry > updateDatabaseMaxRetries) {
                    service.getLog().error(
                            "give up update DB Study Record [iuid=" + suid
                                    + "]:", e);
                    ;
                }
                maxCountUpdateDatabaseRetries = Math.max(retry,
                        maxCountUpdateDatabaseRetries);
                service.getLog().warn(
                        "failed to update DB Study Record [iuid=" + suid
                                + "] - retry:", e);
                try {
                    Thread.sleep(updateDatabaseRetryInterval);
                } catch (InterruptedException e1) {
                    log.warn("update Database Retry Interval interrupted:", e1);
                }
            }
        }
    }

    private void updateDBSeries(Storage store, final String seriuid) {
        int retry = 0;
        for (;;) {
            try {
				if (serializeDBUpdate) {
	                synchronized (store) {
	                    store.updateSeries(seriuid);
	                }
				} else {
                    store.updateSeries(seriuid);
				}
                return;
            } catch (Exception e) {
                ++retry;
                if (retry > updateDatabaseMaxRetries) {
                    service.getLog().error(
                            "give up update DB Series Record [iuid=" + seriuid
                                    + "]:", e);
                }
                maxCountUpdateDatabaseRetries = Math.max(retry,
                        maxCountUpdateDatabaseRetries);
                service.getLog().warn(
                        "failed to update DB Series Record [iuid=" + seriuid
                                + "] - retry", e);
                try {
                    Thread.sleep(updateDatabaseRetryInterval);
                } catch (InterruptedException e1) {
                    log.warn("update Database Retry Interval interrupted:", e1);
                }
            }
        }
    }

}


text:
require "uri"
require "mime/types"

using Mournmail::MessageRendering

module Mournmail
  class MessageMode < Textbringer::Mode
    MESSAGE_MODE_MAP = Keymap.new
    MESSAGE_MODE_MAP.define_key("\C-m", :message_open_link_or_part_command)
    MESSAGE_MODE_MAP.define_key("s", :message_save_part_command)
    MESSAGE_MODE_MAP.define_key("\t", :message_next_link_or_part_command)

    # See http://nihongo.jp/support/mail_guide/dev_guide.txt
    MAILTO_REGEXP = URI.regexp("mailto")
    URI_REGEXP = /(https?|ftp):\/\/[^  \t\n>)"]*[^\]  \t\n>.,:)"]+|#{MAILTO_REGEXP}/
    MIME_REGEXP = /^\[(([0-9.]+) [A-Za-z._\-]+\/[A-Za-z._\-]+.*|PGP\/MIME .*)\]$/
    URI_OR_MIME_REGEXP = /#{URI_REGEXP}|#{MIME_REGEXP}/

    define_syntax :field_name, /^[A-Za-z\-]+: /
    define_syntax :quotation, /^>.*/
    define_syntax :mime_part, MIME_REGEXP
    define_syntax :link, URI_REGEXP

    def initialize(buffer)
      super(buffer)
      buffer.keymap = MESSAGE_MODE_MAP
      @attached_file = nil
    end

    define_local_command(:message_open_link_or_part,
                         doc: "Open a link or part.") do
      part = current_part
      if part
        open_part(part)
      else
        uri = current_uri
        if uri
          open_uri(uri)
        end
      end
    end

    define_local_command(:message_save_part, doc: "Save the current part.") do
      part = current_part
      return if part.nil?
      default_path = File.expand_path(part_file_name(part),
                                      CONFIG[:mournmail_save_directory])
      path = read_file_name("Save: ", default: default_path)
      if !File.exist?(path) || yes_or_no?("File exists; overwrite?")
        File.write(path, part.decoded)
      end
    end

    define_local_command(:message_next_link_or_part,
                         doc: "Go to the next link or MIME part.") do
      if @buffer.looking_at?(URI_OR_MIME_REGEXP)
        @buffer.forward_char
      end
      if @buffer.re_search_forward(URI_OR_MIME_REGEXP, raise_error: false)
        goto_char(@buffer.match_beginning(0))
      else
        @buffer.beginning_of_buffer
      end
    end

    private

    def current_part
      @buffer.save_excursion do
        @buffer.beginning_of_line
        if @buffer.looking_at?(/\[([0-9.]+) .*\]/)
          index = match_string(1)
          indices = index.split(".").map(&:to_i)
          @buffer[:mournmail_mail].dig_part(*indices)
        else
          nil
        end
      end
    end

    def part_file_name(part)
      file_name =
        (part["content-disposition"]&.parameters&.[]("filename") rescue nil) ||
        (part["content-type"]&.parameters&.[]("name") rescue nil) ||
        part_default_file_name(part)
      decoded_file_name = Mail::Encodings.decode_encode(file_name, :decode)
      if /\A([A-Za-z0-9_\-]+)'(?:[A-Za-z0-9_\-])*'(.*)/ =~ decoded_file_name
        $2.encode("utf-8", $1)
      else
        decoded_file_name
      end
    end

    def part_default_file_name(part)
      base_name =
        begin
          part.cid.gsub(/[^A-Za-z0-9_\-]/, "_")
        rescue NoMethodError
          "mournmail"
        end
      ext = part_extension(part)
      if ext
        base_name + "." + ext
      else
        base_name
      end
    end

    def part_extension(part)
      mime_type = part["content-type"].string
      MIME::Types[mime_type]&.first&.preferred_extension
    end

    def current_uri
      @buffer.save_excursion do
        pos = @buffer.point
        @buffer.beginning_of_line
        pos2 = @buffer.re_search_forward(URI_REGEXP, raise_error: false)
        if pos2 && match_beginning(0) <= pos && pos < match_end(0)
          match_string(0)
        else
          nil
        end
      end
    end

    def open_part(part)
      if part.multipart?
        raise EditorError, "Can't open a multipart entity."
      end
      ext = part_file_name(part).slice(/\.([^.]+)\z/, 1)
      if part.main_type != "text" || part.sub_type == "html"
        if ext.nil?
          raise EditorError, "The extension of the filename is not specified"
        end
        if !CONFIG[:mournmail_allowed_attachment_extensions].include?(ext)
          raise EditorError, ".#{ext} is not allowed"
        end
      end
      if ext
        file_name = ["mournmail", "." + ext]
      else
        file_name = "mournmail"
      end
      @attached_file = Tempfile.open(file_name, binmode: true)
      s = part.decoded
      if part.content_type == "text/html"
        s = s.sub(/<meta http-equiv="content-type".*?>/i, "")
      elsif part.charset
        s = s.encode(part.charset)
      end
      @attached_file.write(s)
      @attached_file.close
      if part.main_type == "text" && part.sub_type != "html"
        find_file(@attached_file.path)
      else
        background do
          system(*CONFIG[:mournmail_file_open_comamnd], @attached_file.path,
                 out: File::NULL, err: File::NULL)
        end
      end
    end

    def open_uri(uri)
      case uri
      when /\Amailto:/
        u = URI.parse(uri)
        if u.headers.assoc("subject")
          re = /^To:\s*\nSubject:\s*\n/
        else
          re = /^To:\s*\n/
        end
        Commands.mail
        beginning_of_buffer
        re_search_forward(re)
        replace_match("")
        insert u.to_mailtext.sub(/\n\n\z/, "")
        end_of_buffer
      else
        system(*CONFIG[:mournmail_link_open_comamnd], uri,
               out: File::NULL, err: File::NULL)
      end
    end
  end
end


text:
package database

import (
	"log"
	"time"

	"github.com/twinj/uuid"
)

type Order struct {
	ID             int64          `json:"id"`
	UUID           string         `json:"uuid"`
	ProductID      int64          `json:"productid"`
	CustomerID     int64          `json:"customer"`
	PaymentID      int64          `json:"payment"`
	ShippingAdress ShippingAdress `json:"shippingadress"`
	Paid           bool           `json:"paid"`
	Fulfilled      bool           `json:"fulfilled"`
	TimePlaced     time.Time      `json:"timestamp"`
	Price          float64        `json:"price"`
	Quantity       int            `json:"quantity"`
}

type Payment struct {
	ID          int64  `json:"id"`
	UUID        string `json:"uuid"`
	PaymentType string `json:"paymenttype"`
	Allowed     bool   `json:"allowed"`
}

type ShippingAdress struct {
	Contry string `json:"contry"`
	Zip    string `json:"zip"`
	Adress string `json:"adress"`
}

func GetPayment(id string) (p Payment, err error) {

	return
}

func GetPayments() (p []Payment, err error) {
	rows, err := DB.Query(`select id, uuid,paymenttype ,allowed from payment`)
	if err != nil {
		return
	}

	for rows.Next() {
		payment := new(Payment)

		if err = rows.Scan(&payment.ID, &payment.UUID, &payment.PaymentType, &payment.Allowed); err != nil {
			return
		}
		p = append(p, *payment)
	}
	return
}

type CartItem struct {
	ProductID int64 `json:"productid"`
	Quantity  int   `json:"quantity"`
}

type Cart struct {
	Items          []CartItem     `json:"items"`
	PaymentMethod  int            `json:"paymentid"`
	ShippingAdress ShippingAdress `json:"shippingadress"`
}

func AddOrder(customerid int64, cart Cart) (orders []Order, err error) {

	// DEBUG
	log.Println(customerid)
	// loop all the elemets of the cart and write them to aorder
	for _, item := range cart.Items {
		uuid4 := uuid.NewV4()
		_, err = DB.Exec(`insert into orders(uuid , customerid, paymentid,
				shippingadress, shippingcontry, shippingzip ,quantity , productid) values(?,?,?,?,?,?)`, uuid4,
			customerid, cart.PaymentMethod, cart.ShippingAdress.Adress, cart.ShippingAdress.Contry, cart.ShippingAdress.Zip, item.Quantity, item.ProductID)
		if err != nil {
			return
		}

	}

	orders, err = GetUserOrders(customerid)
	return
}

func GetUserOrders(userid int64) (orders []Order, err error) {
	rows, err := DB.Query(`select id, uuid,productid ,customerid,paymentid,shippingadress, shippingcontry, shippingzip,price,quantity  from orders where customerid = ? and fulfilled=false`, userid)
	if err != nil {
		return
	}

	for rows.Next() {
		order := new(Order)

		if err = rows.Scan(&order.ID, &order.UUID, &order.ProductID, &order.CustomerID, &order.PaymentID, &order.ShippingAdress.Adress, &order.ShippingAdress.Contry, &order.ShippingAdress.Zip, &order.Price, &order.Quantity); err != nil {
			return
		}
		orders = append(orders, *order)
	}
	return

}


text:
.. automodule:: insights.parsers.heat_log
   :members:
   :show-inheritance:


text:
FROM docker:20

LABEL maintainer="mritd <mritd@linux.com>"

ARG TZ="Asia/Shanghai"

ENV TZ ${TZ}

ENV KUBE_VERSION v1.21.1
ENV KUBECTL_DOWNLOAD_URL https://storage.googleapis.com/kubernetes-release/release/${KUBE_VERSION}/bin/linux/amd64/kubectl

RUN apk upgrade --update \
    && apk add bash curl tzdata wget ca-certificates git \
    && wget -q ${KUBECTL_DOWNLOAD_URL} -O /usr/local/bin/kubectl \
    && chmod +x /usr/local/bin/kubectl \
    && ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime \
    && echo ${TZ} > /etc/timezone \
    && rm -rf /var/cache/apk/*

CMD ["/bin/bash"]


text:
package org.apache.jena.riot.tokens;

import org.apache.jena.atlas.junit.BaseTest ;
import org.apache.jena.graph.Node ;
import org.apache.jena.riot.system.PrefixMap ;
import org.apache.jena.riot.system.PrefixMapFactory ;
import org.apache.jena.sparql.util.NodeFactoryExtra ;
import org.junit.BeforeClass ;
import org.junit.Test ;

public class TestTokenForNode extends BaseTest
{
    static String base = "http://localhost/" ;
    static PrefixMap prefixMap = PrefixMapFactory.create() ;

    @BeforeClass static public void beforeClass()
    {
        prefixMap.add("ex", "http://example/") ;
    }

    @Test public void tokenForNode01()
    { test( "'x'", TokenType.STRING, "x", null, null, null) ; }

    @Test public void tokenForNode02()
    { test( "<x>", TokenType.IRI, "x", null, null, null) ; }

    @Test public void tokenForNode03()
    { test( "'en'@lang", TokenType.LITERAL_LANG, "en", "lang", new Token(TokenType.STRING, "en"), null) ; }

    @Test public void tokenForNode04()
    {
        Token sub = new Token(-1,-1) ;
        sub.setType(TokenType.IRI) ;
        sub.setImage("dtype") ;
        test( "'lex'^^<dtype>", TokenType.LITERAL_DT, "lex", null, new Token(TokenType.STRING, "lex"), sub) ;
    }

    @Test public void tokenForNode05()
    { test( "<http://localhost/foo>", TokenType.IRI, "foo", null, null, null) ; }

    @Test public void tokenForNode06()
    { test( "<http://example/bar>", TokenType.PREFIXED_NAME, "ex", "bar", null, null) ; }

    @Test public void tokenForNode07()
    { test( org.apache.jena.graph.NodeFactory.createBlankNode("abc"), TokenType.BNODE, "abc", null, null, null ) ; }

    @Test public void tokenForNode08()
    { test( Node.ANY, TokenType.KEYWORD, "ANY", null, null, null) ; }

    // Short forms.

    @Test public void tokenForNode20()
    { test( "123", TokenType.INTEGER, "123", null, null, null) ; }

    @Test public void tokenForNode21()
    { test( "123.0", TokenType.DECIMAL, "123.0", null, null, null) ; }

    @Test public void tokenForNode22()
    { test( "12e0", TokenType.DOUBLE, "12e0", null, null, null) ; }

    private static void test(String nodeStr, TokenType type, String image, String image2, Token subToken1, Token subToken2)
    {
        Node n = NodeFactoryExtra.parseNode(nodeStr) ;
        test(n, type, image, image2, subToken1, subToken2) ;
    }

    private static void test(Node node, TokenType type, String image, String image2, Token subToken1, Token subToken2)
    {
        Token t = Token.tokenForNode(node, base, prefixMap) ;
        assertEquals(type, t.getType()) ;
        assertEquals(image, t.getImage()) ;
        assertEquals(image2, t.getImage2()) ;
        assertEquals(subToken1, t.getSubToken1()) ;
        assertEquals(subToken2, t.getSubToken2()) ;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:textSize="20sp"
          android:textColor="@android:color/white"
          android:background="@color/normal"
          android:gravity="start"
          android:padding="5dip"/>


text:
SELECT "users".* FROM "users"
Here are some example usages of the gem, along with the generated SQL.

Each of those methods can be chained with scoping methods, so they can be used on `Post`, `my_user.posts`, `Post.where('hello')` or inside a scope. Note that for the `*_sql` variants, those should preferably be used on classes only, because otherwise, it could be confusing for a reader.

The models can be found in [examples/models.md](examples/models.md). The comments in that file explain how to get a console to try the queries. There are also example uses of the gem for scopes.

The content of this file is generated when running `rake`

-------

## Simple examples

```ruby
# Posts that have a least one comment
Post.where_assoc_exists(:comments)
```
```sql
SELECT "posts".* FROM "posts"
WHERE (EXISTS (
  SELECT 1 FROM "comments"
  WHERE "comments"."post_id" = "posts"."id"
))
```

---

```ruby
# Posts that have no comments
Post.where_assoc_not_exists(:comments)
```
```sql
SELECT "posts".* FROM "posts"
WHERE (NOT EXISTS (
  SELECT 1 FROM "comments"
  WHERE "comments"."post_id" = "posts"."id"
))
```

---

```ruby
# Posts that have a least 50 comment
Post.where_assoc_count(50, :<=, :comments)
```
```sql
SELECT "posts".* FROM "posts"
WHERE ((50) <= COALESCE((
  SELECT COUNT(*) FROM "comments"
  WHERE "comments"."post_id" = "posts"."id"
), 0))
```

---

```ruby
# Users that have made posts
User.where_assoc_exists(:posts)
```
```sql
SELECT "users".* FROM "users"
WHERE (EXISTS (
  SELECT 1 FROM "posts"
  WHERE "posts"."author_id" = "users"."id"
))
```

---

```ruby
# Users that have made posts that have comments
User.where_assoc_exists([:posts, :comments])
```
```sql
SELECT "users".* FROM "users"
WHERE (EXISTS (
  SELECT 1 FROM "posts"
  WHERE "posts"."author_id" = "users"."id" AND (EXISTS (
    SELECT 1 FROM "comments"
    WHERE "comments"."post_id" = "posts"."id"
  ))
))
```

---

```ruby
# Users with a post or a comment (without using ActiveRecord's `or` method)
# Using `my_users` to highlight that *_sql methods should always be called on the class
my_users.where("#{User.assoc_exists_sql(:posts)} OR #{User.assoc_exists_sql(:comments)}")
```
```sql
SELECT "users".* FROM "users"
WHERE (EXISTS (
  SELECT 1 FROM "posts"
  WHERE "posts"."author_id" = "users"."id"
) OR EXISTS (
  SELECT 1 FROM "comments"
  WHERE "comments"."author_id" = "users"."id"
))
```

---

```ruby
# Users with a post or a comment (using ActiveRecord's `or` method)
User.where_assoc_exists(:posts).or(User.where_assoc_exists(:comments))
```
```sql
SELECT "users".* FROM "users"
WHERE (EXISTS (
  SELECT 1 FROM "posts"
  WHERE "posts"."author_id" = "users"."id"
) OR EXISTS (
  SELECT 1 FROM "comments"
  WHERE "comments"."author_id" = "users"."id"
))
```

---

## Examples with condition / scope

```ruby
# comments of `my_post` that were made by an admin (Using a hash)
my_post.comments.where_assoc_exists(:author, is_admin: true)
```
```sql
SELECT "comments".* FROM "comments"
WHERE "comments"."post_id" = 1 AND (EXISTS (
  SELECT 1 FROM "users"
  WHERE "users"."id" = "comments"."author_id" AND "users"."is_admin" = 1
))
```

---

```ruby
# comments of `my_post` that were not made by an admin (Using scope)
my_post.comments.where_assoc_not_exists(:author, &:admins)
```
```sql
SELECT "comments".* FROM "comments"
WHERE "comments"."post_id" = 1 AND (NOT EXISTS (
  SELECT 1 FROM "users"
  WHERE "users"."id" = "comments"."author_id" AND "users"."is_admin" = 1
))
```

---

```ruby
# Posts that have at least 5 reported comments (Using array condition)
Post.where_assoc_count(5, :<=, :comments, ["is_reported = ?", true])
```
```sql
SELECT "posts".* FROM "posts"
WHERE ((5) <= COALESCE((
  SELECT COUNT(*) FROM "comments"
  WHERE "comments"."post_id" = "posts"."id" AND (is_reported = 1)
), 0))
```

---

```ruby
# Posts made by an admin (Using a string)
Post.where_assoc_exists(:author, "is_admin = 't'")
```
```sql
SELECT "posts".* FROM "posts"
WHERE (EXISTS (
  SELECT 1 FROM "users"
  WHERE "users"."id" = "posts"."author_id" AND (is_admin = 't')
))
```

---

```ruby
# comments of `my_post` that were not made by an admin (Using block and a scope)
my_post.comments.where_assoc_not_exists(:author) { admins }
```
```sql
SELECT "comments".* FROM "comments"
WHERE "comments"."post_id" = 1 AND (NOT EXISTS (
  SELECT 1 FROM "users"
  WHERE "users"."id" = "comments"."author_id" AND "users"."is_admin" = 1
))
```

---

```ruby
# Posts that have 5 to 10 reported comments (Using block with #where and range for count)
Post.where_assoc_count(5..10, :==, :comments) { where(is_reported: true) }
```
```sql
SELECT "posts".* FROM "posts"
WHERE (COALESCE((
  SELECT COUNT(*) FROM "comments"
  WHERE "comments"."post_id" = "posts"."id" AND "comments"."is_reported" = 1
), 0) BETWEEN 5 AND 10)
```

---

```ruby
# comments made in replies to my_user's post
Comment.where_assoc_exists(:post, author_id: my_user.id)
```
```sql
SELECT "comments".* FROM "comments"
WHERE (EXISTS (
  SELECT 1 FROM "posts"
  WHERE "posts"."id" = "comments"."post_id" AND "posts"."author_id" = 1
))
```

---

## Complex / powerful examples

```ruby
# posts with a comment by an admin (uses array to go through multiple associations)
Post.where_assoc_exists([:comments, :author], is_admin: true)
```
```sql
SELECT "posts".* FROM "posts"
WHERE (EXISTS (
  SELECT 1 FROM "comments"
  WHERE "comments"."post_id" = "posts"."id" AND (EXISTS (
    SELECT 1 FROM "users"
    WHERE "users"."id" = "comments"."author_id" AND "users"."is_admin" = 1
  ))
))
```

---

```ruby
# posts where the author also commented on the post (uses a conditions between tables)
Post.where_assoc_exists(:comments, "posts.author_id = comments.author_id")
```
```sql
SELECT "posts".* FROM "posts"
WHERE (EXISTS (
  SELECT 1 FROM "comments"
  WHERE "comments"."post_id" = "posts"."id" AND (posts.author_id = comments.author_id)
))
```

---

```ruby
# posts with a reported comment made by an admin (must be the same comments)
Post.where_assoc_exists(:comments, is_reported: true) {
  where_assoc_exists(:author, is_admin: true)
}
```
```sql
SELECT "posts".* FROM "posts"
WHERE (EXISTS (
  SELECT 1 FROM "comments"
  WHERE "comments"."post_id" = "posts"."id" AND "comments"."is_reported" = 1 AND (EXISTS (
    SELECT 1 FROM "users"
    WHERE "users"."id" = "comments"."author_id" AND "users"."is_admin" = 1
  ))
))
```

---

```ruby
# posts with a reported comment and a comment by an admin (can be different or same comments)
my_user.posts.where_assoc_exists(:comments, is_reported: true)
             .where_assoc_exists([:comments, :author], is_admin: true)
```
```sql
SELECT "posts".* FROM "posts"
WHERE "posts"."author_id" = 1 AND (EXISTS (
  SELECT 1 FROM "comments"
  WHERE "comments"."post_id" = "posts"."id" AND "comments"."is_reported" = 1
)) AND (EXISTS (
  SELECT 1 FROM "comments"
  WHERE "comments"."post_id" = "posts"."id" AND (EXISTS (
    SELECT 1 FROM "users"
    WHERE "users"."id" = "comments"."author_id" AND "users"."is_admin" = 1
  ))
))
```
```ruby
# Users with more posts than comments
# Using `my_users` to highlight that *_sql methods should always be called on the class
my_users.where("#{User.only_assoc_count_sql(:posts)} > #{User.only_assoc_count_sql(:comments)}")
```
```sql
SELECT "users".* FROM "users"
WHERE (COALESCE((
  SELECT COUNT(*) FROM "posts"
  WHERE "posts"."author_id" = "users"."id"
), 0) > COALESCE((
  SELECT COUNT(*) FROM "comments"
  WHERE "comments"."author_id" = "users"."id"
), 0))
```