text:
#ifndef __NAND_TYPE_H
#define __NAND_TYPE_H

#include "nand_drv_cfg.h"

//==============================================================================
//  define the data structure for physic layer module
//==============================================================================

//define the optional physical operation parameter
struct __OptionalPhyOpPar_t
{
    __u8        MultiPlaneReadCmd[2];               //the command for multi-plane read, the sequence is [0] -ADDR- [0] -ADDR- [1] - DATA
    __u8        MultiPlaneWriteCmd[2];              //the command for multi-plane program, the sequence is 80 -ADDR- DATA - [0] - [1] -ADDR- DATA - 10/15
    __u8        MultiPlaneCopyReadCmd[3];           //the command for multi-plane page copy-back read, the sequence is [0] -ADDR- [1] -ADDR- [2]
    __u8        MultiPlaneCopyWriteCmd[3];          //the command for multi-plane page copy-back program, the sequence is [0] -ADDR- [1] - [2] -ADDR- 10
    __u8        MultiPlaneStatusCmd;                //the command for multi-plane operation status read, the command may be 0x70/0x71/0x78/...
    __u8        InterBnk0StatusCmd;                 //the command for inter-leave bank0 operation status read, the command may be 0xf1/0x78/...
    __u8        InterBnk1StatusCmd;                 //the command for inter-leave bank1 operation status read, the command may be 0xf2/0x78/...
    __u8        BadBlockFlagPosition;               //the flag that marks the position of the bad block flag,0x00-1stpage/ 0x01-1st&2nd page/ 0x02-last page/ 0x03-last 2 page
    __u16       MultiPlaneBlockOffset;              //the value of the block number offset between the left-plane block and the right pane block
};

typedef struct
{
	__u32		ChannelCnt;
    __u32        ChipCnt;                            //the count of the total nand flash chips are currently connecting on the CE pin
    __u32       ChipConnectInfo;                    //chip connect information, bit == 1 means there is a chip connecting on the CE pin
	__u32		RbCnt;
	__u32		RbConnectInfo;						//the connect  information of the all rb  chips are connected
    __u32        RbConnectMode;						//the rb connect  mode
	__u32        BankCntPerChip;                     //the count of the banks in one nand chip, multiple banks can support Inter-Leave
    __u32        DieCntPerChip;                      //the count of the dies in one nand chip, block management is based on Die
    __u32        PlaneCntPerDie;                     //the count of planes in one die, multiple planes can support multi-plane operation
    __u32        SectorCntPerPage;                   //the count of sectors in one single physic page, one sector is 0.5k
    __u32       PageCntPerPhyBlk;                   //the count of physic pages in one physic block
    __u32       BlkCntPerDie;                       //the count of the physic blocks in one die, include valid block and invalid block
    __u32       OperationOpt;                       //the mask of the operation types which current nand flash can support support
    __u32        FrequencePar;                       //the parameter of the hardware access clock, based on 'MHz'
    __u32        EccMode;                            //the Ecc Mode for the nand flash chip, 0: bch-16, 1:bch-28, 2:bch_32
    __u8        NandChipId[8];                      //the nand chip id of current connecting nand chip
    __u32       ValidBlkRatio;                      //the ratio of the valid physical blocks, based on 1024
	__u32 		good_block_ratio;					//good block ratio get from hwscan
	__u32		ReadRetryType;						//the read retry type
	__u32       DDRType;
	__u32		Reserved[22];
}boot_nand_para_t;

typedef struct boot_flash_info{
	__u32 chip_cnt;
	__u32 blk_cnt_per_chip;
	__u32 blocksize;
	__u32 pagesize;
	__u32 pagewithbadflag; /*bad block flag was written at the first byte of spare area of this page*/
}boot_flash_info_t;

//define the nand flash storage system information
struct __NandStorageInfo_t
{
	__u32		ChannelCnt;
    __u32        ChipCnt;                            //the count of the total nand flash chips are currently connecting on the CE pin
    __u32       ChipConnectInfo;                    //chip connect information, bit == 1 means there is a chip connecting on the CE pin
	__u32		RbCnt;
	__u32		RbConnectInfo;						//the connect  information of the all rb  chips are connected
    __u32        RbConnectMode;						//the rb connect  mode
	__u32       BankCntPerChip;                     //the count of the banks in one nand chip, multiple banks can support Inter-Leave
    __u32        DieCntPerChip;                      //the count of the dies in one nand chip, block management is based on Die
    __u32        PlaneCntPerDie;                     //the count of planes in one die, multiple planes can support multi-plane operation
    __u32        SectorCntPerPage;                   //the count of sectors in one single physic page, one sector is 0.5k
    __u32       PageCntPerPhyBlk;                   //the count of physic pages in one physic block
    __u32       BlkCntPerDie;                       //the count of the physic blocks in one die, include valid block and invalid block
    __u32       OperationOpt;                       //the mask of the operation types which current nand flash can support support
    __u32        FrequencePar;                       //the parameter of the hardware access clock, based on 'MHz'
    __u32       EccMode;                            //the Ecc Mode for the nand flash chip, 0: bch-16, 1:bch-28, 2:bch_32
    __u32       NandChipId[8];                      //the nand chip id of current connecting nand chip
    __u32       ValidBlkRatio;                         //the ratio of the valid physical blocks, based on 1024
    __u32		ReadRetryType;						//the read retry type
    __u32       DDRType;
    struct __OptionalPhyOpPar_t OptPhyOpPar;        //the parameters for some optional operation
};

//define the page buffer pool for nand flash driver
struct __NandPageCachePool_t
{
    __u8        *PageCache0;                        //the pointer to the first page size ram buffer
    __u8        *PageCache1;                        //the pointer to the second page size ram buffer
    __u8        *PageCache2;                        //the pointer to the third page size ram buffer
    __u8		*SpareCache;

	__u8		*TmpPageCache;
};

//define the User Data structure for nand flash driver
struct __NandUserData_t
{
    __u8        BadBlkFlag;                         //the flag that marks if a physic block is a valid block or a invalid block
    __u16       LogicInfo;                          //the logical information of the physical block
    __u8        Reserved0;                          //reserved for 32bit align
    __u16       LogicPageNum;                       //the value of the logic page number, which the physic page is mapping to
    __u8        PageStatus;                         //the logical information of the physical page
    __u8        Reserved1;                          //reserved for 32bit align
} __attribute__ ((packed));

//define the paramter structure for physic operation function
struct __PhysicOpPara_t
{
    __u32        BankNum;                            //the number of the bank current accessed, bank NO. is different of chip NO.
    __u32       PageNum;                            //the number of the page current accessed, the page is based on single-plane or multi-plane
    __u32       BlkNum;                             //the number of the physic block, the block is based on single-plane or multi-plane
    __u32       SectBitmap;                         //the bitmap of the sector in the page which need access data
    void        *MDataPtr;                          //the pointer to main data buffer, it is the start address of a page size based buffer
    void        *SDataPtr;                          //the pointer to spare data buffer, it will be set to NULL if needn't access spare data
};

//==============================================================================
//  define the data structure for logic management module
//==============================================================================

//define the logical architecture parameter structure
struct __LogicArchitecture_t
{
    __u16       LogicBlkCntPerZone;                 //the counter that marks how many logic blocks in one zone
    __u16       PageCntPerLogicBlk;                 //the counter that marks how many pages in one logical block
    __u8        SectCntPerLogicPage;                //the counter that marks how many  sectors in one logical page
    __u8        ZoneCntPerDie;                      //the counter that marks how many zones in one die
    __u16       Reserved;                           //reserved for 32bit align
};

//define the super block type
struct __SuperPhyBlkType_t
{
    __u16       PhyBlkNum;                          //the super physic block offset number in a die,the first block of the die is 0
    __u16       BlkEraseCnt;                        //the erase count of the super physic block,record how many times it has been erased
};

//define the log block table item type
struct __LogBlkType_t
{
    __u16       LogicBlkNum;                        //the logic block number which the log block is belonged to
    __u16       LastUsedPage;                       //the number of the page which is the last used in the super physic block
    struct __SuperPhyBlkType_t PhyBlk;              //the super physic block number which the log block is mapping to
};

//define the zone table position information type
struct __ZoneTblPstInfo_t
{
    __u16       PhyBlkNum;                          //the physic block number in the chip which stored the block mapping table
    __u16       TablePst;                           //the page number in the physic block which stored the valid block mapping table
};

//define the block mapping table cache access type
struct __BlkMapTblCache_t
{
    __u8        ZoneNum;                            //the number of the zone which is the block mapping table belonged to
    __u8        DirtyFlag;                          //the flag that marks the status of the table in the nand, notes if the table need write back
    __u16       AccessCnt;                          //the counter that record how many times the block mapping table has been accessed
    struct __SuperPhyBlkType_t *DataBlkTbl;         //the pointer to the data block table of the block mapping table
    struct __LogBlkType_t *LogBlkTbl;               //the pointer to the log block table of the block mapping table
    struct __SuperPhyBlkType_t *FreeBlkTbl;         //the pointer to the free block table of the block mapping table
    __u16       LastFreeBlkPst;                     //the pointer to the free block position which is got last time
    __u16       Reserved;                           //reserved for 32bit align
};

//define the block mapping table cache management parameter type
struct __BlkMapTblCachePool_t
{
    struct __BlkMapTblCache_t *ActBlkMapTbl;                                //the pointer to the active block mapping table
    struct __BlkMapTblCache_t BlkMapTblCachePool[BLOCK_MAP_TBL_CACHE_CNT];  //the pool of the block mapping table cache
    __u16       LogBlkAccessAge[MAX_LOG_BLK_CNT];   //the time of accessing log block for the log block
    __u16       LogBlkAccessTimer;                  //the timer of the access time for recording the log block accessing time
    __u16       SuperBlkEraseCnt;                   //the counter of the super block erase, for do wear-levelling
};

//define the page mapping table item type
struct __PageMapTblItem_t
{
    __u16       PhyPageNum;                         //the physic page number which the logic page mapping to
};

//define the page mapping table access type
struct __PageMapTblCache_t
{
    __u8        ZoneNum;                            //the zone number which the page mapping table is belonged to
    __u8        LogBlkPst;                          //the position of the log block in the log block table
    __u16       AccessCnt;                          //the counter that the page mapping table has been accessed
	struct __PageMapTblItem_t *PageMapTbl;          //the pointer to the page mapping table
    __u8        DirtyFlag;                          //the flag that marks if the page mapping table need be writen back to nand flash
    __u8        Reserved[3];                        //reserved for 32bit align
};

//define the page mapping table cache management parameter type
struct __PageMapTblCachePool_t
{
    struct __PageMapTblCache_t *ActPageMapTbl;                              //the poninter to the active page mapping table
    struct __PageMapTblCache_t PageMapTblCachePool[PAGE_MAP_TBL_CACHE_CNT]; //the pool of the page mapping table cache
};

//define the global logical page parameter type
struct __GlobalLogicPageType_t
{
    __u32       LogicPageNum;                       //the global page number of the logic page, it is based on super page size
    __u32       SectorBitmap;                       //the bitmap of the sector in the logic page which data need access
};

//define the global logcial page based on zone and block parameter type
struct __LogicPageType_t
{
    __u32       SectBitmap;                         //the bitmap marks which sectors' data in the logical page need access
    __u16       BlockNum;                           //the value of the number of the logical block which the page is belonged to
    __u16       PageNum;                            //the value of the number of the page in the logical block
    __u8        ZoneNum;                            //the value of the number of the zone, which the page is belonged to
    __u8        Reserved[3];                        //reserved for 32bit align
};

//define the logical control layer management parameter type
struct __LogicCtlPar_t
{
    __u8        OpMode;                             //record nand flash driver last operation, may be read, write, or none.
    __u8        ZoneNum;                            //the number of the zone which is accessed last time
    __u16       LogicBlkNum;                        //the number of the logic block which is accessed last time
    __u16       LogicPageNum;                       //the number of the logic page which is accessed last time
    __u16       LogPageNum;                         //the number of the log page, which is accessed last time
    struct __SuperPhyBlkType_t  DataBlkNum;         //the number of the data block, which is accessed last time
    struct __SuperPhyBlkType_t  LogBlkNum;          //the number of the log block, which is accessed last time
    __u32       DiskCap;                            //the capacity of the logical disk
};

//define the nand flash physical information parameter type
struct __NandPhyInfoPar_t
{
    __u8        NandID[8];                          //the ID number of the nand flash chip
    __u8        DieCntPerChip;                      //the count of the Die in one nand flash chip
    __u8        SectCntPerPage;                     //the count of the sectors in one single physical page
    __u16       PageCntPerBlk;                      //the count of the pages in one single physical block
    __u16       BlkCntPerDie;                       //the count fo the physical blocks in one nand flash Die
    __u16       OperationOpt;                       //the bitmap that marks which optional operation that the nand flash can support
    __u16       ValidBlkRatio;                      //the valid block ratio, based on 1024 blocks
    __u16       AccessFreq;                         //the highest access frequence of the nand flash chip, based on MHz
    __u16       EccMode;                            //the Ecc Mode for the nand flash chip, 0: bch-16, 1:bch-28, 2:bch_32
    __u32 		ReadRetryType;
    __u32       DDRType;
    struct __OptionalPhyOpPar_t *OptionOp;          //the pointer point to the optional operation parameter
};

//define the global paramter for nand flash driver to access all parameter
struct __NandDriverGlobal_t
{
    struct __NandStorageInfo_t  *NandStorageInfo;               //the pointer to the nand flash hardware information parameter
    struct __ZoneTblPstInfo_t   *ZoneTblPstInfo;                //the pointer to the block mapping table information parameter
    struct __BlkMapTblCachePool_t   *BlkMapTblCachePool;        //the pointer to the block mapping thable cache pool management parameter
    struct __PageMapTblCachePool_t  *PageMapTblCachePool;       //the pointer to the page mapping table cache pool management parameter
    struct __LogicArchitecture_t    *LogicalArchitecture;       //the pointer to the logical archtecture parameter
    struct __NandPageCachePool_t    *PageCachePool;             //the pointer to the page cache pool parameter
};

//==============================================================================
//  define some constant variable for the nand flash driver used
//==============================================================================

//define the mask for the nand flash optional operation
#define NAND_CACHE_READ         (1<<0)              //nand flash support cache read operation
#define NAND_CACHE_PROGRAM      (1<<1)              //nand flash support page cache program operation
#define NAND_MULTI_READ         (1<<2)              //nand flash support multi-plane page read operation
#define NAND_MULTI_PROGRAM      (1<<3)              //nand flash support multi-plane page program operation
#define NAND_PAGE_COPYBACK      (1<<4)              //nand flash support page copy-back command mode operation
#define NAND_INT_INTERLEAVE     (1<<5)              //nand flash support internal inter-leave operation, it based multi-bank
#define NAND_EXT_INTERLEAVE     (1<<6)              //nand flash support external inter-leave operation, it based multi-chip
#define NAND_RANDOM		        (1<<7)			    //nand flash support RANDOMIZER
#define NAND_READ_RETRY	        (1<<8)			    //nand falsh support READ RETRY
#define NAND_READ_UNIQUE_ID	    (1<<9)			    //nand falsh support READ UNIQUE_ID
#define NAND_PAGE_ADR_NO_SKIP	(1<<10)			    //nand falsh page adr no skip is requiered
#define NAND_DIE_SKIP           (1<<11)             //nand flash die adr skip
#define NAND_LSB_PAGE_TYPE		 (0xff<<12)			//nand flash lsb page type....

//define the mask for the nand flash operation status
#define NAND_OPERATE_FAIL       (1<<0)              //nand flash program/erase failed mask
#define NAND_CACHE_READY        (1<<5)              //nand flash cache program true ready mask
#define NAND_STATUS_READY       (1<<6)              //nand flash ready/busy status mask
#define NAND_WRITE_PROTECT      (1<<7)              //nand flash write protected mask

//define the mark for physical page status
#define FREE_PAGE_MARK          0xff                //the page is storing no data, is not used
#define DATA_PAGE_MARK          0x55                //the physical page is used for storing the update data
#define TABLE_PAGE_MARK         0xaa                //the physical page is used for storing page mapping table

#define TABLE_BLK_MARK          0xaa                //the mark for the block mapping table block which is a special type block
#define BOOT_BLK_MARK           0xbb                //the mark for the boot block which is a special type block

//define the count of the physical blocks managed by one zone
#define BLOCK_CNT_OF_ZONE       1024                //one zone is organized based on 1024 blocks

//define the size of the sector
#define SECTOR_SIZE             512                 //the size of a sector, based on byte

//==============================================================================
//  define the function return value for different modules
//==============================================================================

#define NAND_OP_TRUE            (0)                     //define the successful return value
#define NAND_OP_FALSE           (-1)                    //define the failed return value

//define the return value
#define ECC_LIMIT               10                  //reach the limit of the ability of ECC
#define ERR_MALLOC              11                  //request buffer failed
#define ERR_ECC                 12                  //too much ecc error
#define ERR_NANDFAIL            13                  //nand flash program or erase fail
#define ERR_TIMEOUT             14                  //hardware timeout
#define ERR_PHYSIC              15                  //physical operation module error
#define ERR_SCAN                16                  //scan module error
#define ERR_FORMAT              17                  //format module error
#define ERR_MAPPING             18                  //mapping module error
#define ERR_LOGICCTL            19                  //logic control module error
#define ERR_ADDRBEYOND          20                  //the logical sectors need be accessed is beyond the logical disk
#define ERR_INVALIDPHYADDR		  21

#endif //ifndef __NAND_TYPE_H


text:
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Core2D.Model;
using Core2D.Model.Editor;
using Core2D.Model.Input;
using Core2D.ViewModels.Editor.Tools.Selection;
using Core2D.ViewModels.Path.Segments;
using Core2D.ViewModels.Shapes;
using static System.Math;

namespace Core2D.ViewModels.Editor.Tools.Path;

public partial class ArcPathToolViewModel : ViewModelBase, IPathTool
{
    public enum State { Start, End }
    private State _currentState;
    private readonly LineShapeViewModel _arc;
    private LineSelection? _selection;

    public string Title => "Arc";

    public ArcPathToolViewModel(IServiceProvider? serviceProvider) : base(serviceProvider)
    {
        _currentState = State.Start;
        _arc = new LineShapeViewModel(serviceProvider);
    }

    public override object Copy(IDictionary<object, object>? shared)
    {
        throw new NotImplementedException();
    }

    private void NextPoint(InputArgs args)
    {
        var factory = ServiceProvider.GetService<IViewModelFactory>();
        var editor = ServiceProvider.GetService<ProjectEditorViewModel>();
        var selection = ServiceProvider.GetService<ISelectionService>();
        var pathTool = ServiceProvider.GetService<PathToolViewModel>();
        if (factory is null || editor?.Project?.Options is null || selection is null || pathTool is null)
        {
            return;
        }

        var (sx, sy) = selection.TryToSnap(args);
        switch (_currentState)
        {
            case State.Start:
            {
                editor.IsToolIdle = false;
                _arc.Start = selection.TryToGetConnectionPoint((double) sx, (double) sy) ??
                             factory.CreatePointShape((double) sx, (double) sy);
                if (!pathTool.IsInitialized)
                {
                    pathTool.InitializeWorkingPath(_arc.Start);
                }
                else
                {
                    _arc.Start = pathTool.GetLastPathPoint();
                }

                _arc.End = factory.CreatePointShape((double) sx, (double) sy);
                if (_arc.Start is { } && _arc.End is { })
                {
                    pathTool.GeometryContext?.ArcTo(
                        _arc.End,
                        factory.CreatePathSize(
                            Abs(_arc.Start.X - _arc.End.X),
                            Abs(_arc.Start.Y - _arc.End.Y)));
                }

                editor.Project.CurrentContainer?.WorkingLayer?.RaiseInvalidateLayer();
                ToStateEnd();
                Move(null);
                _currentState = State.End;
                break;
            }
            case State.End:
            {
                if (_arc.End is { })
                {
                    _arc.End.X = (double)sx;
                    _arc.End.Y = (double)sy;
                }
                if (editor.Project.Options.TryToConnect)
                {
                    var end = selection.TryToGetConnectionPoint((double) sx, (double) sy);
                    if (end is { })
                    {
                        _arc.End = end;
                    }
                }

                _arc.Start = _arc.End;
                _arc.End = factory.CreatePointShape((double) sx, (double) sy);
                if (_arc.Start is { } && _arc.End is { })
                {
                    pathTool.GeometryContext?.ArcTo(
                        _arc.End,
                        factory.CreatePathSize(
                            Abs(_arc.Start.X - _arc.End.X),
                            Abs(_arc.Start.Y - _arc.End.Y)));
                }
                editor.Project.CurrentContainer?.WorkingLayer?.RaiseInvalidateLayer();
                Move(null);
                _currentState = State.End;
                break;
            }
        }
    }

    public void BeginDown(InputArgs args)
    {
        NextPoint(args);
    }

    public void BeginUp(InputArgs args)
    {
        var editor = ServiceProvider.GetService<ProjectEditorViewModel>();
        if (editor?.Project is null)
        {
            return;
        }

        if (editor.Project.Options?.SinglePressMode ?? true)
        {
            if (_currentState != State.Start)
            {
                NextPoint(args);
            }
        }
    }

    public void EndDown(InputArgs args)
    {
        switch (_currentState)
        {
            case State.Start:
            {
                break;
            }
            case State.End:
            {
                Reset();
                Finalize(null);
                break;
            }
        }
    }

    public void EndUp(InputArgs args)
    {
    }

    public void Move(InputArgs args)
    {
        var editor = ServiceProvider.GetService<ProjectEditorViewModel>();
        var selection = ServiceProvider.GetService<ISelectionService>();
        var pathTool = ServiceProvider.GetService<PathToolViewModel>();
        if (editor?.Project?.Options is null || selection is null)
        {
            return;
        }
        var (sx, sy) = selection.TryToSnap(args);
        switch (_currentState)
        {
            case State.Start:
            {
                if (editor.Project.Options.TryToConnect)
                {
                    selection.TryToHoverShape((double)sx, (double)sy);
                }
                break;
            }
            case State.End:
            {
                if (editor.Project.Options.TryToConnect)
                {
                    selection.TryToHoverShape((double)sx, (double)sy);
                }
                if (_arc.End is { })
                {
                    _arc.End.X = (double)sx;
                    _arc.End.Y = (double)sy;
                }
                var figure = pathTool?.Path?.Figures.LastOrDefault();
                if (figure is { })
                {
                    var arc = figure.Segments.LastOrDefault() as ArcSegmentViewModel;
                    if (arc is { } && arc.Size is { } && _arc.Start is { } && _arc.End is { })
                    {
                        arc.Point = _arc.End;
                        arc.Size.Width = Abs(_arc.Start.X - _arc.End.X);
                        arc.Size.Height = Abs(_arc.Start.Y - _arc.End.Y);
                        editor.Project.CurrentContainer?.WorkingLayer?.RaiseInvalidateLayer();
                    }
                }
                Move(null);
                break;
            }
        }
    }

    public void ToStateEnd()
    {
        _selection?.Reset();

        var editor = ServiceProvider.GetService<ProjectEditorViewModel>();
        if (editor is { }
            && editor.Project?.CurrentContainer?.HelperLayer is { }
            && editor.PageState?.HelperStyle is { })
        {
            _selection = new LineSelection(
                ServiceProvider,
                editor.Project.CurrentContainer.HelperLayer,
                _arc,
                editor.PageState.HelperStyle);

            _selection.ToStateEnd();
        }
    }

    public void Move(BaseShapeViewModel? shape)
    {
        _selection?.Move();
    }

    public void Finalize(BaseShapeViewModel? shape)
    {
    }

    public void Reset()
    {
        var editor = ServiceProvider.GetService<ProjectEditorViewModel>();
        var pathTool = ServiceProvider.GetService<PathToolViewModel>();
        if (editor is null)
        {
            return;
        }

        switch (_currentState)
        {
            case State.Start:
                break;
            case State.End:
            {
                pathTool?.RemoveLastSegment<ArcSegmentViewModel>();
                break;
            }
        }

        _currentState = State.Start;

        if (_selection is { })
        {
            _selection.Reset();
            _selection = null;
        }

        editor.IsToolIdle = true;
    }
}

redpajama_set_name: RedPajamaGithub


text:
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO

Partial Class members_photogallery
    Inherits System.Web.UI.Page

    Dim cf As New comonfunctions
    Private Sub PopulatePublishersGridView(ByVal pass As String)
        Dim connectionString As String = cf.justviewcon
        Dim accessConnection As SqlConnection = New SqlConnection(connectionString)
        Dim sqlQuery As String = ""
        sqlQuery = makequery()
        Dim accessCommand As New SqlCommand(sqlQuery, accessConnection)
        Dim publishersDataAdapter As New SqlDataAdapter(accessCommand)
        Dim publishersDataTable As New DataTable("profile")
        publishersDataAdapter.Fill(publishersDataTable)
        Dim dataTableRowCount As Integer = publishersDataTable.Rows.Count
        If dataTableRowCount > 0 Then
            'gridViewPublishers.DataSource = publishersDataTable
            'gridViewPublishers.DataBind()
            If publishersDataTable.Rows(0)("passw") <> "" Then
                If pass <> "" Then
                    If publishersDataTable.Rows(0)("passw") = pass Then
                        GoTo bindList
                    Else
                        lblPError.ForeColor = System.Drawing.Color.Red
                        lblPError.Text = "Wrong Password"
                    End If
                End If
            Else
bindList:
                ListView1.DataSource = publishersDataTable
                ListView1.DataBind()
                photopassw.Visible = False
                Button1.Visible = False
                lblP.Visible = False
                lblPError.Text = ""
            End If

        End If
    End Sub
    Function makequery() As String
        If Request.QueryString("pid") <> "" And Request.QueryString("pid") IsNot Nothing Then
            makequery = "photogallery " & Request.QueryString("pid") & "" ' select photoname,photoid,candiid from photos where candiid=" & Request.QueryString("id") & " order by uploaddate desc"
        Else
            makequery = "photogallery " & 0 & "" ' " select photoname,photoid,candiid from photos where candiid=" & Request.Cookies("candiid").Value & " order by uploaddate desc"
        End If
    End Function
    Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
        Try
            If Not Page.IsPostBack Then
                PopulatePublishersGridView("")
                If Request.QueryString("Pic") <> "" Then

                    'TextBox1.Text = Request.QueryString("picid")
                    '  "c.candiid=" & Request.QueryString("id") & " and c.photoid=" &
                    If IsNumeric(Request.QueryString("Pic")) Then
                        showphoto(Request.QueryString("Pic"))
                    End If
                End If
            End If
        Catch ex As Exception
            Response.Write(ex.Message)
        End Try
    End Sub

    Sub showphoto(ByVal phid As String)
        Dim cn As New SqlConnection
        Dim cmd As New SqlCommand
        Dim myreader As SqlDataReader
        Dim sql As String = ""
        Dim a As String = ""
        sql = "select photoname,photoid,pid from photo where photoid=" & phid
        cn.ConnectionString = cf.justviewcon
        cn.Open()

        cmd.Connection = cn
        cmd.CommandTimeout = 5000
        cmd.CommandText = sql
        myreader = cmd.ExecuteReader

        Try

            Dim pid As String = Request.QueryString("pid")
            Dim ImgName As String = ""
            If myreader.HasRows Then
                While myreader.Read
                    a = myreader.GetValue(1).ToString
                    ImgName = myreader.GetValue(0).ToString
                End While
            End If
            cn.Close()
            Dim PhotoUrl As String = ""
            If File.Exists(Server.MapPath("../App_Themes/" & ImgName)) Then
                pic.ImageUrl = "../App_Themes/" & ImgName
                pic.Visible = True
                div_Lnk.InnerHtml = "<link rel='image_src' href='http://www.yoursite.com/App_Themes/" & ImgName & "' />"

                Try
                    PhotoUrl = "&Pic=" & a
                Catch ex As Exception
                End Try
            End If
            Dim gg As String = ""
            'googlecomments.InnerHtml = "<g:comments   href = 'http://www.yoursite.com'  width = '642' first_party_property = 'BLOGGER'    view_type='FILTERED_POSTMOD'></g:comments>"
            gg = ""
            gg += "                    <g:comments"
            gg += "                        href='http://www.yoursite.com/photogallery.aspx?pid=" & pid & PhotoUrl & "'"
            gg += "                        width='642'"
            gg += "                        first_party_property='BLOGGER'"
            gg += "                        view_type='FILTERED_POSTMOD'>"
            gg += "                    </g:comments>"

            googlecomments.InnerHtml = gg
            Dim fbco As String = ""
            'googlecomments.InnerHtml = "<g:comments   href = 'http://www.yoursite.com'  width = '642' first_party_property = 'BLOGGER'    view_type='FILTERED_POSTMOD'></g:comments>"
            fbco = facebookcomment.InnerHtml
            fbco = Replace(fbco, "abcd", "http://www.yoursite.com/photogallery.aspx?pid=" & pid & PhotoUrl)
            fbco = "

"
            facebookcomment.InnerHtml = fbco
            'GridView1.DataSourceID = ObjectDataSource1.ID
            viewcomment.Visible = True

        Catch ex As Exception
            'Response.Write(ex.ToString)

            cn.Close()
        End Try
    End Sub

    Sub deleterec(ByVal reqid As String)
        Dim cmd As New SqlCommand
        cmd.CommandText = "Deletephotocomment"
        cmd.Parameters.AddWithValue("@id", reqid)
        cf.ExecuteNonQuery(cmd, cf.justviewcon)
    End Sub
    Protected Sub ListView1_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles ListView1.ItemCommand
        If e.CommandName = "ShowImg" Then
            'TextBox1.Text = e.CommandArgument
            '  "c.candiid=" & Request.QueryString("id") & " and c.photoid=" &
            showphoto(e.CommandArgument)
        End If
    End Sub
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        PopulatePublishersGridView(photopassw.Text)
    End Sub
#Region "Old Gallery"

    'Dim cf As New comonfunctions
    'Dim pid As Integer = 0
    'Private Sub PopulatePublishersGridView()
    '    Dim ds1 As New DataSet
    '    ' If Session("chcPopulatePublishersGridView" & Request.QueryString("pid")) Is Nothing Then
    '    Dim cmd As New SqlCommand
    '    cmd.CommandText = "photogallery"
    '    cmd.Parameters.AddWithValue("@pid", Request.QueryString("pid"))
    '    cmd.CommandType = CommandType.StoredProcedure
    '    ds1 = cf.ExecuteDataset(cmd)
    '    '   Session("chcPopulatePublishersGridView" & Request.QueryString("pid")) = ds1
    '    'End If
    '    'ds1 = Session("chcPopulatePublishersGridView" & Request.QueryString("pid"))
    '    If ds1.Tables(0).Rows.Count > 0 Then
    '        gridViewPublishers.DataSource = ds1.Tables(0)
    '        gridViewPublishers.DataBind()
    '    End If
    'End Sub
    'Private Property GridViewSortDirection() As String
    '    Get
    '        Return IIf(ViewState("SortDirection") = Nothing, "ASC", ViewState("SortDirection"))
    '    End Get
    '    Set(ByVal value As String)
    '        ViewState("SortDirection") = value
    '    End Set
    'End Property

    'Private Property GridViewSortExpression() As String
    '    Get
    '        Return IIf(ViewState("SortExpression") = Nothing, String.Empty, ViewState("SortExpression"))
    '    End Get
    '    Set(ByVal value As String)
    '        ViewState("SortExpression") = value
    '    End Set
    'End Property

    'Private Function GetSortDirection() As String
    '    Select Case GridViewSortDirection
    '        Case "ASC"
    '            GridViewSortDirection = "DESC"
    '        Case "DESC"
    '            GridViewSortDirection = "ASC"
    '    End Select
    '    Return GridViewSortDirection
    'End Function

    'Protected Sub gridViewPublishers_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
    '    'gridViewPublishers.DataSource = SortDataTable(CType(gridViewPublishers.DataSource, DataTable), True)
    '    gridViewPublishers.PageIndex = e.NewPageIndex
    '    PopulatePublishersGridView()
    '    'gridViewPublishers.DataBind()
    'End Sub

    'Protected Function SortDataTable(ByVal pdataTable As DataTable, ByVal isPageIndexChanging As Boolean) As DataView
    '    If Not pdataTable Is Nothing Then
    '        Dim pdataView As New DataView(pdataTable)
    '        If GridViewSortExpression <> String.Empty Then
    '            If isPageIndexChanging Then
    '                pdataView.Sort = String.Format("{0} {1}", GridViewSortExpression, GridViewSortDirection)
    '            Else
    '                pdataView.Sort = String.Format("{0} {1}", GridViewSortExpression, GetSortDirection())
    '            End If
    '        End If
    '        Return pdataView
    '    Else
    '        Return New DataView()
    '    End If
    'End Function

    'Protected Sub gridViewPublishers_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
    '    GridViewSortExpression = e.SortExpression
    '    Dim pageIndex As Integer = gridViewPublishers.PageIndex
    '    gridViewPublishers.DataSource = SortDataTable(CType(gridViewPublishers.DataSource, DataTable), False)
    '    gridViewPublishers.DataBind()
    '    gridViewPublishers.PageIndex = pageIndex
    'End Sub

    'Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
    '    Try

    '        Try
    '            pid = Request.QueryString("pid")
    '        Catch ex As Exception

    '        End Try
    '        If Not Page.IsPostBack Then
    '            PopulatePublishersGridView()
    '            displaydelbtn()
    '            If Not IsNothing(Request.QueryString("flag")) Then
    '                If Request.QueryString("flag") = "Delete" Then
    '                    deletephoto()
    '                End If
    '            End If
    '        End If
    '    Catch ex As Exception
    '        Response.Write(ex.Message)
    '    End Try
    'End Sub

    'Protected Sub displaydelbtn()
    '    Dim i As Integer
    '    If Session("mrole") IsNot Nothing Then
    '        If Session("mrole") = "mod" Then
    '            For i = 0 To gridViewPublishers.Rows.Count - 1
    '                gridViewPublishers.Rows(i).Cells(0).Text = "Delete"
    '            Next
    '        Else
    '            gridViewPublishers.Columns(0).Visible = False
    '        End If
    '    End If
    'End Sub

    'Protected Sub deletephoto()
    '    Dim strcon1 As String = cf.friendshipdb()
    '    Dim cmd As New SqlCommand
    '    Dim dc As Integer
    '    Dim strcon As SqlConnection = New SqlConnection(strcon1)
    '    strcon.Open()
    '    cmd.Connection = strcon
    '    cmd.CommandTimeout = 5000
    '    cmd.CommandText = "delete from photo where photoid=" & Request.QueryString("photoid") & ""
    '    dc = cmd.ExecuteNonQuery()
    '    Dim ds As New DataSet
    '    Session("chcPopulatePublishersGridView" & Request.QueryString("pid")) = Nothing

    '    If dc <> 0 Then
    '        Response.Redirect("photogallery.aspx?pid=" & Request.QueryString("pid") & " ")
    '    Else
    '        Response.Redirect("photogallery.aspx?pid=" & Request.QueryString("pid") & " ")
    '    End If
    '    cmd.Dispose()
    '    strcon.Close()
    'End Sub

    'Protected Sub gridViewPublishers_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridViewPublishers.RowDataBound
    '    If e.Row.RowType = DataControlRowType.DataRow Then
    '        Dim PhotoUrl As String = ""
    '        Try
    '            PhotoUrl = "&Pic=" & TryCast(DataBinder.Eval(e.Row.DataItem, "Photoname"), String)
    '        Catch ex As Exception

    '        End Try
    '        Dim gg As String = ""
    '        'googlecomments.InnerHtml = "<g:comments   href = 'http://www.yoursite.com'  width = '642' first_party_property = 'BLOGGER'    view_type='FILTERED_POSTMOD'></g:comments>"
    '        gg = googlecomments.InnerHtml
    '        gg = Replace(gg, "http://www.yoursite.com", "http://www.yoursite.com/photogallery.aspx?pid=" & pid & PhotoUrl)
    '        googlecomments.InnerHtml = gg

    '        Dim fbco As String = ""
    '        'googlecomments.InnerHtml = "<g:comments   href = 'http://www.yoursite.com'  width = '642' first_party_property = 'BLOGGER'    view_type='FILTERED_POSTMOD'></g:comments>"
    '        fbco = facebookcomment.InnerHtml
    '        fbco = Replace(fbco, "abcd", "http://www.yoursite.com/photogallery.aspx?pid=" & pid & PhotoUrl)
    '        facebookcomment.InnerHtml = fbco
    '    End If

    'End Sub
#End Region

End Class


text:
package com.apptentive.android.sdk.tests.push;

import android.app.PendingIntent;
import android.os.Bundle;
import androidx.test.rule.UiThreadTestRule;
import androidx.test.runner.AndroidJUnit4;

import com.apptentive.android.sdk.Apptentive;
import com.apptentive.android.sdk.ApptentiveInternal;
import com.apptentive.android.sdk.tests.ApptentiveTestCaseBase;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

@RunWith(AndroidJUnit4.class)
public class ApptentivePayload extends ApptentiveTestCaseBase {

	private static final String good = "{\"action\":\"pmc\"}";
	private static final String unknownAction = "{\"action\":\"foo\"}";
	private static final String wrongKey = "{\"foo\":\"pmc\"}";
	private static final String corrupt = "{\"foo:pmc";

	@Rule
	public UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();

	@Before
	public void setUp() {
		super.setUp();
		ApptentiveInternal.setInstance(new ApptentiveInternal(targetContext));
	}

	@Test
	public void missingApptentive() {
		Bundle bundle = new Bundle();
		Apptentive.buildPendingIntentFromPushNotification(new Apptentive.PendingIntentCallback() {
			@Override
			public void onPendingIntent(PendingIntent pendingIntent) {
				assertNull(pendingIntent);
			}
		}, bundle);
		assertFalse(Apptentive.isApptentivePushNotification(bundle));
	}

/* TODO: Decouple tested code from Conversation and MessageManager
	@Test
	public void good() throws Throwable {
		final Bundle bundle = new Bundle();
		bundle.putString("apptentive", good);
		uiThreadTestRule.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				assertNotNull(Apptentive.buildPendingIntentFromPushNotification(bundle));
			}
		});
		assertTrue(Apptentive.isApptentivePushNotification(bundle));
	}
*/

	// These three are tricky, because they are not valid actions, but it's still an Apptentive push.
	@Test
	public void unknownAction() {
		Bundle bundle = new Bundle();
		bundle.putString("apptentive", unknownAction);
		Apptentive.buildPendingIntentFromPushNotification(new Apptentive.PendingIntentCallback() {
			@Override
			public void onPendingIntent(PendingIntent pendingIntent) {
				assertNull(pendingIntent);
			}
		}, bundle);
		assertTrue(Apptentive.isApptentivePushNotification(bundle));
	}

	@Test
	public void wrongActionKey() {
		Bundle bundle = new Bundle();
		bundle.putString("apptentive", wrongKey);
		Apptentive.buildPendingIntentFromPushNotification(new Apptentive.PendingIntentCallback() {
			@Override
			public void onPendingIntent(PendingIntent pendingIntent) {
				assertNull(pendingIntent);
			}
		}, bundle);
		assertTrue(Apptentive.isApptentivePushNotification(bundle));
	}

	@Test
	public void corrupt() {
		Bundle bundle = new Bundle();
		bundle.putString("apptentive", corrupt);
		Apptentive.buildPendingIntentFromPushNotification(new Apptentive.PendingIntentCallback() {
			@Override
			public void onPendingIntent(PendingIntent pendingIntent) {
				assertNull(pendingIntent);
			}
		}, bundle);
		assertTrue(Apptentive.isApptentivePushNotification(bundle));
	}
}


text:
package storageversiongc

import (
	"context"
	"fmt"
	"time"

	apiserverinternalv1alpha1 "k8s.io/api/apiserverinternal/v1alpha1"
	coordinationv1 "k8s.io/api/coordination/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	utilerrors "k8s.io/apimachinery/pkg/util/errors"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/apimachinery/pkg/util/wait"
	apiserverinternalinformers "k8s.io/client-go/informers/apiserverinternal/v1alpha1"
	coordinformers "k8s.io/client-go/informers/coordination/v1"
	"k8s.io/client-go/kubernetes"
	coordlisters "k8s.io/client-go/listers/coordination/v1"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/util/workqueue"
	"k8s.io/kubernetes/pkg/controlplane"

	"k8s.io/klog/v2"
)

// Controller watches kube-apiserver leases and storageversions, and delete stale
// storage version entries and objects.
type Controller struct {
	kubeclientset kubernetes.Interface

	leaseLister  coordlisters.LeaseLister
	leasesSynced cache.InformerSynced

	storageVersionSynced cache.InformerSynced

	leaseQueue          workqueue.RateLimitingInterface
	storageVersionQueue workqueue.RateLimitingInterface
}

// NewStorageVersionGC creates a new Controller.
func NewStorageVersionGC(clientset kubernetes.Interface, leaseInformer coordinformers.LeaseInformer, storageVersionInformer apiserverinternalinformers.StorageVersionInformer) *Controller {
	c := &Controller{
		kubeclientset:        clientset,
		leaseLister:          leaseInformer.Lister(),
		leasesSynced:         leaseInformer.Informer().HasSynced,
		storageVersionSynced: storageVersionInformer.Informer().HasSynced,
		leaseQueue:           workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "storage_version_garbage_collector_leases"),
		storageVersionQueue:  workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "storage_version_garbage_collector_storageversions"),
	}

	leaseInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		DeleteFunc: c.onDeleteLease,
	})
	// use the default resync period from the informer
	storageVersionInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc:    c.onAddStorageVersion,
		UpdateFunc: c.onUpdateStorageVersion,
	})

	return c
}

// Run starts one worker.
func (c *Controller) Run(stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()
	defer c.leaseQueue.ShutDown()
	defer c.storageVersionQueue.ShutDown()
	defer klog.Infof("Shutting down storage version garbage collector")

	klog.Infof("Starting storage version garbage collector")

	if !cache.WaitForCacheSync(stopCh, c.leasesSynced, c.storageVersionSynced) {
		utilruntime.HandleError(fmt.Errorf("timed out waiting for caches to sync"))
		return
	}

	// Identity lease deletion and storageversion update don't happen too often. Start one
	// worker for each of them.
	// runLeaseWorker handles legit identity lease deletion, while runStorageVersionWorker
	// handles storageversion creation/update with non-existing id. The latter should rarely
	// happen. It's okay for the two workers to conflict on update.
	go wait.Until(c.runLeaseWorker, time.Second, stopCh)
	go wait.Until(c.runStorageVersionWorker, time.Second, stopCh)

	<-stopCh
}

func (c *Controller) runLeaseWorker() {
	for c.processNextLease() {
	}
}

func (c *Controller) processNextLease() bool {
	key, quit := c.leaseQueue.Get()
	if quit {
		return false
	}
	defer c.leaseQueue.Done(key)

	err := c.processDeletedLease(key.(string))
	if err == nil {
		c.leaseQueue.Forget(key)
		return true
	}

	utilruntime.HandleError(fmt.Errorf("lease %v failed with: %v", key, err))
	c.leaseQueue.AddRateLimited(key)
	return true
}

func (c *Controller) runStorageVersionWorker() {
	for c.processNextStorageVersion() {
	}
}

func (c *Controller) processNextStorageVersion() bool {
	key, quit := c.storageVersionQueue.Get()
	if quit {
		return false
	}
	defer c.storageVersionQueue.Done(key)

	err := c.syncStorageVersion(key.(string))
	if err == nil {
		c.storageVersionQueue.Forget(key)
		return true
	}

	utilruntime.HandleError(fmt.Errorf("storage version %v failed with: %v", key, err))
	c.storageVersionQueue.AddRateLimited(key)
	return true
}

func (c *Controller) processDeletedLease(name string) error {
	_, err := c.kubeclientset.CoordinationV1().Leases(metav1.NamespaceSystem).Get(context.TODO(), name, metav1.GetOptions{})
	// the lease isn't deleted, nothing we need to do here
	if err == nil {
		return nil
	}
	if !apierrors.IsNotFound(err) {
		return err
	}
	// the frequency of this call won't be too high because we only trigger on identity lease deletions
	storageVersionList, err := c.kubeclientset.InternalV1alpha1().StorageVersions().List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		return err
	}

	var errors []error
	for _, sv := range storageVersionList.Items {
		var serverStorageVersions []apiserverinternalv1alpha1.ServerStorageVersion
		hasStaleRecord := false
		for _, ssv := range sv.Status.StorageVersions {
			if ssv.APIServerID == name {
				hasStaleRecord = true
				continue
			}
			serverStorageVersions = append(serverStorageVersions, ssv)
		}
		if !hasStaleRecord {
			continue
		}
		if err := c.updateOrDeleteStorageVersion(&sv, serverStorageVersions); err != nil {
			errors = append(errors, err)
		}
	}

	return utilerrors.NewAggregate(errors)
}

func (c *Controller) syncStorageVersion(name string) error {
	sv, err := c.kubeclientset.InternalV1alpha1().StorageVersions().Get(context.TODO(), name, metav1.GetOptions{})
	if apierrors.IsNotFound(err) {
		// The problematic storage version that was added/updated recently is gone.
		// Nothing we need to do here.
		return nil
	}
	if err != nil {
		return err
	}

	hasInvalidID := false
	var serverStorageVersions []apiserverinternalv1alpha1.ServerStorageVersion
	for _, v := range sv.Status.StorageVersions {
		lease, err := c.kubeclientset.CoordinationV1().Leases(metav1.NamespaceSystem).Get(context.TODO(), v.APIServerID, metav1.GetOptions{})
		if err != nil || lease == nil || lease.Labels == nil ||
			lease.Labels[controlplane.IdentityLeaseComponentLabelKey] != controlplane.KubeAPIServer {
			// We cannot find a corresponding identity lease from apiserver as well.
			// We need to clean up this storage version.
			hasInvalidID = true
			continue
		}
		serverStorageVersions = append(serverStorageVersions, v)
	}
	if !hasInvalidID {
		return nil
	}
	return c.updateOrDeleteStorageVersion(sv, serverStorageVersions)
}

func (c *Controller) onAddStorageVersion(obj interface{}) {
	castObj := obj.(*apiserverinternalv1alpha1.StorageVersion)
	c.enqueueStorageVersion(castObj)
}

func (c *Controller) onUpdateStorageVersion(oldObj, newObj interface{}) {
	castNewObj := newObj.(*apiserverinternalv1alpha1.StorageVersion)
	c.enqueueStorageVersion(castNewObj)
}

// enqueueStorageVersion enqueues the storage version if it has entry for invalid apiserver
func (c *Controller) enqueueStorageVersion(obj *apiserverinternalv1alpha1.StorageVersion) {
	for _, sv := range obj.Status.StorageVersions {
		lease, err := c.leaseLister.Leases(metav1.NamespaceSystem).Get(sv.APIServerID)
		if err != nil || lease == nil || lease.Labels == nil ||
			lease.Labels[controlplane.IdentityLeaseComponentLabelKey] != controlplane.KubeAPIServer {
			// we cannot find a corresponding identity lease in cache, enqueue the storageversion
			klog.V(4).Infof("Observed storage version %s with invalid apiserver entry", obj.Name)
			c.storageVersionQueue.Add(obj.Name)
			return
		}
	}
}

func (c *Controller) onDeleteLease(obj interface{}) {
	castObj, ok := obj.(*coordinationv1.Lease)
	if !ok {
		tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
		if !ok {
			utilruntime.HandleError(fmt.Errorf("couldn't get object from tombstone %#v", obj))
			return
		}
		castObj, ok = tombstone.Obj.(*coordinationv1.Lease)
		if !ok {
			utilruntime.HandleError(fmt.Errorf("tombstone contained object that is not a Lease %#v", obj))
			return
		}
	}

	if castObj.Namespace == metav1.NamespaceSystem &&
		castObj.Labels != nil &&
		castObj.Labels[controlplane.IdentityLeaseComponentLabelKey] == controlplane.KubeAPIServer {
		klog.V(4).Infof("Observed lease %s deleted", castObj.Name)
		c.enqueueLease(castObj)
	}
}

func (c *Controller) enqueueLease(obj *coordinationv1.Lease) {
	c.leaseQueue.Add(obj.Name)
}

func setCommonEncodingVersion(sv *apiserverinternalv1alpha1.StorageVersion) {
	if len(sv.Status.StorageVersions) == 0 {
		return
	}
	firstVersion := sv.Status.StorageVersions[0].EncodingVersion
	agreed := true
	for _, ssv := range sv.Status.StorageVersions {
		if ssv.EncodingVersion != firstVersion {
			agreed = false
			break
		}
	}
	if agreed {
		sv.Status.CommonEncodingVersion = &firstVersion
	} else {
		sv.Status.CommonEncodingVersion = nil
	}
}

func (c *Controller) updateOrDeleteStorageVersion(sv *apiserverinternalv1alpha1.StorageVersion, serverStorageVersions []apiserverinternalv1alpha1.ServerStorageVersion) error {
	if len(serverStorageVersions) == 0 {
		return c.kubeclientset.InternalV1alpha1().StorageVersions().Delete(
			context.TODO(), sv.Name, metav1.DeleteOptions{})
	}
	sv.Status.StorageVersions = serverStorageVersions
	setCommonEncodingVersion(sv)
	_, err := c.kubeclientset.InternalV1alpha1().StorageVersions().UpdateStatus(
		context.TODO(), sv, metav1.UpdateOptions{})
	return err
}


text:
package de.fraunhofer.fokus.oefit.particity.scheduler;

import java.util.List;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageListener;
import com.liferay.portal.kernel.messaging.MessageListenerException;
import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;

import de.fraunhofer.fokus.oefit.particity.model.AHAddr;
import de.fraunhofer.fokus.oefit.particity.model.AHOffer;
import de.fraunhofer.fokus.oefit.particity.model.AHOrg;
import de.fraunhofer.fokus.oefit.particity.model.AHRegion;
import de.fraunhofer.fokus.oefit.particity.service.AHAddrLocalServiceUtil;
import de.fraunhofer.fokus.oefit.particity.service.AHOfferLocalServiceUtil;
import de.fraunhofer.fokus.oefit.particity.service.AHOrgLocalServiceUtil;
import de.fraunhofer.fokus.oefit.particity.service.AHRegionLocalServiceUtil;

/**
 * Scheduler for daily tasks
 */
public class DailyScheduler implements MessageListener {

	private static final Log	m_objLog	= LogFactoryUtil
	                                             .getLog(DailyScheduler.class);

	/* (non-Javadoc)
	 * @see com.liferay.portal.kernel.messaging.MessageListener#receive(com.liferay.portal.kernel.messaging.Message)
	 */
	@Override
	public void receive(final Message message) throws MessageListenerException {
		try {

			// removeOrganisationsWithoutUsers();
			// removeOffersWithoutOrganisations();
			// removeOrphanedAddresses();
			// removeOrphanedRegions();
			// removeOffersWithoutAddresses();

			m_objLog.info("Daily scheduler update done.");
		} catch (final Throwable t) {
			m_objLog.warn(
			        "Could not exec daily schedule due to: " + t.getMessage(),
			        t);
		}
	}

	/**
	 * Removes the offers without addresses.
	 */
	public void removeOffersWithoutAddresses() {
		try {
			final int offerSize = AHOfferLocalServiceUtil.getAHOffersCount();
			if (offerSize > 0) {
				List<AHOffer> offers;
				AHAddr addr;
				for (int i = 0; i < offerSize; i += 5) {
					offers = AHOfferLocalServiceUtil.getAHOffers(i, i + 5);
					for (final AHOffer offer : offers) {
						try {
							addr = AHAddrLocalServiceUtil.getAHAddr(offer
							        .getAdressId());
						} catch (final Throwable t) {
							addr = null;
						}
						if (addr == null) {
							AHOfferLocalServiceUtil.deleteAHOffer(offer
							        .getOfferId());
							m_objLog.warn("Removing offer "
							        + offer.getOfferId() + "/"
							        + offer.getTitle()
							        + " due to missing address "
							        + offer.getAdressId());
						}
					}
				}
			}
		} catch (final Throwable t) {
			m_objLog.warn(
			        "Check for orphaned offers failed due to " + t.getMessage(),
			        t);
		}
	}

	/**
	 * Removes the offers without organisations.
	 */
	public void removeOffersWithoutOrganisations() {
		try {
			final int offerSize = AHOfferLocalServiceUtil.getAHOffersCount();
			if (offerSize > 0) {
				List<AHOffer> offers;
				AHOrg org;
				for (int i = 0; i < offerSize; i += 5) {
					offers = AHOfferLocalServiceUtil.getAHOffers(i, i + 5);
					for (final AHOffer offer : offers) {
						final long orgId = offer.getOrgId();
						try {
							org = AHOrgLocalServiceUtil.getAHOrg(orgId);
						} catch (final Throwable t) {
							org = null;
						}
						if (org == null) {
							AHOfferLocalServiceUtil.deleteAHOffer(offer
							        .getOfferId());
							m_objLog.warn("Removing offer "
							        + offer.getOfferId() + "/"
							        + offer.getTitle()
							        + " due to missing organisation "
							        + offer.getOrgId());
						}
					}
				}
			}
		} catch (final Throwable t) {
			m_objLog.warn(
			        "Check for orphaned offers failed due to " + t.getMessage(),
			        t);
		}
	}

	/**
	 * Removes the organisations without users.
	 */
	public void removeOrganisationsWithoutUsers() {
		try {
			final long companyId = PortalUtil.getDefaultCompanyId();
			final int orgSize = AHOrgLocalServiceUtil.getAHOrgsCount();
			if (orgSize > 0) {
				List<AHOrg> orgs;
				for (int i = 0; i < orgSize; i += 5) {
					orgs = AHOrgLocalServiceUtil.getAHOrgs(i, i + 5);
					for (final AHOrg org : orgs) {
						final String mail = org.getOwner();
						User user = null;
						try {
							user = UserLocalServiceUtil.getUserByEmailAddress(
							        companyId, mail);
						} catch (final Throwable t) {
						}
						if (user == null) {
							m_objLog.warn("Removing organisation "
							        + org.getOrgId() + "/" + org.getName()
							        + " due to missing user.");
							AHOrgLocalServiceUtil.deleteOrganisation(org
							        .getOrgId());
						}
					}
				}
			}
		} catch (final Throwable t) {
			m_objLog.warn(
			        "Check for inactive organisations failed due to "
			                + t.getMessage(), t);
		}
	}

	/**
	 * Removes the orphaned addresses.
	 */
	public void removeOrphanedAddresses() {
		try {
			final int addrSize = AHAddrLocalServiceUtil.getAHAddrsCount();
			if (addrSize > 0) {
				List<AHAddr> addresses;
				for (int i = 0; i < addrSize; i += 5) {
					addresses = AHAddrLocalServiceUtil.getAHAddrs(i, i + 5);
					for (final AHAddr addr : addresses) {
						final int size = AHOfferLocalServiceUtil
						        .countOfferByAddress(addr.getAddrId());
						if (size <= 0) {
							AHAddrLocalServiceUtil.deleteAHAddr(addr
							        .getAddrId());
							m_objLog.info("Removing address "
							        + addr.getStreet() + " " + addr.getNumber()
							        + " with " + size + " offers!");
						}
					}
				}
			}

		} catch (final Throwable t) {
			m_objLog.warn("Check for orphaned addresses/regions failed due to "
			        + t.getMessage(), t);
		}
	}

	/**
	 * Removes the orphaned regions.
	 */
	public void removeOrphanedRegions() {
		try {
			final int regSize = AHRegionLocalServiceUtil.getAHRegionsCount();
			if (regSize > 0) {
				List<AHRegion> regions;
				for (int i = 0; i < regSize; i += 5) {
					regions = AHRegionLocalServiceUtil.getAHRegions(i, i + 5);
					for (final AHRegion region : regions) {
						// TODO : count only
						final List<AHAddr> addrs = AHAddrLocalServiceUtil
						        .findAddressesForRegion(region.getRegionId());
						if (addrs == null || addrs.size() == 0) {
							AHRegionLocalServiceUtil.removeRegion(region
							        .getRegionId());
							m_objLog.info("Removing region " + region.getZip()
							        + ", " + region.getCity()
							        + " without addresses!");
						}
					}
				}
			}

		} catch (final Throwable t) {
			m_objLog.warn("Check for orphaned addresses/regions failed due to "
			        + t.getMessage(), t);
		}
	}
}


text:
PySFLib
=======

PySFLib is a python library used by the Software Factory project ( https://softwarefactory-project.io ).
It is a set of wrappers over some REST APIs (Gerrit, Redmine, ...) to simplify
management tasks on Software Factory, and provide authentication.

Installation
------------

Clone this repository, then::

  cd pysflib && pip install .

Contribute
----------

This project is hosted on https://softwarefactory-project.io and contributions
undergo a reviewing process. To contribute, please clone the repository at
https://softwarefactory-project.io and setup a gerrit review account (see
Software Factory's documentation for more information).


text:
<!DOCTYPE html>

    <title>Poi · Little World</title>
    <meta name="generator" content="Hugo 0.17-DEV" />
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="author" content="carbin-gun">

      <meta name="description" content="Hello,World!">

      <link href="http://littleworld.me/tags/poi/index.xml" rel="alternate" type="application/rss+xml" title="Little World" />
      <link href="http://littleworld.me/tags/poi/index.xml" rel="feed" type="application/rss+xml" title="Little World" />

    <link rel="icon" href="http://littleworld.me/favicon.ico">
    <link rel="apple-touch-icon" href="http://littleworld.me/apple-touch-icon.png" />
    <link rel="stylesheet" href="http://littleworld.me/css/style.css">
    <link rel="stylesheet" href="http://littleworld.me/css/font-awesome.min.css">
    <link rel="stylesheet" href="http://littleworld.me/css/monokai.css">
    <link rel="stylesheet" href="http://littleworld.me/fancybox/jquery.fancybox.css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:400italic,400,600' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro' rel='stylesheet' type='text/css'>
    <meta property="og:title" content="Poi" />
<meta property="og:description" content="" />
<meta property="og:type" content="website" />
<meta property="og:url" content="http://littleworld.me/tags/poi/" />

<meta property="og:updated_time" content="2016-07-31T20:54:41+08:00"/>

<meta itemprop="name" content="Poi">
<meta itemprop="description" content="">

          Little World

          Home

          Tags

          Categories

          <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form">
              <input type="search" name="q" results="0" class="search-form-input" placeholder="Search">
              <button type="submit" class="search-form-submit">
              </button>
              <input type="hidden" name="q" value="site:http://littleworld.me/">
         </form>

          Home

          Tags

          Categories

          <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form">
          <input type="search" name="q" results="0" class="search-form-input" placeholder="Search">
          <input type="hidden" name="q" value="site:http://littleworld.me/">
          </form>

carbin-gun

Programmer - Gopher - Blogger

      Beijing

              Follow

        6
        Posts

          10

            Tags

                    Poi

            excel export by poi

                <time datetime="2016-07-31 20:54:41 +0800 CST" itemprop="datePublished">2016-07-31</time>

        Recents

                        programming

zookeeper introduction with expiration explanation

                        <time datetime="2016-11-24 14:02:41 +0800 CST" itemprop="datePublished">2016-11-24</time>

                        programming

golang build tags

                        <time datetime="2016-10-18 12:00:00 +0800 CST" itemprop="datePublished">2016-10-18</time>

                        programming

Redis Lock

                        <time datetime="2016-10-16 14:07:41 +0800 CST" itemprop="datePublished">2016-10-16</time>

                        programming

redis string operations

                        <time datetime="2016-10-14 16:20:41 +0800 CST" itemprop="datePublished">2016-10-14</time>

                        programming

excel export by poi

                        <time datetime="2016-07-31 20:54:41 +0800 CST" itemprop="datePublished">2016-07-31</time>

Categories

                    cache

                2

                    golang

                1

                    programming

                6

        Tags

                    distribute

                1

                    golang

                1

                    lock

                1

                    poi

                1

                    queue

                1

                    rabbitmq

                1

                    rate-limit

                1

                    redis

                2

                    string

                1

                    zookeeper

                1

        Tag cloud

        distribute

        golang

        lock

        poi

        queue

        rabbitmq

        rate-limit

        redis

        string

        zookeeper

      © 2016
      Powered by Hugo. Theme by PPOffice.


text:
package org.mrgeo.ingest;

import org.junit.*;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import org.mrgeo.data.ProviderProperties;
import org.mrgeo.data.raster.MrGeoRaster;
import org.mrgeo.image.MrsImage;
import org.mrgeo.image.MrsPyramid;
import org.mrgeo.image.MrsPyramidMetadata;
import org.mrgeo.junit.IntegrationTest;
import org.mrgeo.junit.UnitTest;
import org.mrgeo.test.LocalRunnerTest;
import org.mrgeo.test.TestUtils;
import org.mrgeo.utils.GDALUtils;
import org.mrgeo.utils.LongRectangle;
import org.mrgeo.utils.tms.Bounds;
import org.mrgeo.utils.tms.TMSUtils;

import java.awt.image.DataBuffer;
import java.io.IOException;
import java.util.HashMap;

@SuppressWarnings("all") // test code, not included in production
public class IngestImageTest extends LocalRunnerTest
{
public final static boolean GEN_BASELINE_DATA_ONLY = false;
private static TestUtils testUtils;
@Rule
public TestName testname = new TestName();
private String onetile = "onetile.tif";
private String bigtile = "bigtile.tif";
private String shiftedtile = "shiftedtile.tif";
private String[] fourtiles = {
    "fourtiles-1-1.tif",
    "fourtiles-1-2.tif",
    "fourtiles-2-1.tif",
    "fourtiles-2-2.tif"
};

@BeforeClass
public static void init() throws IOException
{
  testUtils = new TestUtils(IngestImageTest.class);
}

@Before
public void setup() throws IOException
{
}

@Test
@Category(UnitTest.class)
public void ingestOneTile() throws IOException
{

//  def localIngest(inputs: Array[String], output: String,
//    categorical: Boolean, skipCategoryLoad: Boolean, config: Configuration, bounds: Bounds,
//    zoomlevel: Int, tilesize: Int, nodata: Array[Double], bands: Int, tiletype: Int,
//    tags: java.util.Map[String, String], protectionLevel: String,
//    providerProperties: ProviderProperties): Boolean = {

  String input = testUtils.getInputLocalFor(onetile);
  String output = testUtils.getOutputHdfsFor(testname.getMethodName()).toString();

  int tilesize = 512;
  int zoom = GDALUtils.calculateZoom(input, tilesize);
  Bounds bounds = GDALUtils.getBounds(GDALUtils.open(input));

  IngestImage.localIngest(new String[]{input}, output, false, false, getConfiguration(),
      bounds, zoom, tilesize, new double[]{-9999}, 1, DataBuffer.TYPE_FLOAT,
      new HashMap<String, String>(), "", new ProviderProperties());

  MrsPyramid ingested = MrsPyramid.open(output, getConfiguration());
  MrsPyramidMetadata meta = ingested.getMetadata();

  Assert.assertEquals("Bad zoom", 3, meta.getMaxZoomLevel());

  LongRectangle tb = meta.getTileBounds(zoom);
  Assert.assertEquals("Wrong number of tiles", 1, tb.getWidth() * tb.getHeight());

  try (MrsImage image = ingested.getImage(zoom))
  {
    MrGeoRaster raster = image.getRaster();

    TestUtils.compareNumberedRaster(raster);
  }
}

@Test
@Category(UnitTest.class)
public void ingestFourTiles() throws IOException
{

//  def localIngest(inputs: Array[String], output: String,
//    categorical: Boolean, skipCategoryLoad: Boolean, config: Configuration, bounds: Bounds,
//    zoomlevel: Int, tilesize: Int, nodata: Array[Double], bands: Int, tiletype: Int,
//    tags: java.util.Map[String, String], protectionLevel: String,
//    providerProperties: ProviderProperties): Boolean = {

  String[] inputs = new String[fourtiles.length];
  for (int i = 0; i < fourtiles.length; i++)
  {
    inputs[i] = testUtils.getInputLocalFor(fourtiles[i]);
  }

  String output = testUtils.getOutputHdfsFor(testname.getMethodName()).toString();

  int zoom = 3;
  int tilesize = 512;

  Bounds bounds = null;
  for (int x = 1; x < 3; x++)
  {
    for (int y = 1; y < 3; y++)
    {
      if (bounds == null)
      {
        bounds = TMSUtils.tileBounds(x, y, zoom, tilesize);
      }
      else
      {
        bounds = bounds.expand(TMSUtils.tileBounds(x, y, zoom, tilesize));
      }
    }
  }

  IngestImage.localIngest(inputs, output, false, false, getConfiguration(),
      bounds, zoom, tilesize, new double[]{-9999}, 1, DataBuffer.TYPE_FLOAT,
      new HashMap<String, String>(), "", new ProviderProperties());

  MrsPyramid ingested = MrsPyramid.open(output, getConfiguration());
  MrsPyramidMetadata meta = ingested.getMetadata();

  Assert.assertEquals("Bad zoom", zoom, meta.getMaxZoomLevel());

  LongRectangle tb = meta.getTileBounds(zoom);
  Assert.assertEquals("Wrong number of tiles", 4, tb.getWidth() * tb.getHeight());

  try (MrsImage image = ingested.getImage(zoom))
  {
    MrGeoRaster raster = image.getRaster();

    for (int y = 0; y < raster.height(); y++)
    {
      for (int x = 0; x < raster.width(); x++)
      {
        int pixelId = (x % tilesize) + ((y % tilesize) * tilesize);

        Assert.assertEquals(
            "Bad pixel px: " + x + " py: " + y + " expected: " + pixelId + " actual: " + raster.getPixelDouble(x, y, 0),
            pixelId, raster.getPixelDouble(x, y, 0), 1e-8);
      }
    }
  }
}

@Test
@Category(UnitTest.class)
public void ingestTileShifted() throws IOException
{

//  def localIngest(inputs: Array[String], output: String,
//    categorical: Boolean, skipCategoryLoad: Boolean, config: Configuration, bounds: Bounds,
//    zoomlevel: Int, tilesize: Int, nodata: Array[Double], bands: Int, tiletype: Int,
//    tags: java.util.Map[String, String], protectionLevel: String,
//    providerProperties: ProviderProperties): Boolean = {

  String input = testUtils.getInputLocalFor(shiftedtile);
  String output = testUtils.getOutputHdfsFor(testname.getMethodName()).toString();

  int tilesize = 512;
  int zoom = GDALUtils.calculateZoom(input, tilesize);
  Bounds bounds = GDALUtils.getBounds(GDALUtils.open(input));

  IngestImage.localIngest(new String[]{input}, output, false, false, getConfiguration(),
      bounds, zoom, tilesize, new double[]{-9999}, 1, DataBuffer.TYPE_FLOAT,
      new HashMap<String, String>(), "", new ProviderProperties());

  MrsPyramid ingested = MrsPyramid.open(output, getConfiguration());
  MrsPyramidMetadata meta = ingested.getMetadata();

  Assert.assertEquals("Bad zoom", 3, meta.getMaxZoomLevel());

  LongRectangle tb = meta.getTileBounds(zoom);
  Assert.assertEquals("Wrong number of tiles", 4, tb.getWidth() * tb.getHeight());

  try (MrsImage image = ingested.getImage(zoom))
  {
    MrGeoRaster raster = image.getRaster();

    int pixelId = 0;
    for (int y = 0; y < raster.height(); y++)
    {
      for (int x = 0; x < raster.width(); x++)
      {
        int px = raster.getPixelInt(x, y, 0);
        if (px != -9999)
        {
          Assert.assertEquals(
              "Bad pixel px: " + x + " py: " + y + " expected: " + pixelId + " actual: " + raster.getPixelInt(x, y, 0),
              pixelId, raster.getPixelInt(x, y, 0));

          pixelId++;
        }
//        else
//        {
//          System.out.println("px: " + x + " py: " + y);
//        }
      }
    }
  }
}

// This test has differences between GDAL 1.x and GDAL 2.x.  We therefor need to have 2 golden images
@Test
@Category(IntegrationTest.class)
public void ingestBigtile() throws IOException
{

//  def localIngest(inputs: Array[String], output: String,
//    categorical: Boolean, skipCategoryLoad: Boolean, config: Configuration, bounds: Bounds,
//    zoomlevel: Int, tilesize: Int, nodata: Array[Double], bands: Int, tiletype: Int,
//    tags: java.util.Map[String, String], protectionLevel: String,
//    providerProperties: ProviderProperties): Boolean = {

  String input = testUtils.getInputLocalFor(bigtile);
  String output = testUtils.getOutputHdfsFor(testname.getMethodName()).toString();

  int tilesize = 512;
  int zoom = 9; // GDALUtils.calculateZoom(input, tilesize);

  Bounds bounds = GDALUtils.getBounds(GDALUtils.open(input));
  IngestImage.localIngest(new String[]{input}, output, false, false, getConfiguration(),
      bounds, zoom, tilesize, new double[]{-9999}, 1, DataBuffer.TYPE_FLOAT,
      new HashMap<String, String>(), "", new ProviderProperties());

  MrsPyramid ingested = MrsPyramid.open(output, getConfiguration());
  MrsPyramidMetadata meta = ingested.getMetadata();

  Assert.assertEquals("Bad zoom", zoom, meta.getMaxZoomLevel());

  LongRectangle tb = meta.getTileBounds(zoom);
  //Assert.assertEquals("Wrong number of tiles", 6, tb.getWidth() * tb.getHeight());

  try (MrsImage image = ingested.getImage(zoom))
  {
    MrGeoRaster raster = image.getRaster();

    if (GEN_BASELINE_DATA_ONLY)
    {
      testUtils.saveBaselineTif(testname.getMethodName(), raster,
          TMSUtils.tileBounds(bounds, zoom, tilesize), -9999, true);
    }
    else
    {
      testUtils.compareRasters(testname.getMethodName(), raster, true);
    }

  }
}

}


text:
download: https://s3.eu-central-1.amazonaws.com/s3ctf.tf/crackme1_by_neo_theone.zip
---


text:
namespace MassTransit.EventHubIntegration
{
    using System.Threading;
    using Azure.Messaging.EventHubs.Producer;
    using Configuration;
    using MassTransit.Middleware;

    public class SharedConnectionContext :
        ProxyPipeContext,
        ConnectionContext
    {
        readonly ConnectionContext _context;

        public SharedConnectionContext(ConnectionContext context, CancellationToken cancellationToken)
            : base(context)
        {
            _context = context;
            CancellationToken = cancellationToken;
        }

        public override CancellationToken CancellationToken { get; }

        public IHostSettings HostSettings => _context.HostSettings;

        public IStorageSettings StorageSettings => _context.StorageSettings;

        public EventHubProducerClient CreateEventHubClient(string eventHubName)
        {
            return _context.CreateEventHubClient(eventHubName);
        }
    }
}


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

<title>The GNU Fortran Compiler: Extensions not implemented in GNU Fortran</title>

<meta name="description" content="The GNU Fortran Compiler: Extensions not implemented in GNU Fortran">
<meta name="keywords" content="The GNU Fortran Compiler: Extensions not implemented in GNU Fortran">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Option-Index.html#Option-Index" rel="index" title="Option Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Extensions.html#Extensions" rel="up" title="Extensions">
<link href="STRUCTURE-and-RECORD.html#STRUCTURE-and-RECORD" rel="next" title="STRUCTURE and RECORD">
<link href="Argument-list-functions.html#Argument-list-functions" rel="prev" title="Argument list functions">

Previous: Extensions implemented in GNU Fortran, Up: Extensions   [Contents][Index]

6.2 Extensions not implemented in GNU Fortran

The long history of the Fortran language, its wide use and broad
userbase, the large number of different compiler vendors and the lack of
some features crucial to users in the first standards have lead to the
existence of a number of important extensions to the language.  While
some of the most useful or popular extensions are supported by the GNU
Fortran compiler, not all existing extensions are supported.  This section
aims at listing these extensions and offering advice on how best make
code that uses them running with the GNU Fortran compiler.

• STRUCTURE and RECORD:

• ENCODE and DECODE statements:

• Variable FORMAT expressions:

• Alternate complex function syntax:

• Volatile COMMON blocks:


text:
permalink: /tree/components/o-tree-node.component/overview
title: "Tree"
comp: treeNode
layout: o-component
---
{% include base_path %}
{% include toc %}

## Introduction
The `o-tree-node` component allows to define inner nodes of another `o-tree-node` or the root `o-tree` component.

## Parent keys
When using a remote data binded tree component, a `o-tree-node` must specify in its `parent-keys` attribute which parent node registry property is going to use for doing its data query.

Example

```html
<o-tree #treeview fxFlex root-title="CUSTOMERS" service="customers" entity="customer"
  keys="CUSTOMERID" columns="CUSTOMERID;SURNAME;NAME"
  description-columns="SURNAME;NAME" separator=", ">

<o-tree-node root-title="ACCOUNTS" show-root="no" service="customers"
  entity="customerAccount" columns="ACCOUNTID;CUSTOMERID;ACCOUNT"
  description-columns="ACCOUNT" keys="ACCOUNTID" parent-keys="CUSTOMERID">

  <o-tree-node root-title="ACCOUNT_CONCEPTS" show-root="no" service="branches"
    entity="accountConcepts" columns="CONCEPT;ACCOUNTID"
    description-columns="CONCEPT" keys="CONCEPT;ACCOUNTID" parent-keys="ACCOUNTID">
  </o-tree-node>

  <o-tree-node root-title="ACCOUNT_MOVEMENTTYPES" show-root="no"
    service="branches" entity="accountMovementTypes" columns="DESCRIPTION;ACCOUNTID"
    description-columns="DESCRIPTION" keys="DESCRIPTION;ACCOUNTID"
    parent-keys="ACCOUNTID">
  </o-tree-node>

</o-tree-node>

</o-tree>
```

![Tree component]({{ "/images/components/tree/inner.png" | absolute_url }}){: .comp-example-img}

## Quick filter

You can configure the same `o-tree` component filtering properties, that will only affect to this tree node.

## Demo

You can see an example of this component behaviour in this [OntimizeWeb tree quickstart](https://try.imatia.com/ontimizeweb/tree/main/nodes){:target="_blank"} section.


text:
require_relative './init'
require 'timecop'

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
end

describe User do
  before do
    IntegrationSpecHelper.InitializeMongo()
  end

  before(:each) do
    User.destroy_all
    @sut = build(:helper)
    @sut.save
  end

  describe "can create user, with firstname" do
    it {  expect(@sut.first_name).to eq("Helper") }
  end

  describe "awake times in different timezones" do
    it "sets default wake up time in utc" do
      expected = DEFAULT_WAKE_UP_HOUR - 2 #withdraw the utc_offset
      expect(@sut.wake_up_in_seconds_since_midnight).to eq(expected  * 3600)
    end

    it "can change the timezone" do
      @sut.utc_offset = 7
      @sut.wake_up = "07:00"
      @sut.save!

      expect(@sut.wake_up_in_seconds_since_midnight).to eq(0)
    end

    it "can change the wake up time" do
      @sut.wake_up = "10:00"
      @sut.save!

      expect(@sut.wake_up_in_seconds_since_midnight).to eq(8 * 3600)
    end
  end

  describe "only returns awake users" do
    before(:each) do
      Helper.destroy_all
    end
    it "does not wake up asleep helper in DK when blind from US needs help" do
      request = build(:request)

      Timecop.freeze(Time.gm(2014,"jul",9,4,30) ) do
        asleep_users = User.asleep_users.where(role: "helper")
        expect(asleep_users.count).to eq(1)

        available_helpers = request.helper.available request
        expect(available_helpers.count).to eq(0)
      end
    end

    it "asleep user not returned as awake" do
      @sut.utc_offset = 0
      @sut.go_to_sleep = "22:00"
      @sut.save!
      Timecop.travel(Time.gm(2000,"jan",1,23,15,1) ) do
        awake_users = User.asleep_users
        expect(awake_users.count).to eq(1)
      end
    end

    it "one awake one asleep, only awake is choosen" do
      @sut.utc_offset = 0
      @sut.go_to_sleep = "22:00"
      @sut.save!

      awake = build(:helper)
      awake.utc_offset = 0
      awake.go_to_sleep = "23:30"
      awake.save!

      Timecop.travel(Time.gm(2000,"jan",1,23,15,1) ) do
        asleep_users = User.asleep_users
        expect(asleep_users.count).to eq(1)
      end
    end

    it "user in another timezone, called in the afternoon" do
      @sut.utc_offset = -4
      @sut.go_to_sleep = "22:00"
      @sut.save!
      Timecop.travel(Time.gm(2000,"jan",1,20,15,1) ) do
        asleep_users = User.asleep_users
        expect(asleep_users.count).to eq(0)
      end
    end

    it "user in another timezone, not called in the night" do
      @sut.utc_offset =  4
      @sut.go_to_sleep = "22:00"
      @sut.save!
      Timecop.travel(Time.gm(2000,"jan",1,20,15,1) ) do
        asleep_users = User.asleep_users
        expect(asleep_users.count).to eq(1)
      end
    end

    it "awake user returned as awake" do
      @sut.utc_offset = 0
      @sut.go_to_sleep = "22:00"
      @sut.save!
      Timecop.travel(Time.gm(2000,"jan",1,20,15,1) ) do
        asleep_users = User.asleep_users
        expect(asleep_users.count).to eq(0)
      end
    end
  end
end


text:
CC=g++
CFLAGS=-Wall
LDFLAGS=-lwiringPi -lpthread

shutoffpower:
	$(CC) $(CFLAGS) ShutOffPower.cpp -o ShutOffPower $(LDFLAGS)

clean:
	rm ShutOffPower


text:
package parquet.filter;

import parquet.Preconditions;
import parquet.column.ColumnReader;

/**
 * ColumnPredicates class provides checks for column values. Factory methods
 * are provided for standard predicates which wrap the job of getting the
 * correct value from the column.
 */
public class ColumnPredicates {

  public static interface Predicate {
    boolean apply(ColumnReader input);
  }

  public static Predicate equalTo(final String target) {
    Preconditions.checkNotNull(target,"target");
    return new Predicate() {
      @Override
      public boolean apply(ColumnReader input) {
        return target.equals(input.getBinary().toStringUsingUTF8());
      }
    };
  }

  public static Predicate equalTo(final int target) {
    return new Predicate() {
      @Override
      public boolean apply(ColumnReader input) {
        return input.getInteger() == target;
      }
    };
  }

  public static Predicate equalTo(final long target) {
    return new Predicate() {
      @Override
      public boolean apply(ColumnReader input) {
        return input.getLong() == target;
      }
    };
  }

  public static Predicate equalTo(final float target) {
    return new Predicate() {
      @Override
      public boolean apply(ColumnReader input) {
        return input.getFloat() == target;
      }
    };
  }

  public static Predicate equalTo(final double target) {
    return new Predicate() {
      @Override
      public boolean apply(ColumnReader input) {
        return input.getDouble() == target;
      }
    };
  }

  public static Predicate equalTo(final boolean target) {
    return new Predicate() {
      @Override
      public boolean apply(ColumnReader input) {
        return input.getBoolean() == target;
      }
    };
  }

  public static <E extends Enum> Predicate equalTo(final E target) {
    Preconditions.checkNotNull(target,"target");
    final String targetAsString = target.name();
    return new Predicate() {
      @Override
      public boolean apply(ColumnReader input) {
        return targetAsString.equals(input.getBinary().toStringUsingUTF8());
      }
    };
  }
}


text:
<?php

declare(strict_types=1);

namespace Smuuf\Primi\Helpers;

use \Smuuf\Primi\Ex\IndexError;
use \Smuuf\Primi\Values\AbstractValue;

/**
 * Helpers for handling accessing PHP arrays via possibly negative indices.
 */
abstract class Indices {

	/**
	 * Translate negative index to positive index that's a valid index for a
	 * given number of items.
	 *
	 * Return `null` when it's not possible to do so.
	 *
	 * For example:
	 * - index 1 for list with 2 items -> index == 1
	 * - index 2 for list with 2 items -> NOT FOUND!
	 * - index -1 for list with 2 items -> index == <max_index> - 1 (= 1)
	 * - index -2 for list with 2 items -> index == <max_index> - 2 (= 0)
	 * - index -3 for list with 2 items -> NOT FOUND!
	 */
	public static function resolveNegativeIndex(
		int $index,
		int $maxIndex
	): ?int {

		$normalized = $index < 0
			? $maxIndex + $index + 1
			: $index;

		if ($normalized < 0 || $normalized > $maxIndex) {
			return \null;
		}

		return $normalized;

	}

	/**
	 * Return resolved positive array index based on possibly negative index
	 * passed as the first argument.
	 *
	 * If the negative index could not be resolved, or if the index does not
	 * represent an existing index in the array passed as the second argument,
	 * an IndexError exception is thrown.
	 *
	 * @param array<int, AbstractValue>|\ArrayAccess<int, AbstractValue> $array
	 * @return mixed
	 */
	public static function resolveIndexOrError(int $index, $array) {

		$actualIndex = self::resolveNegativeIndex($index, \count($array) - 1);
		if ($actualIndex === \null || !isset($array[$actualIndex])) {

			// $index on purpose - report error with the index originally used.
			throw new IndexError($index);

		}

		return $actualIndex;

	}

}


text:
"""remove starred change financial_id to string

Revision ID: 17ba496fb5ee
Revises: 2e30804e1994
Create Date: 2015-08-19 15:32:31.587407

"""

# revision identifiers, used by Alembic.
revision = '17ba496fb5ee'
down_revision = '2e30804e1994'

from alembic import op
import sqlalchemy as sa

index_set = [
    'tsv_contract_description',
    'tsv_company_name',
    'tsv_detail_value',
    'tsv_line_item_description'
]

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()

    # drop the search_view
    conn.execute(sa.sql.text('''
    DROP MATERIALIZED VIEW IF EXISTS search_view
    '''))

    op.drop_table('contract_starred_association')
    op.alter_column(u'contract', 'financial_id',
               existing_type=sa.Integer(),
               type_=sa.String(255),
               )

    # recreate our search view
    conn.execute(sa.sql.text('''
    CREATE MATERIALIZED VIEW search_view AS (
        SELECT
            c.id::VARCHAR || contract_property.id::VARCHAR || line_item.id::VARCHAR || company.id::VARCHAR AS id,
            c.id AS contract_id,
            company.id AS company_id,
            c.expiration_date, c.financial_id,
            c.description AS contract_description,
            to_tsvector(c.description) AS tsv_contract_description,
            company.company_name AS company_name,
            to_tsvector(company.company_name) AS tsv_company_name,
            contract_property.key AS detail_key,
            contract_property.value AS detail_value,
            to_tsvector(contract_property.value) AS tsv_detail_value,
            line_item.description AS line_item_description,
            to_tsvector(line_item.description) AS tsv_line_item_description
        FROM contract c
        LEFT OUTER JOIN contract_property ON c.id = contract_property.contract_id
        LEFT OUTER JOIN line_item ON c.id = line_item.contract_id
        LEFT OUTER JOIN company_contract_association ON c.id = company_contract_association.contract_id
        LEFT OUTER JOIN company ON company.id = company_contract_association.company_id
    )
    '''))

    op.create_index(op.f('ix_search_view_id'), 'search_view', ['id'], unique=True)

    # create remaining indices on the tsv columns
    for index in index_set:
        op.create_index(op.f(
            'ix_tsv_{}'.format(index)), 'search_view', [index], postgresql_using='gin'
        )
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()

    # drop the search_view
    conn.execute(sa.sql.text('''
    DROP MATERIALIZED VIEW IF EXISTS search_view
    '''))

    conn.execute(sa.sql.text(
    '''
    ALTER TABLE contract ALTER COLUMN financial_id TYPE integer USING (financial_id::integer);
    '''
    ))

    op.create_table('contract_starred_association',
    sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=True),
    sa.Column('contract_id', sa.INTEGER(), autoincrement=False, nullable=True),
    sa.ForeignKeyConstraint(['contract_id'], [u'contract.id'], name=u'contract_starred_association_contract_id_fkey', ondelete=u'SET NULL'),
    sa.ForeignKeyConstraint(['user_id'], [u'users.id'], name=u'contract_starred_association_user_id_fkey', ondelete=u'SET NULL')
    )

    # recreate our search view
    conn.execute(sa.sql.text('''
    CREATE MATERIALIZED VIEW search_view AS (
        SELECT
            c.id::VARCHAR || contract_property.id::VARCHAR || line_item.id::VARCHAR || company.id::VARCHAR AS id,
            c.id AS contract_id,
            company.id AS company_id,
            c.expiration_date, c.financial_id,
            c.description AS contract_description,
            to_tsvector(c.description) AS tsv_contract_description,
            company.company_name AS company_name,
            to_tsvector(company.company_name) AS tsv_company_name,
            contract_property.key AS detail_key,
            contract_property.value AS detail_value,
            to_tsvector(contract_property.value) AS tsv_detail_value,
            line_item.description AS line_item_description,
            to_tsvector(line_item.description) AS tsv_line_item_description
        FROM contract c
        LEFT OUTER JOIN contract_property ON c.id = contract_property.contract_id
        LEFT OUTER JOIN line_item ON c.id = line_item.contract_id
        LEFT OUTER JOIN company_contract_association ON c.id = company_contract_association.contract_id
        LEFT OUTER JOIN company ON company.id = company_contract_association.company_id
    )
    '''))

    # create unique index on ids
    op.create_index(op.f('ix_search_view_id'), 'search_view', ['id'], unique=True)

    # create remaining indices on the tsv columns
    for index in index_set:
        op.create_index(op.f(
            'ix_tsv_{}'.format(index)), 'search_view', [index], postgresql_using='gin'
        )

    ### end Alembic commands ###


text:
package org.apache.geode.internal.cache.wan.serial;

import java.util.Set;

import org.apache.logging.log4j.Logger;

import org.apache.geode.cache.EntryEvent;
import org.apache.geode.cache.asyncqueue.AsyncEvent;
import org.apache.geode.cache.util.CacheListenerAdapter;
import org.apache.geode.internal.cache.RegionQueue;
import org.apache.geode.internal.cache.wan.AbstractGatewaySender;
import org.apache.geode.internal.cache.wan.GatewaySenderEventImpl;
import org.apache.geode.logging.internal.log4j.api.LogService;

/**
 * @since GemFire 7.0
 *
 */
public class SerialSecondaryGatewayListener extends CacheListenerAdapter<Long, AsyncEvent<?, ?>> {

  private static final Logger logger = LogService.getLogger();

  private final SerialGatewaySenderEventProcessor processor;

  private final AbstractGatewaySender sender;

  protected SerialSecondaryGatewayListener(SerialGatewaySenderEventProcessor eventProcessor) {
    processor = eventProcessor;
    sender = eventProcessor.getSender();
  }

  @Override
  public void afterCreate(EntryEvent<Long, AsyncEvent<?, ?>> event) {
    if (sender.isPrimary()) {
      // The secondary has failed over to become the primary. There is a small
      // window where the secondary has become the primary, but the listener
      // is
      // still set. Ignore any updates to the map at this point. It is unknown
      // what the state of the map is. This may result in duplicate events
      // being sent.
      return;
    }
    // There is a small window where queue has not been created fully yet.
    // The underlying region of the queue is created, and it receives afterDestroy callback
    final Set<RegionQueue> queues = sender.getQueues();
    if (queues != null && !queues.isEmpty()) {
      sender.getStatistics().incQueueSize();
    }
    // fix bug 35730

    // Send event to the event dispatcher
    GatewaySenderEventImpl senderEvent = (GatewaySenderEventImpl) event.getNewValue();
    processor.handlePrimaryEvent(senderEvent);
  }

  @Override
  public void afterDestroy(EntryEvent<Long, AsyncEvent<?, ?>> event) {
    if (sender.isPrimary()) {
      return;
    }
    // fix bug 37603
    // There is a small window where queue has not been created fully yet. The region is created,
    // and it receives afterDestroy callback.

    final Set<RegionQueue> queues = sender.getQueues();
    if (queues != null && !queues.isEmpty()) {
      sender.getStatistics().decQueueSize();
    }

    // Send event to the event dispatcher
    Object oldValue = event.getOldValue();
    if (oldValue instanceof GatewaySenderEventImpl) {
      GatewaySenderEventImpl senderEvent = (GatewaySenderEventImpl) oldValue;
      if (logger.isDebugEnabled()) {
        logger.debug("Received after Destroy for Secondary event {} the key was {}", senderEvent,
            event.getKey());
      }
      processor.handlePrimaryDestroy(senderEvent);
    }
  }
}