问:
attempt to concatenate field ' ?' (a nil value) corona SDK
hey i'm newbie both in corona and lua, i'm making a little memory game for a school project but i keep getting the error with the concatenation for a nill value, it shows the elements from the concatenation in the screen but it dosn't work

heres my code:

```<code>display.setStatusBar(display.HiddenStatusBar)
centerX=display.contentCenterX
centerY=display.contentCenterY
screenX=display.screenOriginX
screenY=display.screenOriginY
screenWidth=display.contentWidth-screenX * 1
screenHeight=display.contentHeight - screenY *1
screenLeft=screenX
screenRight=screenX + screenWidth
screenTop=screenY
screenBottom=screenY+screenHeight
display.contentWidht=screenWidth
display.contentHeight=screenHeight

display.cl=display.CenterLeftReferencePoint
local tileImg="images/lolo.png"
local hiddenObjects={
"cubo", "abeja", "mariposa", "flor",
"cubo", "abeja", "mariposa", "flor"}

local tileWidth=100
local tileHeigth=100
local tileAcross=6
local tileDown=4
local tileSpacing=2
local topSpacing=screenTop+tileHeigth+tileSpacing
local leftSpacing = screenLeft+tileWidth+tileSpacing

local numMatches=0
local numObjsShowing=0
local flipped={}
local pauseDelay=800
local score=0
local scoreTxt=nil

local allTiles={}
local allThings={}

local resetGame

local function shuffle(t)
    local n= #t
    while n > 2 do
    local k = math.random(n)
    t[n], t[k] = t[k], t[n]
    n = n-1
    end
    return t
end
 local function killObj( obj)
    display.remove( obj )
    obj = nil
 -- body
 end

 local function startOver()
    local msg
    local function start(event)
        killObj(event.target)
        resetGame()
        -- body
    end
    msg=display.newText("Tap Here To Start", 0, 0, "Helvetica", 24)
    msg.x=centerX
    msg.y=centerY+250
    msg:addEventListener("tap", start)
end
local function addToScore( addNum )
    local num = addNum or 100
    score = score +num
    scoreTxt:setReferencePoint(display.cl)
    scoreTxt.x = screenWidth+250
    -- body
end

local function checkForMatch()
    if #flipped== 2 then
        local idx1,idx2=flipped[1],flipped[2]
        local function resetNumObjsShowing()
            numObjsShowing=0

        end
        if allThings[idx1].name==allThings[idx2].name then
            audio.play(sndMatch)
            allThings[idx1]:toFront()
            allThings[idx2]:toFront()
            transition.to(allThings[idx1],{time=400, x=screenRight,                       y=screenTop, alpha=0})
            transition.to(allThings[idx2],{time=400, x=screenRight, y=screenTop, alpha=0})
            addToScore(100)
            resetNumObjsShowing()
            numMatches=numMatches+1
            if numMatches==(tileAcross * tileDown / 2) then
                audio.play(sndWinner)
                startOver()
            end
        else
            audio.play(sndNoMatch)
            transition.to(allTiles[idx1],{delay=pauseDelay, time=200,alpha=1, onComplete=resetNumObjsShowing})
            transition.to(allTiles[idx2],{delay=pauseDelay, time=200,alpha=1,})
            if score> 20 then
                addToScore(-20)
            end
    end

    flipped[1]=nil
    flipped[2]=nil
end
end

local function  tileTapped(event)
    if numObjsShowing< 2 then
        local tile=event.target
        if flipped[numObjsShowing]~=tile.idx then
            numObjsShowing=numObjsShowing+1
            flipped[numObjsShowing]=tile.idx
            transition.to(tile,{time=500,alpha=0,onComplete=checkForMatch})
        end
    end
end

local function makeTiles(things)
    local idx=1
    for x = 1, tileAcross do
        for y = 1, tileDown do
            local thing = display.newImage("images/" ..things[idx].. ".png")
            thing.x=(x+1.5)*(tileWidth + tileSpacing)+ leftSpacing
            thing.y=(y+0.9)*(tileHeigth + tileSpacing)+ topSpacing
            thing.name=things[idx]
            allThings[#allThings+1]=thing

            local tile = display.newImage(tileImg)
            tile.x =(x+1) * (tileWidth + tileSpacing)+ leftSpacing
            tile.y =(y+1) * (tileHeigth + tileSpacing)+ topSpacing
            tile.idx=idx
            tile:addEventListener("tap", tileTapped)
            allTiles[#allTiles+1]=tile

            idx=idx+1
        end
    end
end

function resetGame()
    numMatches= 0
    numObjsShowing = 0
    score = 0
    scoreTxt.text ="score: 000"
    flipped[1]=nil
    flipped[2]=nil

    if allThings ~={} then
        for x=#allThings, 1, -1 do
            killObj(allThings[x])
        end

        allThings={}
    -- body
end
if allTiles ~={} then
    for x=#allTiles,1,-1 do
        killObj(allTiles[x])
end
allTiles={}
end
makeTiles(shuffle(hiddenObjects))
end

local function setupDisplay()
local bg=display.newImage("images/paisaje1.jpg")
bg.x=centerX
bg.y=centerY
bg.width=screenWidth
bg.height=screenHeight

scoreTxt = display.newText("Score: 000", 0, 0, "Helvetica", 18)
scoreTxt.x=screenWidth-120
scoreTxt.y=screenTop+15
end
setupDisplay()
startOver()
</code>```

any suggestion is welcome

答:
The only concatenation in the code occurs in this line:

```<code>local thing = display.newImage("images/" ..things[idx].. ".png")
</code>```

So, it appears that things[idx] is nil.

Body:
hey i'm newbie both in corona and lua, i'm making a little memory game for a school project but i keep getting the error with the concatenation for a nill value, it shows the elements from the concatenation in the screen but it dosn't work

heres my code:

display.setStatusBar(display.HiddenStatusBar)
centerX=display.contentCenterX
centerY=display.contentCenterY
screenX=display.screenOriginX
screenY=display.screenOriginY
screenWidth=display.contentWidth-screenX * 1
screenHeight=display.contentHeight - screenY *1
screenLeft=screenX
screenRight=screenX + screenWidth
screenTop=screenY
screenBottom=screenY+screenHeight
display.contentWidht=screenWidth
display.contentHeight=screenHeight

display.cl=display.CenterLeftReferencePoint
local tileImg="images/lolo.png"
local hiddenObjects={
"cubo", "abeja", "mariposa", "flor",
"cubo", "abeja", "mariposa", "flor"}

local tileWidth=100
local tileHeigth=100
local tileAcross=6
local tileDown=4
local tileSpacing=2
local topSpacing=screenTop+tileHeigth+tileSpacing
local leftSpacing = screenLeft+tileWidth+tileSpacing

local numMatches=0
local numObjsShowing=0
local flipped={}
local pauseDelay=800
local score=0
local scoreTxt=nil

local allTiles={}
local allThings={}

local resetGame

local function shuffle(t)
    local n= #t
    while n > 2 do
    local k = math.random(n)
    t[n], t[k] = t[k], t[n]
    n = n-1
    end
    return t
end
 local function killObj( obj)
    display.remove( obj )
    obj = nil
 -- body
 end

 local function startOver()
    local msg
    local function start(event)
        killObj(event.target)
        resetGame()
        -- body
    end
    msg=display.newText("Tap Here To Start", 0, 0, "Helvetica", 24)
    msg.x=centerX
    msg.y=centerY+250
    msg:addEventListener("tap", start)
end
local function addToScore( addNum )
    local num = addNum or 100
    score = score +num
    scoreTxt:setReferencePoint(display.cl)
    scoreTxt.x = screenWidth+250
    -- body
end

local function checkForMatch()
    if #flipped== 2 then
        local idx1,idx2=flipped[1],flipped[2]
        local function resetNumObjsShowing()
            numObjsShowing=0

        end
        if allThings[idx1].name==allThings[idx2].name then
            audio.play(sndMatch)
            allThings[idx1]:toFront()
            allThings[idx2]:toFront()
            transition.to(allThings[idx1],{time=400, x=screenRight,                       y=screenTop, alpha=0})
            transition.to(allThings[idx2],{time=400, x=screenRight, y=screenTop, alpha=0})
            addToScore(100)
            resetNumObjsShowing()
            numMatches=numMatches+1
            if numMatches==(tileAcross * tileDown / 2) then
                audio.play(sndWinner)
                startOver()
            end
        else
            audio.play(sndNoMatch)
            transition.to(allTiles[idx1],{delay=pauseDelay, time=200,alpha=1, onComplete=resetNumObjsShowing})
            transition.to(allTiles[idx2],{delay=pauseDelay, time=200,alpha=1,})
            if score> 20 then
                addToScore(-20)
            end
    end

    flipped[1]=nil
    flipped[2]=nil
end
end

local function  tileTapped(event)
    if numObjsShowing< 2 then
        local tile=event.target
        if flipped[numObjsShowing]~=tile.idx then
            numObjsShowing=numObjsShowing+1
            flipped[numObjsShowing]=tile.idx
            transition.to(tile,{time=500,alpha=0,onComplete=checkForMatch})
        end
    end
end

local function makeTiles(things)
    local idx=1
    for x = 1, tileAcross do
        for y = 1, tileDown do
            local thing = display.newImage("images/" ..things[idx].. ".png")
            thing.x=(x+1.5)*(tileWidth + tileSpacing)+ leftSpacing
            thing.y=(y+0.9)*(tileHeigth + tileSpacing)+ topSpacing
            thing.name=things[idx]
            allThings[#allThings+1]=thing

            local tile = display.newImage(tileImg)
            tile.x =(x+1) * (tileWidth + tileSpacing)+ leftSpacing
            tile.y =(y+1) * (tileHeigth + tileSpacing)+ topSpacing
            tile.idx=idx
            tile:addEventListener("tap", tileTapped)
            allTiles[#allTiles+1]=tile

            idx=idx+1
        end
    end
end

function resetGame()
    numMatches= 0
    numObjsShowing = 0
    score = 0
    scoreTxt.text ="score: 000"
    flipped[1]=nil
    flipped[2]=nil

    if allThings ~={} then
        for x=#allThings, 1, -1 do
            killObj(allThings[x])
        end

        allThings={}
    -- body
end
if allTiles ~={} then
    for x=#allTiles,1,-1 do
        killObj(allTiles[x])
end
allTiles={}
end
makeTiles(shuffle(hiddenObjects))
end

local function setupDisplay()
local bg=display.newImage("images/paisaje1.jpg")
bg.x=centerX
bg.y=centerY
bg.width=screenWidth
bg.height=screenHeight

scoreTxt = display.newText("Score: 000", 0, 0, "Helvetica", 18)
scoreTxt.x=screenWidth-120
scoreTxt.y=screenTop+15
end
setupDisplay()
startOver()

any suggestion is welcome

Body:
The only concatenation in the code occurs in this line:

local thing = display.newImage("images/" ..things[idx].. ".png")

So, it appears that things[idx] is nil.


来源: stackexchange

问:
Tensorflow: Random selection of masks
I know that this stackoverflow thread already gives some nice examples about conditionals in tensorflow, but I'm still struggling how to solve my issue of randomly selecting among several different masks in tensorflow.

Right now I can only select between two mask tensors a and b:

```<code>rand_num = tf.random_uniform([], minval=0, maxval=2.0, dtype=tf.float32, seed=None)
def if_true():
     return b
def if_false():
     return a
mask_sel = tf.cond(tf.less(rand_num , tf.constant(1.0)),if_true,if_false)
</code>```

(I still find it weird that one needs to define these two helper functions, but not using them weirdly throws an error.)

Now the question: Lets say I have 4 mask tensors (a,b,c,d) or more to randomly select, what would be the best way to do that in tensorflow?

In python that would be

```<code>rand_num = np.random.uniform(low=0,high=4.0)
if (rand_num < 1.0):
    mask_sel = a
elif(rand_num < 2.0):
    mask_sel = b
elif(rand_num < 3.0):
    mask_sel = c
else
    mask_sel = d
</code>```

答:
About the helper functions, they are useful because they allow tensorflow to know which operations will run under each condition, this way it can optimize by running only the selected branch and ignoring the other. Operations outside the helper functions but used by any of them will always be run before tf.cond runs.

The other options is to use tf.select; you won't need the helper functions here but it will always evaluate both sides before running tf.select which can be inefficient if you don't need to.

Now for the main problem 'selecting from more than 2 tesnors', you can use multiple options:

1- Recursively nesting tf.cond operations:

```<code>def select_from_list(selector, tensor_list):
    length = len(tensor_list)
    if length == 0:
        raise ValueError('List is empty')
    elif length == 1:
        return tensor_list[0]
    else:
        half = length // 2
        return tf.cond(tf.less(selector, float(half)), lambda: select_from_list(selector, tensor_list[:half]), lambda: select_from_list(selector - half, tensor_list[half:]))
</code>```

2- Using tf.case:

```<code>def select_from_list(selector, tensor_list):
    length = len(tensor_list)
    if length == 0:
        raise ValueError('List is empty')
    elif length == 1:
        return tensor_list[0]
    else:
        def fn(tensor):
            return lambda: tensor
        pred_fn_pairs = [(tf.less(selector, float(i+1)), fn(tensor)) for i, tensor in enumerate(tensor_list)]
        return tf.case(pred_fn_pairs, default=lambda:tensor_list[-1])
</code>```

You can test any of them using:

```<code>def test(selector, value_list, sess):
    return select_from_list(float(selector), [tf.constant(value) for value in value_list]).eval(session = sess)

sess = tf.Session()
test(3.5, [4,2,6,7,5], sess)
</code>```

This should return 7

ContentLicense: CC BY-SA 3.0

Title: Tensorflow: Random selection of masks

Body:
I know that this stackoverflow thread already gives some nice examples about conditionals in tensorflow, but I'm still struggling how to solve my issue of randomly selecting among several different masks in tensorflow.

Right now I can only select between two mask tensors a and b:

rand_num = tf.random_uniform([], minval=0, maxval=2.0, dtype=tf.float32, seed=None)
def if_true():
     return b
def if_false():
     return a
mask_sel = tf.cond(tf.less(rand_num , tf.constant(1.0)),if_true,if_false)

(I still find it weird that one needs to define these two helper functions, but not using them weirdly throws an error.)

Now the question: Lets say I have 4 mask tensors (a,b,c,d) or more to randomly select, what would be the best way to do that in tensorflow?

In python that would be

rand_num = np.random.uniform(low=0,high=4.0)
if (rand_num < 1.0):
    mask_sel = a
elif(rand_num < 2.0):
    mask_sel = b
elif(rand_num < 3.0):
    mask_sel = c
else
    mask_sel = d

Body:
About the helper functions, they are useful because they allow tensorflow to know which operations will run under each condition, this way it can optimize by running only the selected branch and ignoring the other. Operations outside the helper functions but used by any of them will always be run before tf.cond runs.

The other options is to use tf.select; you won't need the helper functions here but it will always evaluate both sides before running tf.select which can be inefficient if you don't need to.

Now for the main problem 'selecting from more than 2 tesnors', you can use multiple options:

1- Recursively nesting tf.cond operations:

def select_from_list(selector, tensor_list):
    length = len(tensor_list)
    if length == 0:
        raise ValueError('List is empty')
    elif length == 1:
        return tensor_list[0]
    else:
        half = length // 2
        return tf.cond(tf.less(selector, float(half)), lambda: select_from_list(selector, tensor_list[:half]), lambda: select_from_list(selector - half, tensor_list[half:]))

2- Using tf.case:

def select_from_list(selector, tensor_list):
    length = len(tensor_list)
    if length == 0:
        raise ValueError('List is empty')
    elif length == 1:
        return tensor_list[0]
    else:
        def fn(tensor):
            return lambda: tensor
        pred_fn_pairs = [(tf.less(selector, float(i+1)), fn(tensor)) for i, tensor in enumerate(tensor_list)]
        return tf.case(pred_fn_pairs, default=lambda:tensor_list[-1])

You can test any of them using:

def test(selector, value_list, sess):
    return select_from_list(float(selector), [tf.constant(value) for value in value_list]).eval(session = sess)

sess = tf.Session()
test(3.5, [4,2,6,7,5], sess)

This should return 7


问:
link to local disk
Is it possible to put a html link on a page that opens a file in local disk?

Like c:/myFolder/myfile.xls

This page is not actually going to be on web, but this feature would be needed for demostration purposes only. When the page is on web, the file is too, and link has url value.

答:
You could use

```<code><a href="c:/myFolder/myfile.xls">my link</a>
</code>```

Be wary that this may not work for all browsers (ie firefox) due to security reasons (See here) and it certainly wont work for other people accessing the webpage.

ContentLicense: CC BY-SA 2.5

Title: link to local disk

Body:
You could use

<a href="c:/myFolder/myfile.xls">my link</a>

Be wary that this may not work for all browsers (ie firefox) due to security reasons (See here) and it certainly wont work for other people accessing the webpage.


问:
Expected unqualified-id before unsigned in C++ struct
I'm trying to make a struct that resembles a DNS header, but I keep getting compile errors:

error: expected unqualified-id before ‘unsigned’

Here is the code:

```<code>#ifndef RAW_DNS_TYPES_H
#define RAW_DNS_TYPES_H

struct RawDNSHeader
{
    unsigned short int ID;
    unsigned int QR:1;
    unsigned int OPCode:4;
    unsigned int AA:1;
    unsigned int TC:1;
    unsigned int RD:1;
    unsigned int RA:1;
    unsigned int Z:3;
    unsigned int RCode:4;
    unsigned short int QDCount;
    unsigned short int ANCount;
    unsigned short int NSCount;
    unsigned short int ARCount;
};

struct RawDNSPacket
{
    RawDNSHeader header;
    unsigned char body[0];
};

#endif
</code>```

Edit:
I've added the entire source code as requested.

答: So I left my desk for 15 minutes, and when I returned, everything compiled fine. Given the resolution, I can't give many details on the cause of the issue I was having, but I suspect that it had to do with the files <code>#include</code>-ing this one as Barmar pointed out. </p>

Body:
I'm trying to make a struct that resembles a DNS header, but I keep getting compile errors:

error: expected unqualified-id before ‘unsigned’

Here is the code:

#ifndef RAW_DNS_TYPES_H
#define RAW_DNS_TYPES_H

struct RawDNSHeader
{
    unsigned short int ID;
    unsigned int QR:1;
    unsigned int OPCode:4;
    unsigned int AA:1;
    unsigned int TC:1;
    unsigned int RD:1;
    unsigned int RA:1;
    unsigned int Z:3;
    unsigned int RCode:4;
    unsigned short int QDCount;
    unsigned short int ANCount;
    unsigned short int NSCount;
    unsigned short int ARCount;
};

struct RawDNSPacket
{
    RawDNSHeader header;
    unsigned char body[0];
};

#endif

Edit:
I've added the entire source code as requested.

Body: So I left my desk for 15 minutes, and when I returned, everything compiled fine. Given the resolution, I can't give many details on the cause of the issue I was having, but I suspect that it had to do with the files #include-ing this one as Barmar pointed out.


问:
AngularJS Codeigniter http url last segment
My url is this http://localhost/fcm/Maps/create_deped_cm/1/1/1. When I use my https in angular the response would be a php page because the post url will be http://localhost/fcm/Maps/create_deped_cm/1/1/do_add_deped_cm. When I test and find the answer the post url should be http://localhost/fcm/Maps/do_add_deped_cm. How can I achieve this?

angularjs code:

```<code><script type="text/javascript">
angular.module('config', [])
.constant('appName','My Angular App!')
.constant('appVersion','0.3')
.constant('baseUrl','http://localhost/fcm/');

var app = angular.module("myCurriform_deped", ['config']);

   app.controller("standardCtrl", function($scope,$http,$filter,$location,$window,config) {
   .......................

   });
</code>```

答:
You need to defined a base url in your app's config file:

```<code>angular.module('myApp.config', [])
    .constant('appName','My Angular App!')
    .constant('appVersion','0.3')
    .constant('baseUrl','http://localhost/fcm/');
</code>```

Make sure your config is included in your module:

```<code>angular.module('myApp', ['myApp.config']);
</code>```

Then just append your url to the base and use that:

```<code>var url = config.baseUrl + 'Maps/do_add_cm_deped'
</code>```

That should do the trick.

app.js

```<code>angular
.module('config', []).constant('baseUrl','http://localhost/fcm/');

angular
.module('myCurriform_deped', ['config'])
.controller("standardCtrl", function($scope,$http,$filter,$location,$window,config) {
         $scope.submit_button = function(params) {
             // submit logic
             var url = config.baseUrl + 'Maps/do_add_cm_deped';
             var req = {
                 url: url,
                 // other properties
             }
         }
    });
</code>```

Body:
You need to defined a base url in your app's config file:

angular.module('myApp.config', [])
    .constant('appName','My Angular App!')
    .constant('appVersion','0.3')
    .constant('baseUrl','http://localhost/fcm/');

Make sure your config is included in your module:

angular.module('myApp', ['myApp.config']);

Then just append your url to the base and use that:

var url = config.baseUrl + 'Maps/do_add_cm_deped'

That should do the trick.

app.js

angular
.module('config', []).constant('baseUrl','http://localhost/fcm/');

angular
.module('myCurriform_deped', ['config'])
.controller("standardCtrl", function($scope,$http,$filter,$location,$window,config) {
         $scope.submit_button = function(params) {
             // submit logic
             var url = config.baseUrl + 'Maps/do_add_cm_deped';
             var req = {
                 url: url,
                 // other properties
             }
         }
    });


问:
NSXMLParser and the "£" symbol
Hey all, slight problem when i read in an XML form.
NSXMLParse correctly see's the "£" symbol but its prints out the unicode, \U00a3.

I am just reading it to a string.

```<code>   [pre_Currency appendString:[self cleanString:string]];
</code>```

CleanString removes \n - \t and i even added parsing out the unicode and replace it with the Char symbol for the "£".

Oddly enough a NSLog here print a "£" symbol, but when it didEndElement i add it to the dictionary,

```<code>    [number setObject:[self cleanString:pre_Currency] forKey:@"pre_currency"];
</code>```

It add it as a unicode Char.

Cant understand why, looking at google theres very little aimed at parsing unicode chars.

答:
I dont know but might be useful to you,if you use the stringByReplacingOccurrencesOfString method

```<code>NSString *specialChars=@"YOur string with special characters."

specialChars=[specialChars stringByReplacingOccurrencesOfString:@"\U00a3" withString:@"£"];
</code>```

Thanks

Title: NSXMLParser and the "£" symbol

Body:
Hey all, slight problem when i read in an XML form.
NSXMLParse correctly see's the "£" symbol but its prints out the unicode, \U00a3.

I am just reading it to a string.

   [pre_Currency appendString:[self cleanString:string]];

CleanString removes \n - \t and i even added parsing out the unicode and replace it with the Char symbol for the "£".

Oddly enough a NSLog here print a "£" symbol, but when it didEndElement i add it to the dictionary,

    [number setObject:[self cleanString:pre_Currency] forKey:@"pre_currency"];

It add it as a unicode Char.

Cant understand why, looking at google theres very little aimed at parsing unicode chars.

Body:
I dont know but might be useful to you,if you use the stringByReplacingOccurrencesOfString method

NSString *specialChars=@"YOur string with special characters."

specialChars=[specialChars stringByReplacingOccurrencesOfString:@"\U00a3" withString:@"£"];

Thanks


问:
How to create a wrapped / scrolling tiled area that is not slow?
Imagine a canvas that is tile filed both horizontally and vertically by using a single bitmap, for example:

The above is achieved with the following:

```<code>procedure TForm1.PaintBox1Paint(Sender: TObject);
var
  X, Y: Integer;
begin
  Y := 0;
  while Y < PaintBox1.Height do
  begin
    X := 0;
    while X < PaintBox1.Width do
    begin
      PaintBox1.Canvas.Draw(X, Y, Image1.Picture.Bitmap);
      Inc(X, Image1.Picture.Bitmap.Width);
    end;
    Inc(Y, Image1.Picture.Bitmap.Height);
  end;

  PaintBox1.Canvas.Brush.Style := bsClear;
  PaintBox1.Canvas.Rectangle(PaintBox1.ClientRect);
end;
</code>```

Now what I would like to do is extend the above to allow a horizontal and vertical offset to simulate the effect that the tiled images are been wrapped / scrolled when using a scrollbar etc.

The idea is that when changing the horizontal offset for example, the tiled images would move to the left, and from the right you should see the tiled images appear as if they have been wrapped around from one side of the paintbox to the other.

I have managed to make a test project that does work how I want it to and it looks like this:

I have written this test project in Lazarus but it can be easily adapted to test in Delphi.

Below is the lfm:

```<code>object Form1: TForm1
  Left = 0
  Height = 625
  Top = 0
  Width = 782
  Caption = 'Form1'
  ClientHeight = 625
  ClientWidth = 782
  OnCreate = FormCreate
  Position = poScreenCenter
  Visible = False
  object Label1: TLabel
    Left = 25
    Height = 15
    Top = 16
    Width = 40
    Caption = 'Regular'
    ParentColor = False
  end
  object Label2: TLabel
    Left = 361
    Height = 15
    Top = 16
    Width = 32
    Caption = 'Offset'
    ParentColor = False
  end
  object PaintBox1: TPaintBox
    Left = 24
    Height = 320
    Top = 40
    Width = 320
    OnPaint = PaintBox1Paint
  end
  object PaintBox2: TPaintBox
    Left = 361
    Height = 320
    Top = 40
    Width = 320
    OnPaint = PaintBox2Paint
  end
  object Image1: TImage
    Left = 25
    Height = 48
    Top = 544
    Width = 48
    AutoSize = True
    Picture.Data = {
[encoded data, 5438 characters]
    }
    Visible = False
  end
  object Label3: TLabel
    Left = 645
    Height = 15
    Top = 376
    Width = 36
    Alignment = taRightJustify
    AutoSize = False
    Caption = '0'
    ParentColor = False
  end
  object ScrollBar1: TScrollBar
    Left = 361
    Height = 17
    Top = 374
    Width = 273
    Max = 5000
    PageSize = 0
    TabOrder = 0
    OnChange = ScrollBar1Change
  end
  object ScrollBar2: TScrollBar
    Left = 696
    Height = 320
    Top = 40
    Width = 17
    Kind = sbVertical
    Max = 5000
    PageSize = 0
    TabOrder = 1
    OnChange = ScrollBar2Change
  end
  object Label4: TLabel
    Left = 720
    Height = 15
    Top = 40
    Width = 34
    Caption = 'Label4'
    ParentColor = False
  end
end
</code>```

and the source

```<code>unit Unit1;

{$mode delphi}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
  ExtCtrls;

{ TForm1 }

type
  TForm1 = class(TForm)
    Image1: TImage;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    PaintBox1: TPaintBox;
    PaintBox2: TPaintBox;
    ScrollBar1: TScrollBar;
    ScrollBar2: TScrollBar;
    procedure FormCreate(Sender: TObject);
    procedure PaintBox1Paint(Sender: TObject);
    procedure PaintBox2Paint(Sender: TObject);
    procedure ScrollBar1Change(Sender: TObject);
    procedure ScrollBar2Change(Sender: TObject);
  private
    FOffsetX: Integer;
    FOffsetY: Integer;
  public
    { public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
begin
  FOffsetX := 0;
  FOffsetY := 0;
end;

procedure TForm1.PaintBox1Paint(Sender: TObject);
var
  X, Y: Integer;
begin
  Y := 0;
  while Y < PaintBox1.Height do
  begin
    X := 0;
    while X < PaintBox1.Width do
    begin
      PaintBox1.Canvas.Draw(X, Y, Image1.Picture.Bitmap);
      Inc(X, Image1.Picture.Bitmap.Width);
    end;
    Inc(Y, Image1.Picture.Bitmap.Height);
  end;

  PaintBox1.Canvas.Brush.Style := bsClear;
  PaintBox1.Canvas.Rectangle(PaintBox1.ClientRect);
end;

// needs improvement
procedure TForm1.PaintBox2Paint(Sender: TObject);
var
  X, Y: Integer;
begin
  Y := -FOffsetY;
  while Y < PaintBox2.Height do
  begin
    X := -FOffsetX;
    while X < PaintBox2.Width do
    begin
      PaintBox2.Canvas.Draw(X, Y, Image1.Picture.Bitmap);
      Inc(X, Image1.Picture.Bitmap.Width);
    end;
    Inc(Y, Image1.Picture.Bitmap.Height);
  end;

  PaintBox2.Canvas.Brush.Style := bsClear;
  PaintBox2.Canvas.Rectangle(PaintBox2.ClientRect);
end;

procedure TForm1.ScrollBar1Change(Sender: TObject);
begin
  FOffsetX := ScrollBar1.Position;
  Label3.Caption := IntToStr(FOffsetX);
  PaintBox2.Invalidate;
end;

procedure TForm1.ScrollBar2Change(Sender: TObject);
begin
  FOffsetY := ScrollBar2.Position;
  Label4.Caption := IntToStr(FOffsetY);
  PaintBox2.Invalidate;
end;

end.
</code>```

My question is how can I improve my existing code and whether or not there is a better way of doing this, I may have over complicated the task?

For small offsets the paintbox paints quite fast but with larger offsets such as 5000 (what I am currently testing with) the scrolling becomes rather slow and I wonder if I have missed out something obvious?

答:
There is no need to draw all of the bitmaps that are not visible.  For any given width/height of bitmap (let's call it the "tile"), you only need to start/finish drawing at most 1 tile width or height beyond the edge of your canvas.

i.e. calculate the first visible tile and starting painting with that.

The illustration above tries to show what I mean... only the green tiles are in the visible area (shaded blue) so even if the offset includes those that are shown red, there is no point painting them.

Windows (the OS) will clip these anyway, but you are still spending time iterating over those not-visible tiles, which is why your larger offsets result in degraded performance... you are spending time counting up through the "invisible" space, before reaching the tiles that you actually need to paint.

Calculating the "origin" at which to start painting is simple arithmetic and doesn't require loop iterations.  Instead of initialising Y and X to your absolute offsets, set them to the first multiple of the height/width of the tile from that offset, using a simple mod operation:

```<code>Y := -FOffsetY mod Image1.Height;

X := -FOffseXY mod Image1.Width;
</code>```

Or similar

Jerry's observation w.r.t using an offscreen bitmap and then blitting into your control will also optimise the actual painting.

Body:
Imagine a canvas that is tile filed both horizontally and vertically by using a single bitmap, for example:

The above is achieved with the following:

procedure TForm1.PaintBox1Paint(Sender: TObject);
var
  X, Y: Integer;
begin
  Y := 0;
  while Y < PaintBox1.Height do
  begin
    X := 0;
    while X < PaintBox1.Width do
    begin
      PaintBox1.Canvas.Draw(X, Y, Image1.Picture.Bitmap);
      Inc(X, Image1.Picture.Bitmap.Width);
    end;
    Inc(Y, Image1.Picture.Bitmap.Height);
  end;

  PaintBox1.Canvas.Brush.Style := bsClear;
  PaintBox1.Canvas.Rectangle(PaintBox1.ClientRect);
end;

Now what I would like to do is extend the above to allow a horizontal and vertical offset to simulate the effect that the tiled images are been wrapped / scrolled when using a scrollbar etc.

The idea is that when changing the horizontal offset for example, the tiled images would move to the left, and from the right you should see the tiled images appear as if they have been wrapped around from one side of the paintbox to the other.

I have managed to make a test project that does work how I want it to and it looks like this:

I have written this test project in Lazarus but it can be easily adapted to test in Delphi.

Below is the lfm:

object Form1: TForm1
  Left = 0
  Height = 625
  Top = 0
  Width = 782
  Caption = 'Form1'
  ClientHeight = 625
  ClientWidth = 782
  OnCreate = FormCreate
  Position = poScreenCenter
  Visible = False
  object Label1: TLabel
    Left = 25
    Height = 15
    Top = 16
    Width = 40
    Caption = 'Regular'
    ParentColor = False
  end
  object Label2: TLabel
    Left = 361
    Height = 15
    Top = 16
    Width = 32
    Caption = 'Offset'
    ParentColor = False
  end
  object PaintBox1: TPaintBox
    Left = 24
    Height = 320
    Top = 40
    Width = 320
    OnPaint = PaintBox1Paint
  end
  object PaintBox2: TPaintBox
    Left = 361
    Height = 320
    Top = 40
    Width = 320
    OnPaint = PaintBox2Paint
  end
  object Image1: TImage
    Left = 25
    Height = 48
    Top = 544
    Width = 48
    AutoSize = True
    Picture.Data = {
[encoded data, 5438 characters]
    }
    Visible = False
  end
  object Label3: TLabel
    Left = 645
    Height = 15
    Top = 376
    Width = 36
    Alignment = taRightJustify
    AutoSize = False
    Caption = '0'
    ParentColor = False
  end
  object ScrollBar1: TScrollBar
    Left = 361
    Height = 17
    Top = 374
    Width = 273
    Max = 5000
    PageSize = 0
    TabOrder = 0
    OnChange = ScrollBar1Change
  end
  object ScrollBar2: TScrollBar
    Left = 696
    Height = 320
    Top = 40
    Width = 17
    Kind = sbVertical
    Max = 5000
    PageSize = 0
    TabOrder = 1
    OnChange = ScrollBar2Change
  end
  object Label4: TLabel
    Left = 720
    Height = 15
    Top = 40
    Width = 34
    Caption = 'Label4'
    ParentColor = False
  end
end

and the source

unit Unit1;

{$mode delphi}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
  ExtCtrls;

{ TForm1 }

type
  TForm1 = class(TForm)
    Image1: TImage;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    PaintBox1: TPaintBox;
    PaintBox2: TPaintBox;
    ScrollBar1: TScrollBar;
    ScrollBar2: TScrollBar;
    procedure FormCreate(Sender: TObject);
    procedure PaintBox1Paint(Sender: TObject);
    procedure PaintBox2Paint(Sender: TObject);
    procedure ScrollBar1Change(Sender: TObject);
    procedure ScrollBar2Change(Sender: TObject);
  private
    FOffsetX: Integer;
    FOffsetY: Integer;
  public
    { public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
begin
  FOffsetX := 0;
  FOffsetY := 0;
end;

procedure TForm1.PaintBox1Paint(Sender: TObject);
var
  X, Y: Integer;
begin
  Y := 0;
  while Y < PaintBox1.Height do
  begin
    X := 0;
    while X < PaintBox1.Width do
    begin
      PaintBox1.Canvas.Draw(X, Y, Image1.Picture.Bitmap);
      Inc(X, Image1.Picture.Bitmap.Width);
    end;
    Inc(Y, Image1.Picture.Bitmap.Height);
  end;

  PaintBox1.Canvas.Brush.Style := bsClear;
  PaintBox1.Canvas.Rectangle(PaintBox1.ClientRect);
end;

// needs improvement
procedure TForm1.PaintBox2Paint(Sender: TObject);
var
  X, Y: Integer;
begin
  Y := -FOffsetY;
  while Y < PaintBox2.Height do
  begin
    X := -FOffsetX;
    while X < PaintBox2.Width do
    begin
      PaintBox2.Canvas.Draw(X, Y, Image1.Picture.Bitmap);
      Inc(X, Image1.Picture.Bitmap.Width);
    end;
    Inc(Y, Image1.Picture.Bitmap.Height);
  end;

  PaintBox2.Canvas.Brush.Style := bsClear;
  PaintBox2.Canvas.Rectangle(PaintBox2.ClientRect);
end;

procedure TForm1.ScrollBar1Change(Sender: TObject);
begin
  FOffsetX := ScrollBar1.Position;
  Label3.Caption := IntToStr(FOffsetX);
  PaintBox2.Invalidate;
end;

procedure TForm1.ScrollBar2Change(Sender: TObject);
begin
  FOffsetY := ScrollBar2.Position;
  Label4.Caption := IntToStr(FOffsetY);
  PaintBox2.Invalidate;
end;

end.

My question is how can I improve my existing code and whether or not there is a better way of doing this, I may have over complicated the task?

For small offsets the paintbox paints quite fast but with larger offsets such as 5000 (what I am currently testing with) the scrolling becomes rather slow and I wonder if I have missed out something obvious?

Body:
There is no need to draw all of the bitmaps that are not visible.  For any given width/height of bitmap (let's call it the "tile"), you only need to start/finish drawing at most 1 tile width or height beyond the edge of your canvas.

i.e. calculate the first visible tile and starting painting with that.

The illustration above tries to show what I mean... only the green tiles are in the visible area (shaded blue) so even if the offset includes those that are shown red, there is no point painting them.

Windows (the OS) will clip these anyway, but you are still spending time iterating over those not-visible tiles, which is why your larger offsets result in degraded performance... you are spending time counting up through the "invisible" space, before reaching the tiles that you actually need to paint.

Calculating the "origin" at which to start painting is simple arithmetic and doesn't require loop iterations.  Instead of initialising Y and X to your absolute offsets, set them to the first multiple of the height/width of the tile from that offset, using a simple mod operation:

Y := -FOffsetY mod Image1.Height;

X := -FOffseXY mod Image1.Width;

Or similar

Jerry's observation w.r.t using an offscreen bitmap and then blitting into your control will also optimise the actual painting.


问:
How to disable pane switching with ESC in Tmux
I noticed that esc will also start listening for instructions to switch panes. I'm new to Tmux, I copied a Tmux conf file earlier today which should only have enabled alt to switch panes, so I'm not sure if this conf file enabled it or if it's standard in Tmux 2.3.

Seeing as I tend to start moving around after entering normal mode, this annoys the hell out of me. Can anyone tell me how to disable pane switching with esc?

答:
I think your ~/.tmux.conf file contains lines like below:

```<code>bind -n M-h select-pane -L
bind -n M-j select-pane -D
bind -n M-k select-pane -U
bind -n M-l select-pane -R
</code>```

These lines bind Alt-h(j,k,l) to switch pane without need of prefix key.
But it seems that ESC+h(j,k,l) will also trigger the Alt-h(j,k,l). I don't know why either.

My way to fix it:

Make sure you have closed the tmux session. ( use "prefix+&+y" to kill all window)

Change the key binding above in .tmux.conf to the new one below:

bind -n C-j select-pane -D \; display-panes

bind -n C-k select-pane -U \; display-panes

bind -n C-h select-pane -L \; display-panes

bind -n C-l select-pane -R \; display-panes

Restart your tmux. This will remove your previous M-(h,j,k,l) binding, and the new binding will take effect.

The meaning of the new binding is to: Use Ctrl-vim keys without prefix key to switch pane, and at the same time, show the pane indicator: the current active pane index's color will be red.

Body:
I think your ~/.tmux.conf file contains lines like below:

bind -n M-h select-pane -L
bind -n M-j select-pane -D
bind -n M-k select-pane -U
bind -n M-l select-pane -R

These lines bind Alt-h(j,k,l) to switch pane without need of prefix key.
But it seems that ESC+h(j,k,l) will also trigger the Alt-h(j,k,l). I don't know why either.

My way to fix it:

Make sure you have closed the tmux session. ( use "prefix+&+y" to kill all window)

Change the key binding above in .tmux.conf to the new one below:

bind -n C-j select-pane -D \; display-panes

bind -n C-k select-pane -U \; display-panes

bind -n C-h select-pane -L \; display-panes

bind -n C-l select-pane -R \; display-panes

Restart your tmux. This will remove your previous M-(h,j,k,l) binding, and the new binding will take effect.

The meaning of the new binding is to: Use Ctrl-vim keys without prefix key to switch pane, and at the same time, show the pane indicator: the current active pane index's color will be red.


问:
Foundation 6 - Rows alignement in flex box
I'm trying to center two div Horizontally, and align one at the Middle of the parent container, and the second one at the Bottom of the parent container. I'm using Foundation 6, with the Flexbox version.

Html

```<code><section id="hero">
    <div class="row align-middle align-center">
        <h1>Welcome</h1>
    </div>
    <div class="row align-bottom align-center">
        <p>Some text</p>
    </div>
</section>
</code>```

Css

```<code>#hero {
    height: 100vh;
    display: flex;
    flex-wrap: wrap;
}
</code>```

The problem is that every div in the flex container (#hero) appear on the same line.

Thank's for helping !

答:
I finally found how to align vertically 3 divs using a Flexbox. Foundation wasn't really in the problem.

I made a Js Fiddle for those who have the same question:

.wrapper {
    display: flex;
    flex-direction: column;
    height:90vh;
}
.center {
    width: 100%;
    flex-grow: 1;
    align-items: center;
    display:flex;
}
.a {
    width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="wrapper">
        <div class="a">Header</div>
        <div class="center">Body</div>
        <div class="a">Footer</div>
</div>
    </code>```

JSFiddle: https://jsfiddle.net/ek38ff5r/20/

Body:
I'm trying to center two div Horizontally, and align one at the Middle of the parent container, and the second one at the Bottom of the parent container. I'm using Foundation 6, with the Flexbox version.

Html

Welcome

Some text

Css

#hero {
    height: 100vh;
    display: flex;
    flex-wrap: wrap;
}

The problem is that every div in the flex container (#hero) appear on the same line.

Thank's for helping !

Body:
I finally found how to align vertically 3 divs using a Flexbox. Foundation wasn't really in the problem.

I made a Js Fiddle for those who have the same question:

.wrapper {
    display: flex;
    flex-direction: column;
    height:90vh;
}
.center {
    width: 100%;
    flex-grow: 1;
    align-items: center;
    display:flex;
}
.a {
    width: 100%;
}

 <div class="wrapper">
        <div class="a">Header</div>
        <div class="center">Body</div>
        <div class="a">Footer</div>
</div>

JSFiddle: https://jsfiddle.net/ek38ff5r/20/


问:
How does Spark handle exceptions for a spark streaming job?
This question might seem pretty large as is, however I have two specific situations which are better put together than separately. To start with, I'm reading data from Kafka into a dstream using the spark-streaming-kafka API. Assume I have one of the following two situations:

// something goes wrong on the driver
dstream.transform { rdd =>
  throw new Exception
}

// something goes wrong on the executors
dstream.transform { rdd =>
  rdd.foreachPartition { partition =>
    throw new Exception
  }
}
```

<p>This typically describes some situation that might occur in which I need to stop the application - an exception is thrown either on the driver or on one of the executors (e.g. failing to reach some external service which is crucial for the processing). If you try this locally, it the app fails immediately. A bit more code:</p>

<pre class="lang-scala prettyprint-override"><code>dstream.foreachRDD { rdd =>
  // write rdd data to some output
  // update the kafka offsets
}
</code>```

This is the last thing that happens in my app - push the data into Kafka and then making sure to move the offsets in Kafka to avoid re-processing.

Other notes:

I'm running Spark 2.0.1 on top of Mesos with Marathon

checkpointing and write ahead logs are disabled

I'm expecting the application to shutdown in case an exception is thrown (just as if I was running it locally) because I need a fail-fast behavior. Now what happens at times is that after an exception occurs the app still appears as running in Marathon; even worse, the Spark UI can still be accessed in some situations although nothing is processed anymore.

What might be the reason for this?

答: Your examples only show transformations. With Spark only actions throw exceptions because they lazily execute the transformations. I would guess any attempt to write your results somewhere will end up failing fast.

ContentLicense: CC BY-SA 4.0

Body:
This question might seem pretty large as is, however I have two specific situations which are better put together than separately. To start with, I'm reading data from Kafka into a dstream using the spark-streaming-kafka API. Assume I have one of the following two situations:

// something goes wrong on the driver
dstream.transform { rdd =>
  throw new Exception
}

// something goes wrong on the executors
dstream.transform { rdd =>
  rdd.foreachPartition { partition =>
    throw new Exception
  }
}

This typically describes some situation that might occur in which I need to stop the application - an exception is thrown either on the driver or on one of the executors (e.g. failing to reach some external service which is crucial for the processing). If you try this locally, it the app fails immediately. A bit more code:

dstream.foreachRDD { rdd =>
  // write rdd data to some output
  // update the kafka offsets
}

This is the last thing that happens in my app - push the data into Kafka and then making sure to move the offsets in Kafka to avoid re-processing.

Other notes:

I'm running Spark 2.0.1 on top of Mesos with Marathon

checkpointing and write ahead logs are disabled

I'm expecting the application to shutdown in case an exception is thrown (just as if I was running it locally) because I need a fail-fast behavior. Now what happens at times is that after an exception occurs the app still appears as running in Marathon; even worse, the Spark UI can still be accessed in some situations although nothing is processed anymore.

What might be the reason for this?


问:
Trying to show image HTML using database
I am trying to create an animal's database, for an animal shelter. So far, what I have is a set of tables with the animal's species and when the user chooses the species it shows all animals available. Now I want the user to click on the animal chosen and more details about that animal, such has, location, gender, size, will show. Problem is, I know very little about Javascript/ HTML and I am encountering lots of issues. One of them is showing the image in this third screen of more details. What I have so far with HTML is:

```<code><div class="row" style="text-align: center">
<img src="foto_animal" height="180">
</div>
</code>```

"foto_animal" is the column in table "Animal" that holds the Image URL. Is there anything I should change with Javascript or is it just a HTML problem? Thanks in advance.

EDIT

I manage to get the URL, this is the script.js file

```<code>var populateContact = function(data) {
$('#contact_photo').text(data.foto_animal);
</code>```

This is the index.html

```<code><h2><span id="contact_photo"></h2>
</code>```

It shows the URL, but now I want it to be recognize as an image.

答:
EDIT : To have your users download the  as requested i nthe comments, try adding a  tag and setting it's download property.

Here is an example.

Via html, when referencing an image in src property of the  tag, add the file extension of your image file

assuming your foto_animal is a jpeg file and in the same location with the html files,

Via javascript,
You simply call the element using document.getElementByID and set the .src property

document.getElementById("myImg").src = "foto_animal.jpg";

Via jquery,
Simply use the .attr property to set src of your  tag ID

$("#myImg").attr('src', 'foto_animal.jpg');

Body:
I am trying to create an animal's database, for an animal shelter. So far, what I have is a set of tables with the animal's species and when the user chooses the species it shows all animals available. Now I want the user to click on the animal chosen and more details about that animal, such has, location, gender, size, will show. Problem is, I know very little about Javascript/ HTML and I am encountering lots of issues. One of them is showing the image in this third screen of more details. What I have so far with HTML is:

"foto_animal" is the column in table "Animal" that holds the Image URL. Is there anything I should change with Javascript or is it just a HTML problem? Thanks in advance.

EDIT

I manage to get the URL, this is the script.js file

var populateContact = function(data) {
$('#contact_photo').text(data.foto_animal);

This is the index.html

It shows the URL, but now I want it to be recognize as an image.

Body:
EDIT : To have your users download the  as requested i nthe comments, try adding a  tag and setting it's download property.

Here is an example.

Via html, when referencing an image in src property of the <img> tag, add the file extension of your image file

assuming your foto_animal is a jpeg file and in the same location with the html files,

<img id='myImg' src="foto_animal.jpg" height=180px>

Via javascript,
You simply call the element using document.getElementByID and set the .src property

document.getElementById("myImg").src = "foto_animal.jpg";

Via jquery,
Simply use the .attr property to set src of your  tag ID

$("#myImg").attr('src', 'foto_animal.jpg');


问:
Access vm local website without dns
I have a windows server 2012 vm (from azure) with a web node.js app running on it in port 3000.

I want to access that website from my computer, how can I do that?

答:
What should I type in the url

we can type in the URL with Public IP address, like http://publicipaddress:3000

Also we can set FQDN for this VM, so we can type in the URL with FQDN, like http://jasontest321.eastus.cloudapp.azure.com:3000

We can set FQDN in the public IP address via azure portal.

Title: Access vm local website without dns


问:
What is the algorithm unix du command uses to calculate disk space?
I've tried using du to calculate disk usage today on a single directory. The size of directory is 6GB and it took the following amount of time to calculate:

```<code>prompt> time du -sh .
6.0G   .

real    1m32.405s
user    0m2.053s
sys     0m16.552s
</code>```

What is the algorithm unix du command uses to calculate disk space? Why is it so slow? Are there any alternatives to calculate disk space more efficiently? The platform of invocation is Sun. The directory for which size was calculated is NFS mounted.

答: I think it just recursively walks the directory, while adding together the sizes of the files found. Quite simple, really, but of course it takes time. It might be faster if the file system makes these operations quicker.</p>

Body:
I've tried using du to calculate disk usage today on a single directory. The size of directory is 6GB and it took the following amount of time to calculate:

prompt> time du -sh .
6.0G   .

real    1m32.405s
user    0m2.053s
sys     0m16.552s

What is the algorithm unix du command uses to calculate disk space? Why is it so slow? Are there any alternatives to calculate disk space more efficiently? The platform of invocation is Sun. The directory for which size was calculated is NFS mounted.


问:
How do languages execute main method?
I am creating my own programming language for a project and am implementing a scanner, parser, and semantic analyzer. I am wanting this language to be similar to Java or C++ in that they have a method named main that is executed. My grammar allows for a program to consist of 1 or more methods (ideally, the one method would be named main), but the syntax just looks for an identifier as the method name. Since main is not a reserved word in Java or C++, how are they able to enforce having a method named main? Having a program without a main method (besides class files or interfaces, where they typically don't) is an error. Is that something that is done in the Semantic analysis portion? Or would that take place later in the linker/loader?

Something else I have always wondered about is how the main method executes first. I know when I write a program that has, for example, 5 methods (one of them being main) that when I run the program, the one that gets executed at the start is main. This is one of those things that I was taught and accepted, and it makes sense as to why that's the case. But, how does the compiler know to execute that particular method from the other ones?

答:
Your main ISN'T executed first - there's going to be some boilerplate startup code, that sets up the environment needed for your program to run (initializing global variables, for example).  After the compiler is finished, the linker will be called, specifying this startup file as the very first object file (prior to the object files the compiler generated from your source files).  The startup code gets executed first solely because of this distinguished position in the final executable file; the last thing it will do is call your main.  Part of the linker's job is to resolve this reference to the actual function/method named main, wherever it might be among the object files.

Lack of a main is not a syntax error - it might be defined in a different source file than the one you're currently compiling, after all.  The error would actually result from the linker's inability to resolve that reference from the startup code.

(Please note that I am speaking in extremely general terms, about a whole family of compiled programming languages.  Details will differ between different languages, different implementations of the same language, and between platforms.)

Title: How do languages execute main method?


问:
iOS - Adding a 2D image to a scenekit game
Hello i can't for the life of me work out how to add a 2D image in the scene using scenekit is it even possible? What I'm trying to accomplish is have a 3D flying plane over a 2D background image but the background image can't cover the whole screen. Thanks to anyone that can help</p>

答:
Others have said plenty good suggestions above.

Let me summarize each solution with different scenarios:

Using scnScene.background: Easiest, but fullscreen and static. You cannot display in a smaller area of the scene, nor can you customize the transformations.

Using scnScene.overlaySKScene to display a 2D SKScene and adding image sprite. This is probably what fits your scenario. If you want static but with configurable transformations, this is a good choice. Notably overlaySKScene is recommended by Apple to create HUD in your 3D scene.

However, if you want the 2D content to track the 3D movement, you need to do some coordinate conversion from 3D space to 2D space every frame. Bad news is the job is done by CPU, which will add performance drag. (Believe me, this frustrate me too!)

Using SCNNode with SCNPlane geometry and set the diffuse.content with the image; add SCNBillBoardConstraint to the node to ensure it's always facing the camera.

Most flexible. However if your camera is not orthographic, the picture is going to zoom as the fov of camera changes, which doesn't look 2D but rather a hanging 3D billboard.


问:
Why Ruby inject method cannot sum up string lengths without initial value?
Why the following code issues an error ?

```<code>['hello','stack','overflow'].inject{|memo,s|memo+s.length}

TypeError: can't convert Fixnum into String
        from (irb):2:in `+'
        from (irb):2:in `block in irb_binding'
        from (irb):2:in `each'
        from (irb):2:in `inject'
        from (irb):2
</code>```

If the initial value is passed, it works OK:

```<code>['hello','stack','overflow'].inject(0){|memo,s|memo+s.length}
=> 18
</code>```

答:
Without the initial value, inject uses the first element in the collection as the initial value.

see ruby-doc.

Body:
Why the following code issues an error ?

['hello','stack','overflow'].inject{|memo,s|memo+s.length}

TypeError: can't convert Fixnum into String
        from (irb):2:in `+'
        from (irb):2:in `block in irb_binding'
        from (irb):2:in `each'
        from (irb):2:in `inject'
        from (irb):2

If the initial value is passed, it works OK:

['hello','stack','overflow'].inject(0){|memo,s|memo+s.length}
=> 18


问:
Select top N elements of related objects
I have a class Product to hold a specific instance of a given product.
This class has a list of related products that are similar to main product.

```<code>class Product
{
    public string Name;
    public double Rating;
    public List<Product> RelatedProducts;
    //...
    public List<Product> GetTopRelatedProducts(int N)
    {
        // How to implement this method
        // What I did so far(Bad code)
        //     1- INFINITE RECURSION
        //     2- Can not remember visited objects
        var myList = new List<Product>();
        foreach(Product prod in RelatedProducts)
        {
             myList.AddRange(prod.GetTopRelatedProducts(N));
        }
        return myList.Distinct().OrderByDescending(x => x.Rating).Take(N).ToList();
    }
}
</code>```

I want to define a method within Product class to get top N (best rated) related products. This method should take into consideration that elements in RelatedProducts list are of type Product and they also have their own RelatedProducts list. So I should keep navigating nested object until all related products were reached and after that, take the top N product.
I mean, the solution would not be simply this.RelatedProducts.OrderByDescending(x => x.Rating).Take(N);

One more thing to keep in mind: Two products can be mutually related. Which means a product A can belong to RelatedProducts list of a product B and B also can belong to RelatedProducts list of product A.

Any suggestion how to solve this issue in optimal way?

Imagine, I have millions of products to maintain. How can I navigate all related products recursively and recognize already visited ones?

I tagged this as both C# and Java, as the same logic could be applied to both languages

答:
My solution :

```<code>public List<Product> GetTopRelatedProducts(int N)
{
     List<Product> visitedProducts = new List<Product>();
     Queue<Product> ProductsQueue = new Queue<Product>();
     visitedProducts.add(this);
     foreach (product prod in relatedProducts)
         if(prod != this) //if a product can't be related to itself then remove this if statement
             ProductsQueue.Enqueue(prod);

     //for now visitedproducts contains only our main product and ProductsQueue contains the product related to it.

     while (ProductsQueue.count > 0)
     {
          Product p = ProductsQueue.Dequeue();
          visitedProducts.add(p);
          foreach (product prod in p.relatedProducts)
          {
              if( ! visitedProduct.contains(prod) && !ProductsQueue.contains(prod))//if we haven't visited the product already or if it is not in the queue so we are going to visit it.
                  ProductsQueue.Enqueue(prod);
          }

     }
     //now visitedProducts contains all the products that are related (somehow :P) to your first product

     visitedProducts.remove(this);// to remove the main product from the results
     //all what is left to do is to take the top N products.
     return visitedProducts.OrderByDescending(x => x.Rating).Take(N).ToList();
}
</code>```

I tried to make it as simple as possible ;)

Body:
I have a class Product to hold a specific instance of a given product.
This class has a list of related products that are similar to main product.

class Product
{
    public string Name;
    public double Rating;
    public List<Product> RelatedProducts;
    //...
    public List<Product> GetTopRelatedProducts(int N)
    {
        // How to implement this method
        // What I did so far(Bad code)
        //     1- INFINITE RECURSION
        //     2- Can not remember visited objects
        var myList = new List<Product>();
        foreach(Product prod in RelatedProducts)
        {
             myList.AddRange(prod.GetTopRelatedProducts(N));
        }
        return myList.Distinct().OrderByDescending(x => x.Rating).Take(N).ToList();
    }
}

I want to define a method within Product class to get top N (best rated) related products. This method should take into consideration that elements in RelatedProducts list are of type Product and they also have their own RelatedProducts list. So I should keep navigating nested object until all related products were reached and after that, take the top N product.
I mean, the solution would not be simply this.RelatedProducts.OrderByDescending(x => x.Rating).Take(N);

One more thing to keep in mind: Two products can be mutually related. Which means a product A can belong to RelatedProducts list of a product B and B also can belong to RelatedProducts list of product A.

Any suggestion how to solve this issue in optimal way?

Imagine, I have millions of products to maintain. How can I navigate all related products recursively and recognize already visited ones?

I tagged this as both C# and Java, as the same logic could be applied to both languages

Body:
My solution :

public List<Product> GetTopRelatedProducts(int N)
{
     List<Product> visitedProducts = new List<Product>();
     Queue<Product> ProductsQueue = new Queue<Product>();
     visitedProducts.add(this);
     foreach (product prod in relatedProducts)
         if(prod != this) //if a product can't be related to itself then remove this if statement
             ProductsQueue.Enqueue(prod);

     //for now visitedproducts contains only our main product and ProductsQueue contains the product related to it.

     while (ProductsQueue.count > 0)
     {
          Product p = ProductsQueue.Dequeue();
          visitedProducts.add(p);
          foreach (product prod in p.relatedProducts)
          {
              if( ! visitedProduct.contains(prod) && !ProductsQueue.contains(prod))//if we haven't visited the product already or if it is not in the queue so we are going to visit it.
                  ProductsQueue.Enqueue(prod);
          }

     }
     //now visitedProducts contains all the products that are related (somehow :P) to your first product

     visitedProducts.remove(this);// to remove the main product from the results
     //all what is left to do is to take the top N products.
     return visitedProducts.OrderByDescending(x => x.Rating).Take(N).ToList();
}

I tried to make it as simple as possible ;)


问:
How to properly implement/inherit a ComboBox.ObjectCollection class for design-time usage?

SCENARIO

I subclassed the ComboBox class to design a kind of ComboBox control on which I can supply a custom type (MyItem) to its ComboBox.Items collection...

This is the subclassed ComboBox class:

```<code><DesignerCategory("UserControl")>
Public Class MyComboBox : Inherits ComboBox

    <Editor(GetType(CollectionEditor), GetType(UITypeEditor))>
    <DesignerSerializationVisibility(DesignerSerializationVisibility.Content)>
    Public Shadows ReadOnly Property Items As MyItemCollection

    <DebuggerStepThrough>
    Public Sub New()
        MyBase.DrawMode = DrawMode.OwnerDrawFixed
        Me.Items = New MyItemCollection(owner:=Me)
    End Sub

    Protected Overrides Sub OnDrawItem(ByVal e As DrawItemEventArgs)

        e.DrawBackground()
        e.DrawFocusRectangle()

        ' Check if it is an item from the Items collection.
        If (e.Index < 0) Then
            ' not an item, draw the text.
            Using brush As New SolidBrush(e.ForeColor)
                e.Graphics.DrawString(Me.Text, e.Font, brush, e.Bounds.Left, e.Bounds.Top)
            End Using

        Else
            ' Get the item to draw.
            Dim item As MyItem = Me.Items(e.Index)
            Using brush As New SolidBrush(e.ForeColor)
                e.Graphics.DrawString(item.Text, e.Font, brush, e.Bounds.Left, e.Bounds.Top)
            End Using

        End If

        MyBase.OnDrawItem(e)

    End Sub

End Class
</code>```

This is the subclassed ComboBox.ObjectCollection class:

```<code><ListBindable(False)>
<DefaultMember("Item")>
Public Class MyItemCollection : Inherits ObjectCollection

    Sub New(ByVal owner As MyComboBox)
        MyBase.New(owner)
    End Sub

    <Browsable(False)>
    <DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
    Default Public Overloads Property Item(ByVal index As Integer) As MyItem
        Get
            Return DirectCast(MyBase.Item(index), MyItem)
        End Get
        Set(ByVal value As MyItem)
            MyBase.Item(index) = value
        End Set
    End Property

    ' Original property:
    '
    '<Browsable(False)>
    '<DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
    'Default Public Overrides Property Item(ByVal index As Integer) As Object
    '    Get
    '        Return MyBase.Item(index)
    '    End Get
    '    Set(value As Object)
    '        MyBase.Item(index) = value
    '    End Set
    'End Property

End Class
</code>```

And finally this is the custom type MyItem that I will use for the Items collection of my control:

```<code>Public NotInheritable Class MyItem

    Public Property Text As String

    Public Sub New()
        Me.New(String.Empty)
    End Sub

    Public Sub New(ByVal text As String)
        Me.Text = text
    End Sub

End Class
</code>```

All this works fine at execution time, I can add items and it works as expected, the problem is that it won't work at design time...

PROBLEM

When I try to add an item at design time like this:

...At first sight it seems it works, because I can add the item.

And the record seems properly auto-generated by Visual Studio in the Form's dsigner class (Form1.Designer.vb):

```<code>Private Sub InitializeComponent()
    Me.MyComboBox1 = New MyComboBox()
    Dim MyItem1 As MyItem = New MyItem()
    MyItem1.Text = "Test"
    Me.MyComboBox1.Items.AddRange(New Object() {MyItem1})

    ' ...
End Sub
</code>```

Even more, If I try to determine at execution time the current amount of items that are inside the collection by calling the Items.Count property, it gives me the expected value:

```<code>Public Class Form1 : Inherits Form

    Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown

        MessageBox.Show(String.Format("There are '{0}' items in the collection.",
                                      MyComboBox1.Items.Count))

    End Sub

End Class
</code>```

...However, any of that matters, because when I launch the application I don't see the item(s) added at design time, I mean the items added at design time are not drawn in the control at execution time.

QUESTION

What I'm missing to do?. How can I fix that?.

Please note that probably this IS NOT a drawing problem, because the items that I add through the Items.Add() and Items.AddRange() method at execution time are properly added and drawn.

I think maybe it could be some sort of issue about content synchronization...

I really don't know what is happening, because through the Object Inspector of Visual Studio I ensured to specify all the attribute classes to my classes, methods and properties, the same that are assigned by default for the ComboBox.Items property and the ComboBox.ObjectCollection class and the ComboBox.ObjectCollection.Item member.

答:
Here is an example of the technique I mentioned in the comments.  It is highly reliant of using Reflection to set a field in the ComboBox class as well as executing some methods in that class.  As such, it is subject to breaking if MS ever modifies these items.

Edit 2: Corrected Code

```<code>Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Drawing.Design
Imports System.Reflection

<DesignerCategory("UserControl")>
Public Class MyComboBox : Inherits ComboBox
    Private fiItemsCollection As FieldInfo
    Private piCMItem As PropertyInfo
    Private miNativeClear As MethodInfo
    Private miObjectCollectionAddRangeInternal As MethodInfo

    Private _Items As MyItemCollection

    <Editor(GetType(CollectionEditor), GetType(UITypeEditor))>
    <DesignerSerializationVisibility(DesignerSerializationVisibility.Content)>
    Public Shadows ReadOnly Property Items As MyItemCollection
        Get
        Return Me._Items
        End Get
    End Property

    <DebuggerStepThrough>
    Public Sub New()
        MyBase.New()
        MyBase.DrawMode = DrawMode.OwnerDrawFixed
        Me.fiItemsCollection = GetType(ComboBox).GetField("itemsCollection", BindingFlags.Instance Or BindingFlags.NonPublic)
        Me._Items = New MyItemCollection(Me)
        fiItemsCollection.SetValue(Me, Me._Items)
        Me.piCMItem = GetType(CurrencyManager).GetProperty("Item", BindingFlags.Instance Or BindingFlags.NonPublic)
        Me.miNativeClear = GetType(ComboBox).GetMethod("NativeClear", BindingFlags.Instance Or BindingFlags.NonPublic)
        Me.miObjectCollectionAddRangeInternal = GetType(ObjectCollection).GetMethod("AddRangeInternal", BindingFlags.Instance Or BindingFlags.NonPublic)
    End Sub

    Protected Overrides Sub RefreshItems()
        Dim selectedIndex As Integer = Me.SelectedIndex
        Dim itemsCollection As MyItemCollection = Me._Items
        Me._Items = Nothing

        Dim destination As Object() = Nothing
        If ((Not MyBase.DataManager Is Nothing) AndAlso (MyBase.DataManager.Count <> -1)) Then
            destination = New Object(MyBase.DataManager.Count - 1) {}
            Dim args(0 To 0) As Object
            For i As Int32 = 0 To destination.Length - 1
                args(0) = i
                destination(i) = piCMItem.GetValue(MyBase.DataManager, args)
            Next i
        ElseIf (Not itemsCollection Is Nothing) Then
            destination = New Object(itemsCollection.Count - 1) {}
            itemsCollection.CopyTo(destination, 0)
        End If

        Me.BeginUpdate()

        Try
            If MyBase.IsHandleCreated Then
                Me.miNativeClear.Invoke(Me, Nothing)
            End If
            If (Not destination Is Nothing) Then
                Me._Items = New MyItemCollection(Me)
                Me.miObjectCollectionAddRangeInternal.Invoke(Me._Items, New Object() {destination})
                Me.fiItemsCollection.SetValue(Me, Me._Items)
            End If
            If (Not MyBase.DataManager Is Nothing) Then
                Me.SelectedIndex = MyBase.DataManager.Position
            Else
                Me.SelectedIndex = selectedIndex
            End If
        Finally
            Me.EndUpdate()
        End Try
    End Sub

    Protected Overrides Sub OnDrawItem(ByVal e As DrawItemEventArgs)
        e.DrawBackground()
        e.DrawFocusRectangle()
        ' Check if it is an item from the Items collection.
        If (e.Index < 0) Then
            ' not an item, draw the text.
            Using brush As New SolidBrush(e.ForeColor)
                    e.Graphics.DrawString(Me.Text, e.Font, brush, e.Bounds.Left, e.Bounds.Top)
            End Using
        Else
            ' Get the item to draw.
            Dim item As MyItem = Me.Items(e.Index)
            Using brush As New SolidBrush(e.ForeColor)
                    e.Graphics.DrawString(item.Text, e.Font, brush, e.Bounds.Left, e.Bounds.Top)
            End Using
        End If
        MyBase.OnDrawItem(e)
    End Sub
End Class
</code>```

Body:
SCENARIO

I subclassed the ComboBox class to design a kind of ComboBox control on which I can supply a custom type (MyItem) to its ComboBox.Items collection...

This is the subclassed ComboBox class:

<DesignerCategory("UserControl")>
Public Class MyComboBox : Inherits ComboBox

    <Editor(GetType(CollectionEditor), GetType(UITypeEditor))>
    <DesignerSerializationVisibility(DesignerSerializationVisibility.Content)>
    Public Shadows ReadOnly Property Items As MyItemCollection

    <DebuggerStepThrough>
    Public Sub New()
        MyBase.DrawMode = DrawMode.OwnerDrawFixed
        Me.Items = New MyItemCollection(owner:=Me)
    End Sub

    Protected Overrides Sub OnDrawItem(ByVal e As DrawItemEventArgs)

        e.DrawBackground()
        e.DrawFocusRectangle()

        ' Check if it is an item from the Items collection.
        If (e.Index < 0) Then
            ' not an item, draw the text.
            Using brush As New SolidBrush(e.ForeColor)
                e.Graphics.DrawString(Me.Text, e.Font, brush, e.Bounds.Left, e.Bounds.Top)
            End Using

        Else
            ' Get the item to draw.
            Dim item As MyItem = Me.Items(e.Index)
            Using brush As New SolidBrush(e.ForeColor)
                e.Graphics.DrawString(item.Text, e.Font, brush, e.Bounds.Left, e.Bounds.Top)
            End Using

        End If

        MyBase.OnDrawItem(e)

    End Sub

End Class

This is the subclassed ComboBox.ObjectCollection class:

<ListBindable(False)>
<DefaultMember("Item")>
Public Class MyItemCollection : Inherits ObjectCollection

    Sub New(ByVal owner As MyComboBox)
        MyBase.New(owner)
    End Sub

    <Browsable(False)>
    <DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
    Default Public Overloads Property Item(ByVal index As Integer) As MyItem
        Get
            Return DirectCast(MyBase.Item(index), MyItem)
        End Get
        Set(ByVal value As MyItem)
            MyBase.Item(index) = value
        End Set
    End Property

    ' Original property:
    '
    '<Browsable(False)>
    '<DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
    'Default Public Overrides Property Item(ByVal index As Integer) As Object
    '    Get
    '        Return MyBase.Item(index)
    '    End Get
    '    Set(value As Object)
    '        MyBase.Item(index) = value
    '    End Set
    'End Property

End Class

And finally this is the custom type MyItem that I will use for the Items collection of my control:

Public NotInheritable Class MyItem

    Public Property Text As String

    Public Sub New()
        Me.New(String.Empty)
    End Sub

    Public Sub New(ByVal text As String)
        Me.Text = text
    End Sub

End Class

All this works fine at execution time, I can add items and it works as expected, the problem is that it won't work at design time...

PROBLEM

When I try to add an item at design time like this:

...At first sight it seems it works, because I can add the item.

And the record seems properly auto-generated by Visual Studio in the Form's dsigner class (Form1.Designer.vb):

Private Sub InitializeComponent()
    Me.MyComboBox1 = New MyComboBox()
    Dim MyItem1 As MyItem = New MyItem()
    MyItem1.Text = "Test"
    Me.MyComboBox1.Items.AddRange(New Object() {MyItem1})

    ' ...
End Sub

Even more, If I try to determine at execution time the current amount of items that are inside the collection by calling the Items.Count property, it gives me the expected value:

Public Class Form1 : Inherits Form

    Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown

        MessageBox.Show(String.Format("There are '{0}' items in the collection.",
                                      MyComboBox1.Items.Count))

    End Sub

End Class

...However, any of that matters, because when I launch the application I don't see the item(s) added at design time, I mean the items added at design time are not drawn in the control at execution time.

QUESTION

What I'm missing to do?. How can I fix that?.

Please note that probably this IS NOT a drawing problem, because the items that I add through the Items.Add() and Items.AddRange() method at execution time are properly added and drawn.

I think maybe it could be some sort of issue about content synchronization...

I really don't know what is happening, because through the Object Inspector of Visual Studio I ensured to specify all the attribute classes to my classes, methods and properties, the same that are assigned by default for the ComboBox.Items property and the ComboBox.ObjectCollection class and the ComboBox.ObjectCollection.Item member.

Body:
Here is an example of the technique I mentioned in the comments.  It is highly reliant of using Reflection to set a field in the ComboBox class as well as executing some methods in that class.  As such, it is subject to breaking if MS ever modifies these items.

Edit 2: Corrected Code

Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Drawing.Design
Imports System.Reflection

<DesignerCategory("UserControl")>
Public Class MyComboBox : Inherits ComboBox
    Private fiItemsCollection As FieldInfo
    Private piCMItem As PropertyInfo
    Private miNativeClear As MethodInfo
    Private miObjectCollectionAddRangeInternal As MethodInfo

    Private _Items As MyItemCollection

    <Editor(GetType(CollectionEditor), GetType(UITypeEditor))>
    <DesignerSerializationVisibility(DesignerSerializationVisibility.Content)>
    Public Shadows ReadOnly Property Items As MyItemCollection
        Get
        Return Me._Items
        End Get
    End Property

    <DebuggerStepThrough>
    Public Sub New()
        MyBase.New()
        MyBase.DrawMode = DrawMode.OwnerDrawFixed
        Me.fiItemsCollection = GetType(ComboBox).GetField("itemsCollection", BindingFlags.Instance Or BindingFlags.NonPublic)
        Me._Items = New MyItemCollection(Me)
        fiItemsCollection.SetValue(Me, Me._Items)
        Me.piCMItem = GetType(CurrencyManager).GetProperty("Item", BindingFlags.Instance Or BindingFlags.NonPublic)
        Me.miNativeClear = GetType(ComboBox).GetMethod("NativeClear", BindingFlags.Instance Or BindingFlags.NonPublic)
        Me.miObjectCollectionAddRangeInternal = GetType(ObjectCollection).GetMethod("AddRangeInternal", BindingFlags.Instance Or BindingFlags.NonPublic)
    End Sub

    Protected Overrides Sub RefreshItems()
        Dim selectedIndex As Integer = Me.SelectedIndex
        Dim itemsCollection As MyItemCollection = Me._Items
        Me._Items = Nothing

        Dim destination As Object() = Nothing
        If ((Not MyBase.DataManager Is Nothing) AndAlso (MyBase.DataManager.Count <> -1)) Then
            destination = New Object(MyBase.DataManager.Count - 1) {}
            Dim args(0 To 0) As Object
            For i As Int32 = 0 To destination.Length - 1
                args(0) = i
                destination(i) = piCMItem.GetValue(MyBase.DataManager, args)
            Next i
        ElseIf (Not itemsCollection Is Nothing) Then
            destination = New Object(itemsCollection.Count - 1) {}
            itemsCollection.CopyTo(destination, 0)
        End If

        Me.BeginUpdate()

        Try
            If MyBase.IsHandleCreated Then
                Me.miNativeClear.Invoke(Me, Nothing)
            End If
            If (Not destination Is Nothing) Then
                Me._Items = New MyItemCollection(Me)
                Me.miObjectCollectionAddRangeInternal.Invoke(Me._Items, New Object() {destination})
                Me.fiItemsCollection.SetValue(Me, Me._Items)
            End If
            If (Not MyBase.DataManager Is Nothing) Then
                Me.SelectedIndex = MyBase.DataManager.Position
            Else
                Me.SelectedIndex = selectedIndex
            End If
        Finally
            Me.EndUpdate()
        End Try
    End Sub

    Protected Overrides Sub OnDrawItem(ByVal e As DrawItemEventArgs)
        e.DrawBackground()
        e.DrawFocusRectangle()
        ' Check if it is an item from the Items collection.
        If (e.Index < 0) Then
            ' not an item, draw the text.
            Using brush As New SolidBrush(e.ForeColor)
                    e.Graphics.DrawString(Me.Text, e.Font, brush, e.Bounds.Left, e.Bounds.Top)
            End Using
        Else
            ' Get the item to draw.
            Dim item As MyItem = Me.Items(e.Index)
            Using brush As New SolidBrush(e.ForeColor)
                    e.Graphics.DrawString(item.Text, e.Font, brush, e.Bounds.Left, e.Bounds.Top)
            End Using
        End If
        MyBase.OnDrawItem(e)
    End Sub
End Class


问:
How does npm handle lock files
So I'm running npm install xyz inside a script that is called by the postinstall npm hook of another npm module. (Let's not get into why please but it has to do with optional dependencies that are not supported by npm)

```<code>npm install moduleA
  -> installing moduleA
    -> running postinstall hook (my script)
      -> my script runs npm install xyz
</code>```

When I run the script itself the npm install runs reasonably fast but when I install the module within the postinstall hook the script waits on a lock file for at least 1 min. (or so I assume)

When I enable verbose loglevel in npm I get an output like below:

```<code>[a lot more lines above]
npm verb addNamed "latest" is being treated as a dist-tag for invert-kv
npm info addNameTag [ 'invert-kv', 'latest' ]
npm verb addNameTag registry:https://registry.npmjs.org/invert-kv already in flight; waiting
npm verb addNamed "1.0.0" is a plain semver version for invert-kv
npm verb afterAdd /Users/path/.npm/invert-kv/1.0.0/package/package.json not in flight; writing
npm verb correctMkdir /Users/path/.npm correctMkdir not in flight; initializing
npm verb afterAdd /Users/path/.npm/invert-kv/1.0.0/package/package.json written
npm verb cache add spec camelcase@^3.0.0
npm verb addNamed ">=3.0.0 <4.0.0" is a valid semver range for camelcase
npm verb addNameRange registry:https://registry.npmjs.org/camelcase not in flight; fetching
npm verb get https://registry.npmjs.org/camelcase not expired, no request
npm verb addNamed "3.0.0" is a plain semver version for camelcase
npm verb afterAdd /Users/path/.npm/camelcase/3.0.0/package/package.json not in flight; writing
npm verb correctMkdir /Users/path/.npm correctMkdir not in flight; initializing
npm verb afterAdd /Users/path/.npm/camelcase/3.0.0/package/package.json written
npm verb correctMkdir /Users/path/.npm/_locks correctMkdir not in flight; initializing
</code>```

waits here for at least one minute

```<code>npm verb lock using /Users/path/.npm/_locks/staging-d21af557b41d4821.lock for /Users/path/Desktop/t/node_modules/.staging
npm verb unbuild node_modules/.staging/abbrev-ac014442
npm verb unbuild node_modules/.staging/ansi-regex-12e09986
npm verb unbuild node_modules/.staging/ansi-styles-1359ba2f
npm verb unbuild node_modules/.staging/aproba-d9971840
npm verb unbuild node_modules/.staging/array-find-index-c1ddfc4c
[a lot more lines below]
</code>```

Now looking at the code of correctMkdir it seems that to just load all all files in /Users/path/.npm/_locks into memory and try to repair permission? Not sure.

correctMkdir is called by lock. This seems to hash the file and some encryption? Also not sure.

After reverse engineering some npm code I made progress by changing the config for cache-lock-stale, cache-lock-wait to 10ms. Unfortunately it still hangs for way too long before installing everything correctly. I suspect the changed config is not taken into account when changing right before and npm being inflight? Maybe? Maybe it's something entirely different? :)

Anyone who can hint me the right direction? Is there something I can do to speed things up?

答:
After a night of sleep the install now seems to be much faster. I'm guessing some caching was still hang in my _locks folder.

So the answer was:

Set cache-lock-stale and cache-lock-wait to 10ms each temporarily and npm won't wait for your lock file to expire. As I understand it npm is trying to wait for all lock files in the _lock folder to be finished and because we are running npm install inside npm install the lock file from the parent process is still in use obviously. This is all more of a guess but I hope it helps someone in the future.

Title: How does npm handle lock files

Body:
So I'm running npm install xyz inside a script that is called by the postinstall npm hook of another npm module. (Let's not get into why please but it has to do with optional dependencies that are not supported by npm)

npm install moduleA
  -> installing moduleA
    -> running postinstall hook (my script)
      -> my script runs npm install xyz

When I run the script itself the npm install runs reasonably fast but when I install the module within the postinstall hook the script waits on a lock file for at least 1 min. (or so I assume)

When I enable verbose loglevel in npm I get an output like below:

[a lot more lines above]
npm verb addNamed "latest" is being treated as a dist-tag for invert-kv
npm info addNameTag [ 'invert-kv', 'latest' ]
npm verb addNameTag registry:https://registry.npmjs.org/invert-kv already in flight; waiting
npm verb addNamed "1.0.0" is a plain semver version for invert-kv
npm verb afterAdd /Users/path/.npm/invert-kv/1.0.0/package/package.json not in flight; writing
npm verb correctMkdir /Users/path/.npm correctMkdir not in flight; initializing
npm verb afterAdd /Users/path/.npm/invert-kv/1.0.0/package/package.json written
npm verb cache add spec camelcase@^3.0.0
npm verb addNamed ">=3.0.0 <4.0.0" is a valid semver range for camelcase
npm verb addNameRange registry:https://registry.npmjs.org/camelcase not in flight; fetching
npm verb get https://registry.npmjs.org/camelcase not expired, no request
npm verb addNamed "3.0.0" is a plain semver version for camelcase
npm verb afterAdd /Users/path/.npm/camelcase/3.0.0/package/package.json not in flight; writing
npm verb correctMkdir /Users/path/.npm correctMkdir not in flight; initializing
npm verb afterAdd /Users/path/.npm/camelcase/3.0.0/package/package.json written
npm verb correctMkdir /Users/path/.npm/_locks correctMkdir not in flight; initializing

waits here for at least one minute

npm verb lock using /Users/path/.npm/_locks/staging-d21af557b41d4821.lock for /Users/path/Desktop/t/node_modules/.staging
npm verb unbuild node_modules/.staging/abbrev-ac014442
npm verb unbuild node_modules/.staging/ansi-regex-12e09986
npm verb unbuild node_modules/.staging/ansi-styles-1359ba2f
npm verb unbuild node_modules/.staging/aproba-d9971840
npm verb unbuild node_modules/.staging/array-find-index-c1ddfc4c
[a lot more lines below]

Now looking at the code of correctMkdir it seems that to just load all all files in /Users/path/.npm/_locks into memory and try to repair permission? Not sure.

correctMkdir is called by lock. This seems to hash the file and some encryption? Also not sure.

After reverse engineering some npm code I made progress by changing the config for cache-lock-stale, cache-lock-wait to 10ms. Unfortunately it still hangs for way too long before installing everything correctly. I suspect the changed config is not taken into account when changing right before and npm being inflight? Maybe? Maybe it's something entirely different? :)

Anyone who can hint me the right direction? Is there something I can do to speed things up?


问:
Error while trying to destructure an array of possible length 2
I am trying to destructure an array of length 2, but I get a typescript error:

```<code>[ts] Tuple type '[string]' with length '1' cannot be assigned
to tuple with length '2'.
</code>```

```<code>    let output = {status: false};
    if(execute.permission) {
        let message: [string] = execute.params;
        if(message.length >= 2) {
            // Destructuring follows
            [output['position'], output['message']] = message;
        }
    }
</code>```

How do I tell typescript, that the array could possiblly be of length  2?

答:
You've not declared message as an array; you've declared it as a tuple ([string]) and tuples have a fixed number of elements. (See the Tuple section in the Basic Types documentation.)

You could declare it as a tuple that has two string elements ([string, string]), but given that you are testing message.length >= 2 it seems likely you intended to declare it as a string array (string[]):

let output = {status: false};
if(execute.permission) {
    let message: string[] = execute.params;
    if(message.length >= 2) {
        // Destructuring follows
        [output['position'], output['message']] = message;
    }
}
```

Body:
I am trying to destructure an array of length 2, but I get a typescript error:

[ts] Tuple type '[string]' with length '1' cannot be assigned
to tuple with length '2'.

    let output = {status: false};
    if(execute.permission) {
        let message: [string] = execute.params;
        if(message.length >= 2) {
            // Destructuring follows
            [output['position'], output['message']] = message;
        }
    }

How do I tell typescript, that the array could possiblly be of length  2?


问:
Windows Batch: How to grab a Job ID from a log and set it to a variable?
I have a log file (job.log) that contains a jobID that is always changing.
How do I open this file and parse the job ID and store 761 to a variable so I can use it for other command references?  Again, this log will always have a different jobID so I'm looking for a dynamic way to do this.

```<code>"RUNNING","jobId":761,"logFileName":"outbox/logs/AQCONSOL-Finance_761.log
</code>```

FYI, within my bat file, I will use the following command to download this log file...

```<code>call automate downloadfile "outbox/logs/AQCONSOL-Finance_"%jobid%".log"
</code>```

答:
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\Q43128657.txt"
FOR /f "usebackq tokens=3 delims=:," %%a IN ("%filename1%") DO SET job=%%a
ECHO job is %job%

GOTO :EOF
```

<p>You would need to change the setting of <code>sourcedir</code> to suit your circumstances.</p>

<p>I used a file named <code>Q43128657.txt</code> containing your data for my testing.</p>

<p>Simply parse the line using <code>:</code> and <code>,</code> as delimiters and select the third token.</p>

<hr>

<p>Revision to select file "rundatarule*.log"</p>

<pre class="lang-dos prettyprint-override"><code>@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /f "delims=" %%a IN ('dir /b /a-d /od "%sourcedir%\rundatarule*.log" ') DO SET "filename1=%sourcedir%\%%a"
FOR /f "usebackqtokens=3delims=:," %%a IN ("%filename1%") DO SET job=%%a
ECHO job is %job%

GOTO :EOF
</code>```

The dir command lists matching files in /b basic form /a-d with no directorynames /od in order of date (just in case there are multiple files, select the very last chronologically) and processes that list, applying the entire name (in case there are separators) to %%a and thus assigning the reconstructed name (with the directory) to filename1.

It is considered good practice to format date-timestamps as ymdhms, not dmyhms as this provides an easily-sortable sequence.

Body:
I have a log file (job.log) that contains a jobID that is always changing.
How do I open this file and parse the job ID and store 761 to a variable so I can use it for other command references?  Again, this log will always have a different jobID so I'm looking for a dynamic way to do this.

"RUNNING","jobId":761,"logFileName":"outbox/logs/AQCONSOL-Finance_761.log

FYI, within my bat file, I will use the following command to download this log file...

call automate downloadfile "outbox/logs/AQCONSOL-Finance_"%jobid%".log"

Body:
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\Q43128657.txt"
FOR /f "usebackq tokens=3 delims=:," %%a IN ("%filename1%") DO SET job=%%a
ECHO job is %job%

GOTO :EOF

You would need to change the setting of sourcedir to suit your circumstances.

I used a file named Q43128657.txt containing your data for my testing.

Simply parse the line using : and , as delimiters and select the third token.

Revision to select file "rundatarule*.log"

@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /f "delims=" %%a IN ('dir /b /a-d /od "%sourcedir%\rundatarule*.log" ') DO SET "filename1=%sourcedir%\%%a"
FOR /f "usebackqtokens=3delims=:," %%a IN ("%filename1%") DO SET job=%%a
ECHO job is %job%

GOTO :EOF

The dir command lists matching files in /b basic form /a-d with no directorynames /od in order of date (just in case there are multiple files, select the very last chronologically) and processes that list, applying the entire name (in case there are separators) to %%a and thus assigning the reconstructed name (with the directory) to filename1.

It is considered good practice to format date-timestamps as ymdhms, not dmyhms as this provides an easily-sortable sequence.


问:
How can I extract objects several layers deep using the map method?
I'm a trying to access the change order information as seen below to create a list of all the change_order_names. Using the current code I am getting the results I have posted. Will someone show me how I can access the change order information and produce the list?

```<code>if (componentType == CHANGE_ORDER_TYPE) {
        if (!this.props.data) {
            return null;
        } else {
            const changeList = this.props.data.map(function (result) {
                return (result.change_orders);
            });
            // return resultsList;
            console.log(changeList);
        }
    }
</code>```

This is the current response from the map method above.

```<code>[
 [
  {
     "id":1,
     "change_order_name":"change 1",
     "project_id":"1",
     "cws_change_order_id":"33214324",
     "slug":"change-1",
     "created_at":null,
     "updated_at":null
  },
  {
     "id":2,
     "change_order_name":"change 2",
     "project_id":"1",
     "cws_change_order_id":"3211324",
     "slug":"change-2",
     "created_at":null,
     "updated_at":null
  }
],
[
  {
     "id":3,
     "change_order_name":"change 3",
     "project_id":"2",
     "cws_change_order_id":"3234324",
     "slug":"change-3",
     "created_at":null,
     "updated_at":null
  },
  {
     "id":4,
     "change_order_name":"change 4",
     "project_id":"2",
     "cws_change_order_id":"6234532",
     "slug":"change-4",
     "created_at":null,
     "updated_at":null
  }
],
[
  {
     "id":5,
     "change_order_name":"change 5",
     "project_id":"3",
     "cws_change_order_id":"3124214",
     "slug":"change-5",
     "created_at":null,
     "updated_at":null
  }
]
]
</code>```

答:
This is how I dug down to get get access to the individual change_orders</p>

```<code>if (componentType == CHANGE_ORDER_TYPE) {
        if (!this.props.data) {
            return null;
        } else {
            const changeList = this.props.data.map(function (result) {
                return (result.change_orders);
            });
            let changeOrdersArr = [];
            for (let i = 0; i < changeList.length; i++) {
                let inner = changeList[i];
                for (let z = 0; z < inner.length; z++) {
                    changeOrdersArr.push(inner[z])
                }
            }
</code>```

Body:
I'm a trying to access the change order information as seen below to create a list of all the change_order_names. Using the current code I am getting the results I have posted. Will someone show me how I can access the change order information and produce the list?

if (componentType == CHANGE_ORDER_TYPE) {
        if (!this.props.data) {
            return null;
        } else {
            const changeList = this.props.data.map(function (result) {
                return (result.change_orders);
            });
            // return resultsList;
            console.log(changeList);
        }
    }

This is the current response from the map method above.

[
 [
  {
     "id":1,
     "change_order_name":"change 1",
     "project_id":"1",
     "cws_change_order_id":"33214324",
     "slug":"change-1",
     "created_at":null,
     "updated_at":null
  },
  {
     "id":2,
     "change_order_name":"change 2",
     "project_id":"1",
     "cws_change_order_id":"3211324",
     "slug":"change-2",
     "created_at":null,
     "updated_at":null
  }
],
[
  {
     "id":3,
     "change_order_name":"change 3",
     "project_id":"2",
     "cws_change_order_id":"3234324",
     "slug":"change-3",
     "created_at":null,
     "updated_at":null
  },
  {
     "id":4,
     "change_order_name":"change 4",
     "project_id":"2",
     "cws_change_order_id":"6234532",
     "slug":"change-4",
     "created_at":null,
     "updated_at":null
  }
],
[
  {
     "id":5,
     "change_order_name":"change 5",
     "project_id":"3",
     "cws_change_order_id":"3124214",
     "slug":"change-5",
     "created_at":null,
     "updated_at":null
  }
]
]

Body:
This is how I dug down to get get access to the individual change_orders

if (componentType == CHANGE_ORDER_TYPE) {
        if (!this.props.data) {
            return null;
        } else {
            const changeList = this.props.data.map(function (result) {
                return (result.change_orders);
            });
            let changeOrdersArr = [];
            for (let i = 0; i < changeList.length; i++) {
                let inner = changeList[i];
                for (let z = 0; z < inner.length; z++) {
                    changeOrdersArr.push(inner[z])
                }
            }


答:
Use string[] (an array of any length) instead of [string] (a "tuple" limited to length 1) as your type.

Tuples have a specific length and make it easier to represent multiple types assigned to specific index positions, like [string, number]. Homogenous (single-type) tuples are still useful in some scenarios (such as representing pairs in a map), but are not as common.

Arrays, on the other hand, are lists of variable length but are designed to hold only references of a single type (even if that type is a union type or any). If one index of any array can hold a certain value, every index can hold that same kind of value.

TypeScript Code (Playground Link)

```<code>let execute = { permission: true, params: ['a', 'b']}

let output = { status: false };
    if(execute.permission) {
        let message: string[] = execute.params;
        if(message.length >= 2) {
            // Destructuring follows
            [output['position'], output['message']] = message;
        }
}

console.log(output)
</code>```

Title: Error while trying to destructure an array of possible length 2

Body:
Use string[] (an array of any length) instead of [string] (a "tuple" limited to length 1) as your type.

Tuples have a specific length and make it easier to represent multiple types assigned to specific index positions, like [string, number]. Homogenous (single-type) tuples are still useful in some scenarios (such as representing pairs in a map), but are not as common.

Arrays, on the other hand, are lists of variable length but are designed to hold only references of a single type (even if that type is a union type or any). If one index of any array can hold a certain value, every index can hold that same kind of value.

TypeScript Code (<a href="http://www.typescriptlang.org/play/index.html#src=let%20execute%20%3D%20%7B%20permission%3A%20true%2C%20params%3A%20%5B%27a%27%2C%20%27b%27%5D%7D%0D%0A%0D%0A%0D%0A%0D%0Alet%20output%20%3D%20%7B%20status%3A%20false%20%7D%3B%0D%0A%20%20%20%20if(execute.permission)%20%7B%0D%0A%20%20%20%20%20%20%20%20let%20message%3A%20string%5B%5D%20%3D%20execute.params%3B%0D%0A%20%20%20%20%20%20%20%20if(message.length%20%3E%3D%202)%20%7B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20Destructuring%20follows%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%5Boutput%5B%27position%27%5D%2C%20output%5B%27message%27%5D%5D%20%3D%20message%3B%0D%0A%20%20%20%20%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Aconsole.log(output)" rel="nofollow noreferrer">Playground Link)

let execute = { permission: true, params: ['a', 'b']}

let output = { status: false };
    if(execute.permission) {
        let message: string[] = execute.params;
        if(message.length >= 2) {
            // Destructuring follows
            [output['position'], output['message']] = message;
        }
}

console.log(output)