问:
Convert Image object to rgb pixel array and back in Flutter
Is there a way to get an image's rgb matrix representation? and vice versa? I would like to perform image masking/filtering on the original image so it needs to be applied to its rgb matrix representation. Currently using this library to get an image from a device: https://pub.dartlang.org/packages/image_picker</p>

答:
import 'dart:ui' as ui;
import 'package:flutter/material.dart';

// for a local iamge example
List RGBAList;
// 1. get [ImageProvider] instance
//    [ExactAssetImage] extends [AssetBundleImageProvider] extends [ImageProvider]
ExactAssetImage provider = ExactAssetImage('$local_img_uri');

// 2. get [ui.Image] by [ImageProvider]
ImageStream stream = provider.resolve(ImageConfiguration.empty);
Completer completer = Completer<ui.Image>();
ImageStreamListener listener = ImageStreamListener((frame, sync) {
    ui.Image image = frame.image;
    completer.complete(image);
    stream.removeListener(listener);
})
stream.addListener(listener);

// 3. get rgba array/list by [ui.Image]
completer.then((ui.Image image) {
    image.toByteData(format: ui.ImageByteFormat.rowRgba).then((ByteData data) {
        RGBAList = data.buffer.asUint8List().toList();
    });
})
```


来源: stackexchange

问:
DELPHI - Extra semi-colons in except blocks, any purpose? Optional semi-colon before except or end, What's better with or without?
Working in a Delphi 10.3.3 application with a ton of extra & missing semi-colons. The app compiles if they are dropped prior to any block ending statement.

Does a floating semi-colon between [except] and [end] serve any purpose in the code, such as faster run time or throw some default exception, or some other purpose?

Could this throw a random compile or runtime error?

Does leaving a semi-colon off the last line before an end or except speed up runtime?

Is one way, more error-prone than another or subject to random compile or runtime errors?

Here is code that can be dropped into any test project with a form having an edit box, a button and a memo box created with drag-n-drop default settings.

```<code>function TForm1.isThisUseful(this : string): boolean;
var
  i: Integer;
begin
  result := false;
  try
    if this = ''
    then
      i := 0
    else
      i := 1
  except
    ;
  end;
  result := (i > 0)
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if isThisUseful(Edit1.Text)
  then
    Memo1.Text := 'Yes, it is useful'
  else
    Memo1.Text := 'This is a waste of time.'
end;
</code>```

答:
I thought I would try some measurements, using the Line Timer of NexusDB's Quality Suite on this D7 test program:

```<code>{$A8,B-,C+,D+,E-,F-,G+,H+,I+,J-,K-,L+,M-,N+,O-,P+,Q-,R-,S-,T-,U-,V+,W+,X+,Y+,Z1}
program semicolontest;

{$APPTYPE CONSOLE}

uses
  SysUtils;

function isThisUseful1(this : string): boolean;
var
  i: Integer;
begin
  result := false;
  try
    if this = ''
    then
      i := 0
    else
      i := 1
  except
    ;
  end;
  result := (i > 0)
end;

function isThisUseful2(this : string): boolean;
var
  i: Integer;
begin
  result := false;
  try
    if this = ''
    then
      i := 0
    else
      i := 1
  except

  end;
  result := (i > 0)
end;

var
  Input : String[20];
  i : Integer;
  Res : Boolean;

begin

   Input := 'abcdefg';

   writeln('Starting');
   for i := 1 to 1000000 do begin
     Res := isThisUseful1(Input);
     Res := isThisUseful2(Input);
   end;
   writeln('Done');
   // readln;
end.
</code>```

which contains two versions of the isThisUseful function from the question, one with, and one without the semicolon in the except block.  The results of running this code (with apologies for the slightly mangled layout) are as follows:

```<code>Line    Total Time  Hit Count   Source
1       -   {$A8,B-,C+,D+,E-,F-,G+,H+,I+,J-,K-,L+,M-,N+,O-,P+,Q-,R-,S-,T-,U-,V+,W+,X+,Y+,Z1}
2       -   program semicolontest;
3       -
4       -   {$APPTYPE CONSOLE}
5       -
6       -   uses
7       -     SysUtils;
8       -
9       -   function isThisUseful1(this : string): boolean;
10      -   var
11      -     i: Integer;
12  2.807175    1,000,000   begin
13  0.761388    1,000,000     result := false;
14  2.133202    1,000,000     try
15  1.403061    1,000,000       if this = ''
16      -       then
17      -         i := 0
18      -       else
19  0.826841    1,000,000         i := 1
20      -     except
21      -       ;
22      -     end;
23  0.735419    1,000,000     result := (i > 0)
24      -   end;
25      -
26      -   function isThisUseful2(this : string): boolean;
27      -   var
28      -     i: Integer;
29  1.260030    1,000,000   begin
30  0.782293    1,000,000     result := false;
31  0.894420    1,000,000     try
32  0.820860    1,000,000       if this = ''
33      -       then
34      -         i := 0
35      -       else
36  0.873424    1,000,000         i := 1
37      -     except
38      -
39      -     end;
40  0.778922    1,000,000     result := (i > 0)
41      -   end;
42      -
43      -   var
44      -     Input : String[20];
45      -     i : Integer;
46      -     Res : Boolean;
47      -
48  1.167140    1   begin
49      -
50  0.000036    1      Input := 'abcdefg';
51      -
52  0.641347    1      writeln('Starting');
53  0.000026    1      for i := 1 to 1000000 do begin
54      -        Res := isThisUseful1(Input);
55      -        Res := isThisUseful2(Input);
56  0.669066    1,000,000      end;
57  0.402661    1      writeln('Done');
58      -      // readln;
59      -   end.
60      -
</code>```

Notice that no time is recorded for line 21, the semicolon in the try ...except block, for the simple reason that, as expected, no code is generated for it.

For completeness, the following are disassemblies of isThisUseful1 and isThisUseful2

isThisUseful1:

```<code>Address Bytes   Text    Block #
00408620h       [semicolontest.dpr.12] begin
00408620h   55        push ebp  1
00408621h   8BEC          mov ebp, esp  1
00408623h   83C4F4        add esp, 0FFFFFFF4h ; (-0Ch)  1
00408626h   53        push ebx  1
00408627h   56        push esi  1
00408628h   57        push edi  1
00408629h   8945FC        mov [ebp-04h], eax    1
0040862Ch   8B45FC        mov eax, [ebp-04h]    1
0040862Fh   E87CB7FFFF        call System::LStrAddRef ;(00403DB0h)  1
00408634h   33C0          xor eax, eax  1
00408636h   55        push ebp  1
00408637h   689A864000        push offset @@6   1
0040863Ch   64FF30        push fs:[eax] 1
0040863Fh   648920        mov fs:[eax], esp 1
00408642h       [semicolontest.dpr.13] result := false;
00408642h   C645FB00          mov byte ptr [ebp-05h], 00h   1
00408646h       [semicolontest.dpr.14] try
00408646h   33C0          xor eax, eax  1
00408648h   55        push ebp  1
00408649h   6872864000        push offset @@3   1
0040864Eh   64FF30        push fs:[eax] 1
00408651h   648920        mov fs:[eax], esp 1
00408654h       [semicolontest.dpr.15] if this = ''
00408654h   837DFC00          cmp dword ptr [ebp-04h], 00h  1
00408658h   7507          jnz @@1   1
0040865Ah       [semicolontest.dpr.17] i := 0
0040865Ah   33C0          xor eax, eax  2
0040865Ch   8945F4        mov [ebp-0Ch], eax    2
0040865Fh   EB07          jmp @@2   2
00408661h       [semicolontest.dpr.19] i := 1
00408661h       @@1:
00408661h   C745F401000000        mov dword ptr [ebp-0Ch], 01h  3
00408668h       @@2:
00408668h   33C0          xor eax, eax  4
0040866Ah   5A        pop edx   4
0040866Bh   59        pop ecx   4
0040866Ch   59        pop ecx   4
0040866Dh   648910        mov fs:[eax], edx 4
00408670h   EB0A          jmp @@4   4
00408672h       @@3:
00408672h   E9DDACFFFF        jmp System::HandleAnyException ;(00403354h)   5
00408677h       [semicolontest.dpr.21] ;
00408677h   E8B8AEFFFF        call System::DoneExcept ;(00403534h)  5
0040867Ch       [semicolontest.dpr.23] result := (i > 0)
0040867Ch       @@4:
0040867Ch   837DF400          cmp dword ptr [ebp-0Ch], 00h  6
00408680h   0F9F45FB          setnle [ebp-05h]  6
00408684h   33C0          xor eax, eax  6
00408686h   5A        pop edx   6
00408687h   59        pop ecx   6
00408688h   59        pop ecx   6
00408689h   648910        mov fs:[eax], edx 6
0040868Ch   68A1864000        push offset @@7   6
00408691h       @@5:
00408691h   8D45FC        lea eax, [ebp-04h]    7
00408694h   E8BFB3FFFF        call System::LStrClr ;(00403A58h) 7
00408699h   C3        ret   7
0040869Ah       @@6:
0040869Ah   E9E1ADFFFF        jmp System::HandleFinally ;(00403480h)    8
0040869Fh   EBF0          jmp @@5   8
004086A1h       @@7:
004086A1h   8A45FB        mov al, [ebp-05h] 9
004086A4h       [semicolontest.dpr.24] end;
004086A4h   5F        pop edi   9
004086A5h   5E        pop esi   9
004086A6h   5B        pop ebx   9
004086A7h   8BE5          mov esp, ebp  9
004086A9h   5D        pop ebp   9
004086AAh   C3        ret   9
</code>```

isThisUseful2:

```<code>Address Bytes   Text    Block #
00408620h       [semicolontest.dpr.12] begin
00408620h   55        push ebp  1
00408621h   8BEC          mov ebp, esp  1
00408623h   83C4F4        add esp, 0FFFFFFF4h ; (-0Ch)  1
00408626h   53        push ebx  1
00408627h   56        push esi  1
00408628h   57        push edi  1
00408629h   8945FC        mov [ebp-04h], eax    1
0040862Ch   8B45FC        mov eax, [ebp-04h]    1
0040862Fh   E87CB7FFFF        call System::LStrAddRef ;(00403DB0h)  1
00408634h   33C0          xor eax, eax  1
00408636h   55        push ebp  1
00408637h   689A864000        push offset @@6   1
0040863Ch   64FF30        push fs:[eax] 1
0040863Fh   648920        mov fs:[eax], esp 1
00408642h       [semicolontest.dpr.13] result := false;
00408642h   C645FB00          mov byte ptr [ebp-05h], 00h   1
00408646h       [semicolontest.dpr.14] try
00408646h   33C0          xor eax, eax  1
00408648h   55        push ebp  1
00408649h   6872864000        push offset @@3   1
0040864Eh   64FF30        push fs:[eax] 1
00408651h   648920        mov fs:[eax], esp 1
00408654h       [semicolontest.dpr.15] if this = ''
00408654h   837DFC00          cmp dword ptr [ebp-04h], 00h  1
00408658h   7507          jnz @@1   1
0040865Ah       [semicolontest.dpr.17] i := 0
0040865Ah   33C0          xor eax, eax  2
0040865Ch   8945F4        mov [ebp-0Ch], eax    2
0040865Fh   EB07          jmp @@2   2
00408661h       [semicolontest.dpr.19] i := 1
00408661h       @@1:
00408661h   C745F401000000        mov dword ptr [ebp-0Ch], 01h  3
00408668h       @@2:
00408668h   33C0          xor eax, eax  4
0040866Ah   5A        pop edx   4
0040866Bh   59        pop ecx   4
0040866Ch   59        pop ecx   4
0040866Dh   648910        mov fs:[eax], edx 4
00408670h   EB0A          jmp @@4   4
00408672h       @@3:
00408672h   E9DDACFFFF        jmp System::HandleAnyException ;(00403354h)   5
00408677h       [semicolontest.dpr.21] ;
00408677h   E8B8AEFFFF        call System::DoneExcept ;(00403534h)  5
0040867Ch       [semicolontest.dpr.23] result := (i > 0)
0040867Ch       @@4:
0040867Ch   837DF400          cmp dword ptr [ebp-0Ch], 00h  6
00408680h   0F9F45FB          setnle [ebp-05h]  6
00408684h   33C0          xor eax, eax  6
00408686h   5A        pop edx   6
00408687h   59        pop ecx   6
00408688h   59        pop ecx   6
00408689h   648910        mov fs:[eax], edx 6
0040868Ch   68A1864000        push offset @@7   6
00408691h       @@5:
00408691h   8D45FC        lea eax, [ebp-04h]    7
00408694h   E8BFB3FFFF        call System::LStrClr ;(00403A58h) 7
00408699h   C3        ret   7
0040869Ah       @@6:
0040869Ah   E9E1ADFFFF        jmp System::HandleFinally ;(00403480h)    8
0040869Fh   EBF0          jmp @@5   8
004086A1h       @@7:
004086A1h   8A45FB        mov al, [ebp-05h] 9
004086A4h       [semicolontest.dpr.24] end;
004086A4h   5F        pop edi   9
004086A5h   5E        pop esi   9
004086A6h   5B        pop ebx   9
004086A7h   8BE5          mov esp, ebp  9
004086A9h   5D        pop ebp   9
004086AAh   C3        ret   9
</code>```

(I went cross-eyed trying to compare these myself, and wasn't going to waste my time running them past BeyondCompare).

Anyway, I think this shows that as stated by myself and others, the compiler does not generate code for a line containing only a semicolon in a try...except block, and it shouldn't do anywhere else, either, though as noted there are cases where the presence or otherwise of a semicolon changes the semantics of the code and hence the code generated.

ContentLicense: CC BY-SA 4.0

Body:
Working in a Delphi 10.3.3 application with a ton of extra & missing semi-colons. The app compiles if they are dropped prior to any block ending statement.

Does a floating semi-colon between [except] and [end] serve any purpose in the code, such as faster run time or throw some default exception, or some other purpose?

Could this throw a random compile or runtime error?

Does leaving a semi-colon off the last line before an end or except speed up runtime?

Is one way, more error-prone than another or subject to random compile or runtime errors?

Here is code that can be dropped into any test project with a form having an edit box, a button and a memo box created with drag-n-drop default settings.

function TForm1.isThisUseful(this : string): boolean;
var
  i: Integer;
begin
  result := false;
  try
    if this = ''
    then
      i := 0
    else
      i := 1
  except
    ;
  end;
  result := (i > 0)
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if isThisUseful(Edit1.Text)
  then
    Memo1.Text := 'Yes, it is useful'
  else
    Memo1.Text := 'This is a waste of time.'
end;

Body:
I thought I would try some measurements, using the Line Timer of NexusDB's Quality Suite on this D7 test program:

{$A8,B-,C+,D+,E-,F-,G+,H+,I+,J-,K-,L+,M-,N+,O-,P+,Q-,R-,S-,T-,U-,V+,W+,X+,Y+,Z1}
program semicolontest;

{$APPTYPE CONSOLE}

uses
  SysUtils;

function isThisUseful1(this : string): boolean;
var
  i: Integer;
begin
  result := false;
  try
    if this = ''
    then
      i := 0
    else
      i := 1
  except
    ;
  end;
  result := (i > 0)
end;

function isThisUseful2(this : string): boolean;
var
  i: Integer;
begin
  result := false;
  try
    if this = ''
    then
      i := 0
    else
      i := 1
  except

  end;
  result := (i > 0)
end;

var
  Input : String[20];
  i : Integer;
  Res : Boolean;

begin

   Input := 'abcdefg';

   writeln('Starting');
   for i := 1 to 1000000 do begin
     Res := isThisUseful1(Input);
     Res := isThisUseful2(Input);
   end;
   writeln('Done');
   // readln;
end.

which contains two versions of the isThisUseful function from the question, one with, and one without the semicolon in the except block.  The results of running this code (with apologies for the slightly mangled layout) are as follows:

Line    Total Time  Hit Count   Source
1       -   {$A8,B-,C+,D+,E-,F-,G+,H+,I+,J-,K-,L+,M-,N+,O-,P+,Q-,R-,S-,T-,U-,V+,W+,X+,Y+,Z1}
2       -   program semicolontest;
3       -
4       -   {$APPTYPE CONSOLE}
5       -
6       -   uses
7       -     SysUtils;
8       -
9       -   function isThisUseful1(this : string): boolean;
10      -   var
11      -     i: Integer;
12  2.807175    1,000,000   begin
13  0.761388    1,000,000     result := false;
14  2.133202    1,000,000     try
15  1.403061    1,000,000       if this = ''
16      -       then
17      -         i := 0
18      -       else
19  0.826841    1,000,000         i := 1
20      -     except
21      -       ;
22      -     end;
23  0.735419    1,000,000     result := (i > 0)
24      -   end;
25      -
26      -   function isThisUseful2(this : string): boolean;
27      -   var
28      -     i: Integer;
29  1.260030    1,000,000   begin
30  0.782293    1,000,000     result := false;
31  0.894420    1,000,000     try
32  0.820860    1,000,000       if this = ''
33      -       then
34      -         i := 0
35      -       else
36  0.873424    1,000,000         i := 1
37      -     except
38      -
39      -     end;
40  0.778922    1,000,000     result := (i > 0)
41      -   end;
42      -
43      -   var
44      -     Input : String[20];
45      -     i : Integer;
46      -     Res : Boolean;
47      -
48  1.167140    1   begin
49      -
50  0.000036    1      Input := 'abcdefg';
51      -
52  0.641347    1      writeln('Starting');
53  0.000026    1      for i := 1 to 1000000 do begin
54      -        Res := isThisUseful1(Input);
55      -        Res := isThisUseful2(Input);
56  0.669066    1,000,000      end;
57  0.402661    1      writeln('Done');
58      -      // readln;
59      -   end.
60      -

Notice that no time is recorded for line 21, the semicolon in the try ...except block, for the simple reason that, as expected, no code is generated for it.

For completeness, the following are disassemblies of isThisUseful1 and isThisUseful2

isThisUseful1:

Address Bytes   Text    Block #
00408620h       [semicolontest.dpr.12] begin
00408620h   55        push ebp  1
00408621h   8BEC          mov ebp, esp  1
00408623h   83C4F4        add esp, 0FFFFFFF4h ; (-0Ch)  1
00408626h   53        push ebx  1
00408627h   56        push esi  1
00408628h   57        push edi  1
00408629h   8945FC        mov [ebp-04h], eax    1
0040862Ch   8B45FC        mov eax, [ebp-04h]    1
0040862Fh   E87CB7FFFF        call System::LStrAddRef ;(00403DB0h)  1
00408634h   33C0          xor eax, eax  1
00408636h   55        push ebp  1
00408637h   689A864000        push offset @@6   1
0040863Ch   64FF30        push fs:[eax] 1
0040863Fh   648920        mov fs:[eax], esp 1
00408642h       [semicolontest.dpr.13] result := false;
00408642h   C645FB00          mov byte ptr [ebp-05h], 00h   1
00408646h       [semicolontest.dpr.14] try
00408646h   33C0          xor eax, eax  1
00408648h   55        push ebp  1
00408649h   6872864000        push offset @@3   1
0040864Eh   64FF30        push fs:[eax] 1
00408651h   648920        mov fs:[eax], esp 1
00408654h       [semicolontest.dpr.15] if this = ''
00408654h   837DFC00          cmp dword ptr [ebp-04h], 00h  1
00408658h   7507          jnz @@1   1
0040865Ah       [semicolontest.dpr.17] i := 0
0040865Ah   33C0          xor eax, eax  2
0040865Ch   8945F4        mov [ebp-0Ch], eax    2
0040865Fh   EB07          jmp @@2   2
00408661h       [semicolontest.dpr.19] i := 1
00408661h       @@1:
00408661h   C745F401000000        mov dword ptr [ebp-0Ch], 01h  3
00408668h       @@2:
00408668h   33C0          xor eax, eax  4
0040866Ah   5A        pop edx   4
0040866Bh   59        pop ecx   4
0040866Ch   59        pop ecx   4
0040866Dh   648910        mov fs:[eax], edx 4
00408670h   EB0A          jmp @@4   4
00408672h       @@3:
00408672h   E9DDACFFFF        jmp System::HandleAnyException ;(00403354h)   5
00408677h       [semicolontest.dpr.21] ;
00408677h   E8B8AEFFFF        call System::DoneExcept ;(00403534h)  5
0040867Ch       [semicolontest.dpr.23] result := (i > 0)
0040867Ch       @@4:
0040867Ch   837DF400          cmp dword ptr [ebp-0Ch], 00h  6
00408680h   0F9F45FB          setnle [ebp-05h]  6
00408684h   33C0          xor eax, eax  6
00408686h   5A        pop edx   6
00408687h   59        pop ecx   6
00408688h   59        pop ecx   6
00408689h   648910        mov fs:[eax], edx 6
0040868Ch   68A1864000        push offset @@7   6
00408691h       @@5:
00408691h   8D45FC        lea eax, [ebp-04h]    7
00408694h   E8BFB3FFFF        call System::LStrClr ;(00403A58h) 7
00408699h   C3        ret   7
0040869Ah       @@6:
0040869Ah   E9E1ADFFFF        jmp System::HandleFinally ;(00403480h)    8
0040869Fh   EBF0          jmp @@5   8
004086A1h       @@7:
004086A1h   8A45FB        mov al, [ebp-05h] 9
004086A4h       [semicolontest.dpr.24] end;
004086A4h   5F        pop edi   9
004086A5h   5E        pop esi   9
004086A6h   5B        pop ebx   9
004086A7h   8BE5          mov esp, ebp  9
004086A9h   5D        pop ebp   9
004086AAh   C3        ret   9

isThisUseful2:

Address Bytes   Text    Block #
00408620h       [semicolontest.dpr.12] begin
00408620h   55        push ebp  1
00408621h   8BEC          mov ebp, esp  1
00408623h   83C4F4        add esp, 0FFFFFFF4h ; (-0Ch)  1
00408626h   53        push ebx  1
00408627h   56        push esi  1
00408628h   57        push edi  1
00408629h   8945FC        mov [ebp-04h], eax    1
0040862Ch   8B45FC        mov eax, [ebp-04h]    1
0040862Fh   E87CB7FFFF        call System::LStrAddRef ;(00403DB0h)  1
00408634h   33C0          xor eax, eax  1
00408636h   55        push ebp  1
00408637h   689A864000        push offset @@6   1
0040863Ch   64FF30        push fs:[eax] 1
0040863Fh   648920        mov fs:[eax], esp 1
00408642h       [semicolontest.dpr.13] result := false;
00408642h   C645FB00          mov byte ptr [ebp-05h], 00h   1
00408646h       [semicolontest.dpr.14] try
00408646h   33C0          xor eax, eax  1
00408648h   55        push ebp  1
00408649h   6872864000        push offset @@3   1
0040864Eh   64FF30        push fs:[eax] 1
00408651h   648920        mov fs:[eax], esp 1
00408654h       [semicolontest.dpr.15] if this = ''
00408654h   837DFC00          cmp dword ptr [ebp-04h], 00h  1
00408658h   7507          jnz @@1   1
0040865Ah       [semicolontest.dpr.17] i := 0
0040865Ah   33C0          xor eax, eax  2
0040865Ch   8945F4        mov [ebp-0Ch], eax    2
0040865Fh   EB07          jmp @@2   2
00408661h       [semicolontest.dpr.19] i := 1
00408661h       @@1:
00408661h   C745F401000000        mov dword ptr [ebp-0Ch], 01h  3
00408668h       @@2:
00408668h   33C0          xor eax, eax  4
0040866Ah   5A        pop edx   4
0040866Bh   59        pop ecx   4
0040866Ch   59        pop ecx   4
0040866Dh   648910        mov fs:[eax], edx 4
00408670h   EB0A          jmp @@4   4
00408672h       @@3:
00408672h   E9DDACFFFF        jmp System::HandleAnyException ;(00403354h)   5
00408677h       [semicolontest.dpr.21] ;
00408677h   E8B8AEFFFF        call System::DoneExcept ;(00403534h)  5
0040867Ch       [semicolontest.dpr.23] result := (i > 0)
0040867Ch       @@4:
0040867Ch   837DF400          cmp dword ptr [ebp-0Ch], 00h  6
00408680h   0F9F45FB          setnle [ebp-05h]  6
00408684h   33C0          xor eax, eax  6
00408686h   5A        pop edx   6
00408687h   59        pop ecx   6
00408688h   59        pop ecx   6
00408689h   648910        mov fs:[eax], edx 6
0040868Ch   68A1864000        push offset @@7   6
00408691h       @@5:
00408691h   8D45FC        lea eax, [ebp-04h]    7
00408694h   E8BFB3FFFF        call System::LStrClr ;(00403A58h) 7
00408699h   C3        ret   7
0040869Ah       @@6:
0040869Ah   E9E1ADFFFF        jmp System::HandleFinally ;(00403480h)    8
0040869Fh   EBF0          jmp @@5   8
004086A1h       @@7:
004086A1h   8A45FB        mov al, [ebp-05h] 9
004086A4h       [semicolontest.dpr.24] end;
004086A4h   5F        pop edi   9
004086A5h   5E        pop esi   9
004086A6h   5B        pop ebx   9
004086A7h   8BE5          mov esp, ebp  9
004086A9h   5D        pop ebp   9
004086AAh   C3        ret   9

(I went cross-eyed trying to compare these myself, and wasn't going to waste my time running them past BeyondCompare).

Anyway, I think this shows that as stated by myself and others, the compiler does not generate code for a line containing only a semicolon in a try...except block, and it shouldn't do anywhere else, either, though as noted there are cases where the presence or otherwise of a semicolon changes the semantics of the code and hence the code generated.


问:
Require two identically named classes in ruby
In my rails application I connect to another ruby application foo that has a class Database in its folder /classes/database.rb and to another application bar that has another class Databse in its folder /classes/database.rb

In that application I have to put the requires in the application controller. That is done by the following code

```<code>$: << "C:\foo\
require "plug_in_foo.rb"
</code>```

in the plug_in_foo.rb there are the requires of the foo project, i.e.

```<code>require "/classes/database.rb"
</code>```

as in the foo project so for the bar project

```<code>$: << "C:\bar\
require "plug_in_bar.rb"
</code>```

and in the plug_in_bar.rb there are the requires of the bar project, i.e.

```<code>require "/classes/database.rb"
</code>```

The Database class in the bar project has its own module wrapped around it but when I try to access the class by BaRModule::Datbase.new it is recognized as an unitialized constant so I think that the require does not work.

Can someone help me with this? Is there a workaround for this?

答: you should include both of your module in your class like include BaRModule

ContentLicense: CC BY-SA 3.0

Body:
In my rails application I connect to another ruby application foo that has a class Database in its folder /classes/database.rb and to another application bar that has another class Databse in its folder /classes/database.rb

In that application I have to put the requires in the application controller. That is done by the following code

$: << "C:\foo\
require "plug_in_foo.rb"

in the plug_in_foo.rb there are the requires of the foo project, i.e.

require "/classes/database.rb"

as in the foo project so for the bar project

$: << "C:\bar\
require "plug_in_bar.rb"

and in the plug_in_bar.rb there are the requires of the bar project, i.e.

require "/classes/database.rb"

The Database class in the bar project has its own module wrapped around it but when I try to access the class by BaRModule::Datbase.new it is recognized as an unitialized constant so I think that the require does not work.

Can someone help me with this? Is there a workaround for this?


问:
AWK: dynamically change FS or RS
I cannot seem to get the trick to interchange the FS/RS variables dynamically, so that I get the following results from the input:

Input_file

```<code>header 1
header 2
{
something should not be removed
}

50

(
auto1
{
    type        good;
    remove      not useful;
}

 auto2
{
    type        good;
    keep        useful;
}

 auto3
{
    type        moderate;
    remove      not useful;
}
)
</code>```

Output_file

```<code>header 1
header 2
{
something that should not be removed
}

50

(
auto1//good
{
    type        good;//good
}

auto2//good
{
    type        good;//good
    keep        useful;
}

auto3//moderate
{
    type        moderate;//moderate
}
)
</code>```

The key things are:

There's no change is happening when the code-block {...} is not preceded by a autoX (X can be 1,2,3 etc.).

The changes should happen when autoX is followed by a codeblock {...}.

the value inside the codeblock & autoX is modified with the addition of \\good or //moderate, which needs to be read from the {...} itself.

the whole line should be removed from {...}, if it contains the phrase remove.

HINT: It might be something that can use regex and the idea explained here, with this particular example.

For now, I only have been able to meet the last requirement, with the following code:

```<code>awk ' {$1=="{"; FS=="}";} {$1!="}"; gsub("remove",""); print NR"\t\t"$0}' Input_file
</code>```

Thanks in advance, for your skill & time, to tackle this problem with awk.

答:
Here is my attempt to solve this problem:

```<code>awk '
FNR==NR{
  if($0~/auto[0-9]+/){
    found1=1
    val=$0
    next
  }
  if(found1 && $0 ~ /{/){
    found2=1
    next
  }
  if(found1 && found2 && $0 ~ /type/){
    sub(/;/,"",$NF)
    a[val]=$NF
    next
  }
  if($0 ~ /}/){
    found1=found2=val=""
  }
  next
}
found3 && /not useful/{
  next
}
/}/{
  found3=val1=""
}
found3 && /type/{
  sub($NF,$NF"//"a[val1])
}
/auto[0-9]+/ && $0 in a{
  print $0"//"a[$0]
  found3=1
  val1=$0
  next
}
1
'  Input_file  Input_file
</code>```

Explanation: Adding detailed explanation for above code here.

```<code>awk '                                      ##Starting awk program from here.
FNR==NR{                                   ##FNR==NR will be TRUE when first time Input_file is being read.
  if($0~/auto[0-9]+/){                     ##Check condition if a line is having auto string followed by digits then do following.
    found1=1                               ##Setting found1 to 1 which makes sure that the line with auto is FOUND to later logic.
    val=$0                                 ##Storing current line value to variable val here.
    next                                   ##next will skip all further statements from here.
  }
  if(found1 && $0 ~ /{/){                  ##Checking condition if found1 is SET and line has { in it then do following.
    found2=1                               ##Setting found2 value as 1 which tells program further that after auto { is also found now.
    next                                   ##next will skip all further statements from here.
  }
  if(found1 && found2 && $0 ~ /type/){     ##Checking condition if found1 and found2 are ET AND line has type in it then do following.
    sub(/;/,"",$NF)                        ##Substituting semi colon in last field with NULL.
    a[val]=$NF                             ##creating array a with variable var and its value is last column of current line.
    next                                   ##next will skip all further statements from here.
  }
  if($0 ~ /}/){                            ##Checking if line has } in it then do following, which basically means previous block is getting closed here.
    found1=found2=val=""                   ##Nullify all variables value found1, found2 and val here.
  }
  next                                     ##next will skip all further statements from here.
}
/}/{                                       ##Statements from here will be executed when 2nd time Input_file is being read, checking if line has } here.
  found3=val1=""                           ##Nullifying found3 and val1 variables here.
}
found3 && /type/{                          ##Checking if found3 is SET and line has type keyword in it then do following.
  sub($NF,$NF"//"a[val1])                  ##Substituting last field value with last field and array a value with index val1 here.
}
/auto[0-9]+/ && $0 in a{                   ##Searching string auto with digits and checking if current line is present in array a then do following.
  print $0"//"a[$0]                        ##Printing current line // and value of array a with index $0.
  found3=1                                 ##Setting found3 value to 1 here.
  val1=$0                                  ##Setting current line value to val1 here.
  next                                     ##next will skip all further statements from here.
}
1                                          ##1 will print all edited/non0-edited lines here.
'  Input_file  Input_file                  ##Mentioning Input_file names here.
</code>```

Title: AWK: dynamically change FS or RS

Body:
I cannot seem to get the trick to interchange the FS/RS variables dynamically, so that I get the following results from the input:

Input_file

header 1
header 2
{
something should not be removed
}

50

(
auto1
{
    type        good;
    remove      not useful;
}

 auto2
{
    type        good;
    keep        useful;
}

 auto3
{
    type        moderate;
    remove      not useful;
}
)

Output_file

header 1
header 2
{
something that should not be removed
}

50

(
auto1//good
{
    type        good;//good
}

auto2//good
{
    type        good;//good
    keep        useful;
}

auto3//moderate
{
    type        moderate;//moderate
}
)

The key things are:

There's no change is happening when the code-block {...} is not preceded by a autoX (X can be 1,2,3 etc.).

The changes should happen when autoX is followed by a codeblock {...}.

the value inside the codeblock & autoX is modified with the addition of \\good or //moderate, which needs to be read from the {...} itself.

the whole line should be removed from {...}, if it contains the phrase remove.

HINT: It might be something that can use regex and the idea explained here, with this particular example.

For now, I only have been able to meet the last requirement, with the following code:

awk ' {$1=="{"; FS=="}";} {$1!="}"; gsub("remove",""); print NR"\t\t"$0}' Input_file

Thanks in advance, for your skill & time, to tackle this problem with awk.

Body:
Here is my attempt to solve this problem:

awk '
FNR==NR{
  if($0~/auto[0-9]+/){
    found1=1
    val=$0
    next
  }
  if(found1 && $0 ~ /{/){
    found2=1
    next
  }
  if(found1 && found2 && $0 ~ /type/){
    sub(/;/,"",$NF)
    a[val]=$NF
    next
  }
  if($0 ~ /}/){
    found1=found2=val=""
  }
  next
}
found3 && /not useful/{
  next
}
/}/{
  found3=val1=""
}
found3 && /type/{
  sub($NF,$NF"//"a[val1])
}
/auto[0-9]+/ && $0 in a{
  print $0"//"a[$0]
  found3=1
  val1=$0
  next
}
1
'  Input_file  Input_file

Explanation: Adding detailed explanation for above code here.

awk '                                      ##Starting awk program from here.
FNR==NR{                                   ##FNR==NR will be TRUE when first time Input_file is being read.
  if($0~/auto[0-9]+/){                     ##Check condition if a line is having auto string followed by digits then do following.
    found1=1                               ##Setting found1 to 1 which makes sure that the line with auto is FOUND to later logic.
    val=$0                                 ##Storing current line value to variable val here.
    next                                   ##next will skip all further statements from here.
  }
  if(found1 && $0 ~ /{/){                  ##Checking condition if found1 is SET and line has { in it then do following.
    found2=1                               ##Setting found2 value as 1 which tells program further that after auto { is also found now.
    next                                   ##next will skip all further statements from here.
  }
  if(found1 && found2 && $0 ~ /type/){     ##Checking condition if found1 and found2 are ET AND line has type in it then do following.
    sub(/;/,"",$NF)                        ##Substituting semi colon in last field with NULL.
    a[val]=$NF                             ##creating array a with variable var and its value is last column of current line.
    next                                   ##next will skip all further statements from here.
  }
  if($0 ~ /}/){                            ##Checking if line has } in it then do following, which basically means previous block is getting closed here.
    found1=found2=val=""                   ##Nullify all variables value found1, found2 and val here.
  }
  next                                     ##next will skip all further statements from here.
}
/}/{                                       ##Statements from here will be executed when 2nd time Input_file is being read, checking if line has } here.
  found3=val1=""                           ##Nullifying found3 and val1 variables here.
}
found3 && /type/{                          ##Checking if found3 is SET and line has type keyword in it then do following.
  sub($NF,$NF"//"a[val1])                  ##Substituting last field value with last field and array a value with index val1 here.
}
/auto[0-9]+/ && $0 in a{                   ##Searching string auto with digits and checking if current line is present in array a then do following.
  print $0"//"a[$0]                        ##Printing current line // and value of array a with index $0.
  found3=1                                 ##Setting found3 value to 1 here.
  val1=$0                                  ##Setting current line value to val1 here.
  next                                     ##next will skip all further statements from here.
}
1                                          ##1 will print all edited/non0-edited lines here.
'  Input_file  Input_file                  ##Mentioning Input_file names here.


问:
javasript in angular 8
There's a solution on js -

codepen.io/skovtun/pen/VwLvXPB

Can't make an analog for Angular8+.

I need the center block to have a fixed width (1200px), and it is evaluated and compressed by the left, right and both sidebars immediately when they are opened. They should not overlap with the content.

答:
You can achieve this with pure CSS.

You haven't specified what the requirements are, but you can use flexbox like the below example to achieve a max-width main container flanked by 2 compressing sidebars.

body {
  margin: 0;
}

.wrapper{
  display: flex;
}

main {
  width: 1200px;
  padding: 20px;
  background-color: #f1f1f1;
}

.sidebar {
  flex-grow: 1;
  height: 100vh;
  padding: 0 15px;
}

.sidebar-left {
  border-right: 1px solid #06A52B;
}

.sidebar-right {
  border-left: 1px solid #06A52B;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <aside class="sidebar sidebar-left">
    <h2>Left sidebar</h2>
    <p>Add content here</p>
  </aside>
  <main>
    <h1>Max width of this block is 1200px</h1>
  </main>
  <aside class="sidebar sidebar-right">
    <h2>Right sidebar</h2>
    <p>Add content here</p>
  </aside>
</div></code>```

Title: javasript in angular 8

Body:
You can achieve this with pure CSS.

You haven't specified what the requirements are, but you can use flexbox like the below example to achieve a max-width main container flanked by 2 compressing sidebars.

body {
  margin: 0;
}

.wrapper{
  display: flex;
}

main {
  width: 1200px;
  padding: 20px;
  background-color: #f1f1f1;
}

.sidebar {
  flex-grow: 1;
  height: 100vh;
  padding: 0 15px;
}

.sidebar-left {
  border-right: 1px solid #06A52B;
}

.sidebar-right {
  border-left: 1px solid #06A52B;
}

<div class="wrapper">
  <aside class="sidebar sidebar-left">
    <h2>Left sidebar</h2>
    <p>Add content here</p>
  </aside>
  <main>
    <h1>Max width of this block is 1200px</h1>
  </main>
  <aside class="sidebar sidebar-right">
    <h2>Right sidebar</h2>
    <p>Add content here</p>
  </aside>
</div>


问:
NodeJS, promises, streams - processing large CSV files
I need to build a function for processing large CSV files for use in a bluebird.map() call. Given the potential sizes of the file, I'd like to use streaming.

This function should accept a stream (a CSV file) and a function (that processes the chunks from the stream) and return a promise when the file is read to end (resolved) or errors (rejected).

So, I start with:

```<code>'use strict';

var _ = require('lodash');
var promise = require('bluebird');
var csv = require('csv');
var stream = require('stream');

var pgp = require('pg-promise')({promiseLib: promise});

api.parsers.processCsvStream = function(passedStream, processor) {

  var parser = csv.parse(passedStream, {trim: true});
  passedStream.pipe(parser);

  // use readable or data event?
  parser.on('readable', function() {
    // call processor, which may be async
    // how do I throttle the amount of promises generated
  });

  var db = pgp(api.config.mailroom.fileMakerDbConfig);

  return new Promise(function(resolve, reject) {
    parser.on('end', resolve);
    parser.on('error', reject);
  });

}
</code>```

Now, I have two inter-related issues:

I need to throttle the actual amount of data being processed, so as to not create memory pressures.

The function passed as the processor param is going to often be async, such as saving the contents of the file to the db via a library that is promise-based (right now: pg-promise). As such, it will create a promise in memory and move on, repeatedly.

The pg-promise library has functions to manage this, like page(), but I'm not able to wrap my ahead around how to mix stream event handlers with these promise methods. Right now, I return a promise in the handler for readable section after each read(), which means I create a huge amount of promised database operations and eventually fault out because I hit a process memory limit.

Does anyone have a working example of this that I can use as a jumping point?

UPDATE: Probably more than one way to skin the cat, but this works:

```<code>'use strict';

var _ = require('lodash');
var promise = require('bluebird');
var csv = require('csv');
var stream = require('stream');

var pgp = require('pg-promise')({promiseLib: promise});

api.parsers.processCsvStream = function(passedStream, processor) {

  // some checks trimmed out for example

  var db = pgp(api.config.mailroom.fileMakerDbConfig);
  var parser = csv.parse(passedStream, {trim: true});
  passedStream.pipe(parser);

  var readDataFromStream = function(index, data, delay) {
    var records = [];
    var record;
    do {
      record = parser.read();
      if(record != null)
        records.push(record);
    } while(record != null && (records.length < api.config.mailroom.fileParserConcurrency))
    parser.pause();

    if(records.length)
      return records;
  };

  var processData = function(index, data, delay) {
    console.log('processData(' + index + ') > data: ', data);
    parser.resume();
  };

  parser.on('readable', function() {
    db.task(function(tsk) {
      this.page(readDataFromStream, processData);
    });
  });

  return new Promise(function(resolve, reject) {
    parser.on('end', resolve);
    parser.on('error', reject);
  });
}
</code>```

Anyone sees a potential problem with this approach?

答:
I found a slightly better way of doing the same thing; with more control. This is a minimal skeleton with precise parallelism control. With parallel value as one all records are processed in sequence without having the entire file in memory, we can increase parallel value for faster processing.

```<code>      const csv = require('csv');
      const csvParser = require('csv-parser')
      const fs = require('fs');

      const readStream = fs.createReadStream('IN');
      const writeStream = fs.createWriteStream('OUT');

      const transform = csv.transform({ parallel: 1 }, (record, done) => {
                                           asyncTask(...) // return Promise
                                           .then(result => {
                                             // ... do something when success
                                             return done(null, record);
                                           }, (err) => {
                                             // ... do something when error
                                             return done(null, record);
                                           })
                                       }
                                     );

      readStream
      .pipe(csvParser())
      .pipe(transform)
      .pipe(csv.stringify())
      .pipe(writeStream);
</code>```

This allows doing an async task for each record.

To return a promise instead we can return with an empty promise, and complete it when stream finishes.

```<code>    .on('end',function() {
      //do something wiht csvData
      console.log(csvData);
    });
</code>```

Body:
I need to build a function for processing large CSV files for use in a bluebird.map() call. Given the potential sizes of the file, I'd like to use streaming.

This function should accept a stream (a CSV file) and a function (that processes the chunks from the stream) and return a promise when the file is read to end (resolved) or errors (rejected).

So, I start with:

'use strict';

var _ = require('lodash');
var promise = require('bluebird');
var csv = require('csv');
var stream = require('stream');

var pgp = require('pg-promise')({promiseLib: promise});

api.parsers.processCsvStream = function(passedStream, processor) {

  var parser = csv.parse(passedStream, {trim: true});
  passedStream.pipe(parser);

  // use readable or data event?
  parser.on('readable', function() {
    // call processor, which may be async
    // how do I throttle the amount of promises generated
  });

  var db = pgp(api.config.mailroom.fileMakerDbConfig);

  return new Promise(function(resolve, reject) {
    parser.on('end', resolve);
    parser.on('error', reject);
  });

}

Now, I have two inter-related issues:

I need to throttle the actual amount of data being processed, so as to not create memory pressures.

The function passed as the processor param is going to often be async, such as saving the contents of the file to the db via a library that is promise-based (right now: pg-promise). As such, it will create a promise in memory and move on, repeatedly.

The pg-promise library has functions to manage this, like page(), but I'm not able to wrap my ahead around how to mix stream event handlers with these promise methods. Right now, I return a promise in the handler for readable section after each read(), which means I create a huge amount of promised database operations and eventually fault out because I hit a process memory limit.

Does anyone have a working example of this that I can use as a jumping point?

UPDATE: Probably more than one way to skin the cat, but this works:

'use strict';

var _ = require('lodash');
var promise = require('bluebird');
var csv = require('csv');
var stream = require('stream');

var pgp = require('pg-promise')({promiseLib: promise});

api.parsers.processCsvStream = function(passedStream, processor) {

  // some checks trimmed out for example

  var db = pgp(api.config.mailroom.fileMakerDbConfig);
  var parser = csv.parse(passedStream, {trim: true});
  passedStream.pipe(parser);

  var readDataFromStream = function(index, data, delay) {
    var records = [];
    var record;
    do {
      record = parser.read();
      if(record != null)
        records.push(record);
    } while(record != null && (records.length < api.config.mailroom.fileParserConcurrency))
    parser.pause();

    if(records.length)
      return records;
  };

  var processData = function(index, data, delay) {
    console.log('processData(' + index + ') > data: ', data);
    parser.resume();
  };

  parser.on('readable', function() {
    db.task(function(tsk) {
      this.page(readDataFromStream, processData);
    });
  });

  return new Promise(function(resolve, reject) {
    parser.on('end', resolve);
    parser.on('error', reject);
  });
}

Anyone sees a potential problem with this approach?

Body:
I found a slightly better way of doing the same thing; with more control. This is a minimal skeleton with precise parallelism control. With parallel value as one all records are processed in sequence without having the entire file in memory, we can increase parallel value for faster processing.

      const csv = require('csv');
      const csvParser = require('csv-parser')
      const fs = require('fs');

      const readStream = fs.createReadStream('IN');
      const writeStream = fs.createWriteStream('OUT');

      const transform = csv.transform({ parallel: 1 }, (record, done) => {
                                           asyncTask(...) // return Promise
                                           .then(result => {
                                             // ... do something when success
                                             return done(null, record);
                                           }, (err) => {
                                             // ... do something when error
                                             return done(null, record);
                                           })
                                       }
                                     );

      readStream
      .pipe(csvParser())
      .pipe(transform)
      .pipe(csv.stringify())
      .pipe(writeStream);

This allows doing an async task for each record.

To return a promise instead we can return with an empty promise, and complete it when stream finishes.

    .on('end',function() {
      //do something wiht csvData
      console.log(csvData);
    });


问:
Trying to change all tabs to a set number of spaces, K&R Exercise 1-20
I have a solution that I'm relatively sure should work, however, when I run it given an input such as:

```<code>This is\ta test.
^^^^^^^^^^^^^^^^
</code>```

I get an output like this:

```<code>This is
^^^^^^^^^^^
</code>```

This is the solution I've written, and I'm almost certain it should work; it makes sense logically, but there's something that just isn't adding up.

```<code>#include <stdio.h>

#define MAX_SIZE 1000
#define TAB_STOP 4

char line[MAX_SIZE];
int getline_(void);

int main()
{
  int c, len;
  extern char longest[];

  while ((len = getline_()) > 0)
    printf("Line: %s", line);

  return 0;
}

int getline_(void)
{
  int chr, index;
  extern char line[];
  int x;

  for (index = 0; index < (MAX_SIZE - 1)
         && ((chr = getchar()) != EOF) && chr != '\n'; ++index) {
    if (chr == '\t') {
      for (x = 0; x < TAB_STOP && index < MAX_SIZE - 5; ++x) {
        line[index + x] = ' ';
        printf("%d\n", index);
      }
      index = index + x;
    }
    else
      line[index] = chr;
  }
  if (chr == '\n') {
    line[index] = chr;
    ++index;
  }

  line[index] = '\0';
  return index;
}
</code>```

答:
In the case where chr == '\t' you are incrementing index twice:

the first time with index = index + x;

the second time within the for statement ++index

An easy, dirty, trick would be to change the first increment to index = index + x - 1;.

I fully agree with @Sneftel that it would be better to only increment index with the correct value. That means not increment it within a for statement. And do the increment once in each alternative of the if… else blocks with the right value.

Body:
I have a solution that I'm relatively sure should work, however, when I run it given an input such as:

This is\ta test.
^^^^^^^^^^^^^^^^

I get an output like this:

This is
^^^^^^^^^^^

This is the solution I've written, and I'm almost certain it should work; it makes sense logically, but there's something that just isn't adding up.

#include <stdio.h>

#define MAX_SIZE 1000
#define TAB_STOP 4

char line[MAX_SIZE];
int getline_(void);

int main()
{
  int c, len;
  extern char longest[];

  while ((len = getline_()) > 0)
    printf("Line: %s", line);

  return 0;
}

int getline_(void)
{
  int chr, index;
  extern char line[];
  int x;

  for (index = 0; index < (MAX_SIZE - 1)
         && ((chr = getchar()) != EOF) && chr != '\n'; ++index) {
    if (chr == '\t') {
      for (x = 0; x < TAB_STOP && index < MAX_SIZE - 5; ++x) {
        line[index + x] = ' ';
        printf("%d\n", index);
      }
      index = index + x;
    }
    else
      line[index] = chr;
  }
  if (chr == '\n') {
    line[index] = chr;
    ++index;
  }

  line[index] = '\0';
  return index;
}


问:
How to stop a setTimeout loop?
I'm trying to build a loading indicator with a image sprite and I came up with this function

```<code>function setBgPosition() {
   var c = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
       Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c<numbers.length)
        {
            setTimeout(run, 200);
        }else
        {
            setBgPosition();
        }
    }
    setTimeout(run, 200);
}
</code>```

so the out put is looks like this

http://jsfiddle.net/TTkre/

I had to use setBgPosition(); inside else to keep this running in a loop so now my problem is how to stop this loop once I want [load finished]?

答:
var myVar = null;

if(myVar)
   clearTimeout(myVar);

myVar = setTimeout(function(){ alert("Hello"); }, 3000);
```

Title: How to stop a setTimeout loop?

Body:
I'm trying to build a loading indicator with a image sprite and I came up with this function

function setBgPosition() {
   var c = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
       Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c<numbers.length)
        {
            setTimeout(run, 200);
        }else
        {
            setBgPosition();
        }
    }
    setTimeout(run, 200);
}

so the out put is looks like this

http://jsfiddle.net/TTkre/

I had to use setBgPosition(); inside else to keep this running in a loop so now my problem is how to stop this loop once I want [load finished]?


问:
Does Android HoneyComb support multiuser restricted account?
a customer ordered us a tablet application, but they need a lot of access restriction to lock device functions such as:

Permit datas transfer only inside the application not outside

Restricted user access on the device (something close to admin and normal user permissions)

A framework/API that permit to create an internal mail reader/sender

Public API of iOS makes impossible to fulfill those requirements. I was wondering if Android makes life easier when there are those kind of restriction.

UPDATE: To make understand better the field of use. I'm talking about an application that "force" the device to be used just only with that application for an Enterprise use. The app is just like a CRM but the device should be blocked in some functions to make users only work with them and NOT playing or use facebook, market etc.

答:
Not sure you can achiev all of those, but you should look into the device policy for android here and here.

1) Not sure what you mean by point 1. If you mean controlling all data transfer from the device, you might be a in a bind considering the only way to get a firewall running on android is by rooting the device. Perhaps you could look into writing a custom launcher/home like KidZone that only shows approved apps? - Not nearly as secure, though.

2) Honeycomb, so far, doesn't have multi-user support - though you can have multiple google accounts registered. The custom launcher could help in this regard though.

3) I don't see the point of doing this unless they already have a custom mail infrastructure in place. Otherwise just go with exchange.


问:
FM to convert time from 24hr to 12hr format?
I have to format a DateTime which is in UTC based on user settings which include its time zone (CET/IST etc) and time format (24hr/12hr).

I could find CONVERT TIME STAMP statement which takes only TIME ZONE as a parameter and does that conversion:

```<code>DATA: lv_timestampl TYPE timestampl VALUE '20200219095959.0000000',
      lv_date       TYPE d,
      lv_time       TYPE t.
CONVERT TIME STAMP lv_timestampl TIME ZONE sy-zonlo INTO DATE lv_date TIME lv_time.
</code>```

My objective is to convert this lv_timestampl based on TimeZone and TimeFormat together.

PS: I could just do that -12 manipulation on lv_time after CONVERT TIME STAMP statement and append PM/AM but I am looking for a standard way of doing it.

答:
OK, let me be your living help today, if you were not able to find string templates help.

Template to convert timestamp to UTC:

```<code>DATA(ld_tims_utc) = |{ lv_timestampl TIMESTAMP = ENVIRONMENT }|.
</code>```

returns

19.02.2020 09:59:59,0000000

Template to convert timestamp to explicitly specified timezone:

```<code>DATA(ld_tims_zone) = |{ lv_timestampl TIMESTAMP = ENVIRONMENT TIMEZONE = 'CET' }|.
</code>```

returns

19.02.2020 10:59:59,0000000

Getting time and date from timestamp (not timestampl, so conversion needed):

```<code>cl_abap_tstmp=>systemtstmp_utc2syst( EXPORTING
                                       utc_tstmp = CONV timestamp( lv_timestampl )
                                     IMPORTING
                                       syst_date = lv_date
                                       syst_time = lv_time ).
</code>```

Output in 12h format:

```<code>SET COUNTRY 'US'.
DATA(time_us) = |{ lv_time TIME = ENVIRONMENT }|. "gives 01:55:43 PM
</code>```

Output in 24h format:

```<code>SET COUNTRY 'DE'.
DATA(time_de) = |{ lv_time TIME = ENVIRONMENT }|. "gives 13:55:43
</code>```

For the output of AM/PM time formats, they need to be maintained in field TIMEFM of table USR01 aka User settings or table t005x aka Country settings (tcode OY01).

Body:
I have to format a DateTime which is in UTC based on user settings which include its time zone (CET/IST etc) and time format (24hr/12hr).

I could find CONVERT TIME STAMP statement which takes only TIME ZONE as a parameter and does that conversion:

DATA: lv_timestampl TYPE timestampl VALUE '20200219095959.0000000',
      lv_date       TYPE d,
      lv_time       TYPE t.
CONVERT TIME STAMP lv_timestampl TIME ZONE sy-zonlo INTO DATE lv_date TIME lv_time.

My objective is to convert this lv_timestampl based on TimeZone and TimeFormat together.

PS: I could just do that -12 manipulation on lv_time after CONVERT TIME STAMP statement and append PM/AM but I am looking for a standard way of doing it.

Body:
OK, let me be your living help today, if you were not able to find string templates help.

Template to convert timestamp to UTC:

DATA(ld_tims_utc) = |{ lv_timestampl TIMESTAMP = ENVIRONMENT }|.

returns

19.02.2020 09:59:59,0000000

Template to convert timestamp to explicitly specified timezone:

DATA(ld_tims_zone) = |{ lv_timestampl TIMESTAMP = ENVIRONMENT TIMEZONE = 'CET' }|.

returns

19.02.2020 10:59:59,0000000

Getting time and date from timestamp (not timestampl, so conversion needed):

cl_abap_tstmp=>systemtstmp_utc2syst( EXPORTING
                                       utc_tstmp = CONV timestamp( lv_timestampl )
                                     IMPORTING
                                       syst_date = lv_date
                                       syst_time = lv_time ).

Output in 12h format:

SET COUNTRY 'US'.
DATA(time_us) = |{ lv_time TIME = ENVIRONMENT }|. "gives 01:55:43 PM

Output in 24h format:

SET COUNTRY 'DE'.
DATA(time_de) = |{ lv_time TIME = ENVIRONMENT }|. "gives 13:55:43

For the output of AM/PM time formats, they need to be maintained in field TIMEFM of table USR01 aka User settings or table t005x aka Country settings (tcode OY01).


问:
how to get the caller's filename, method name in python
for example, a.boo method calls b.foo method.  In b.foo method, how can I get a's file name (I don't want to pass __file__ to b.foo method)...

答:
Python 3.5+

One-liner

To get the full filename (with path and file extension), use in the callee:

```<code>import inspect
filename = inspect.stack()[1].filename
</code>```

Full filename vs filename only

To retrieve the caller's filename use inspect.stack(). Additionally, the following code also trims the path at the beginning and the file extension at the end of the full filename:

```<code># Callee.py
import inspect
import os.path

def get_caller_info():
  # first get the full filename (including path and file extension)
  caller_frame = inspect.stack()[1]
  caller_filename_full = caller_frame.filename

  # now get rid of the directory (via basename)
  # then split filename and extension (via splitext)
  caller_filename_only = os.path.splitext(os.path.basename(caller_filename_full))[0]

  # return both filename versions as tuple
  return caller_filename_full, caller_filename_only
</code>```

It can then be used like so:

```<code># Caller.py
import callee

filename_full, filename_only = callee.get_caller_info()
print(f"> Filename full: {filename_full}")
print(f"> Filename only: {filename_only}")

# Output
# > Filename full: /workspaces/python/caller_filename/caller.py
# > Filename only: caller
</code>```

Official docs

os.path.basename(): to remove the path from the filename (still includes the extension)

os.path.splitext(): to split the the filename and the file extension

Body:
Python 3.5+

One-liner

To get the full filename (with path and file extension), use in the callee:

import inspect
filename = inspect.stack()[1].filename

Full filename vs filename only

To retrieve the caller's filename use inspect.stack(). Additionally, the following code also trims the path at the beginning and the file extension at the end of the full filename:

# Callee.py
import inspect
import os.path

def get_caller_info():
  # first get the full filename (including path and file extension)
  caller_frame = inspect.stack()[1]
  caller_filename_full = caller_frame.filename

  # now get rid of the directory (via basename)
  # then split filename and extension (via splitext)
  caller_filename_only = os.path.splitext(os.path.basename(caller_filename_full))[0]

  # return both filename versions as tuple
  return caller_filename_full, caller_filename_only

It can then be used like so:

# Caller.py
import callee

filename_full, filename_only = callee.get_caller_info()
print(f"> Filename full: {filename_full}")
print(f"> Filename only: {filename_only}")

# Output
# > Filename full: /workspaces/python/caller_filename/caller.py
# > Filename only: caller

Official docs

os.path.basename(): to remove the path from the filename (still includes the extension)

os.path.splitext(): to split the the filename and the file extension


问:
How to prevent escape of a ~ (tilde) character in LaTeX document using R markdown and pandoc?
I am preapring a scientific article manuscript using R Markdown. My R Markdown file is first converted to Markdown by knitr and then to LaTeX code by pandoc.

In LaTeX, the ~ character is used to indicate a non-breaking space. It is considered good style by some journals to use the ~ character in front of \ref or \cite. For instance, LaTeX code like Section~\ref{...} and Figure~\ref{...} or rather Sect.~\ref{...} and Fig.~\ref{...} is expected by my journal.

Trying to use R Markdown to generate LaTeX code as close as possible to the journal's guidelines, I try to use Sect.~\ref{...}, but this is converted to Sect.\textasciitilde{}\ref{...} by pandoc.

How can I prevent pandoc escaping the ~ character to \textasciitilde{} to obtain the valid LaTeX?

答:
I have found in the pandoc manual (1, 2) that using Sect.\ \ref{...} solves the problem:

A backslash-escaped space is parsed as a nonbreaking space. It will appear
  in TeX output as ~ and in HTML and XML as \  or \ .

Sect.\ \ref{...} in the Markdown file is compiled to Sect.~\ref{...} in the LaTeX file as intended.

Body:
I have found in the pandoc manual (1, 2) that using Sect.\ \ref{...} solves the problem:

A backslash-escaped space is parsed as a nonbreaking space. It will appear
  in TeX output as ~ and in HTML and XML as \&#160; or \&nbsp;.

Sect.\ \ref{...} in the Markdown file is compiled to Sect.~\ref{...} in the LaTeX file as intended.


问:
Getting the angle from 3 vectors, without excluding non-reflex of obtuse angles
So I struggled last two days and found many answers but I have modified one

```<code>findAngle(c, b, a) {

    const ab = {x: b.x - a.x, y: b.y - a.y};
    const cb = {x: b.x - c.x, y: b.y - c.y};

    const dot = (ab.x * cb.x + ab.y * cb.y); // dot product
    const cross = (ab.x * cb.y - ab.y * cb.x); // cross product

    let alpha = Math.atan2(cross, dot);
    if (alpha < 0) {
      alpha = (Math.PI * 2 + alpha);
    }
    return alpha;
}
</code>```

im not sure its right, I don't like the alpha < 0 portion can anyone suggest a better opinion

答:
// assuming that b is the point at which you want to find the angle (formed by vectors bc and ba)
const angle = (c, b, a) => {
  const bc = {x: c.x - b.x, y: c.y - b.y};
  const ba = {x: a.x - b.x, y: a.y - b.y};
  // the cosine of the angle between the two vectors is their dot product divided by the product of their magnitudes
  const cos = (bc.x * ba.x + bc.y * ba.y) / (Math.hypot(bc.x, bc.y) * Math.hypot(ba.x, ba.y));
  // return the angle in degrees
  return 180 * Math.acos(cos) / Math.PI;
}
console.log(angle({x: 3, y: 4}, {x: 0, y: 0}, {x: -3, y: -4})); // the angle between two opposite vectors
console.log(angle({x: 0, y: 4}, {x: 0, y: 0}, {x: 4, y: 0})); // the angle between two perpendicular vectors
console.log(angle({x: 3, y: 4}, {x: 0, y: 0}, {x: 4, y: 3}));```

Body:
So I struggled last two days and found many answers but I have modified one

findAngle(c, b, a) {

    const ab = {x: b.x - a.x, y: b.y - a.y};
    const cb = {x: b.x - c.x, y: b.y - c.y};

    const dot = (ab.x * cb.x + ab.y * cb.y); // dot product
    const cross = (ab.x * cb.y - ab.y * cb.x); // cross product

    let alpha = Math.atan2(cross, dot);
    if (alpha < 0) {
      alpha = (Math.PI * 2 + alpha);
    }
    return alpha;
}

im not sure its right, I don't like the alpha < 0 portion can anyone suggest a better opinion


问:
Is there any SQLite Manager for MAC OS X which is able to show ER Diagram?
Is there any SQLite Manager for MAC OS X which is able to show ER Diagram (Relationship between tables)?</p>

答: I use Visual Paradigm, there's a free version you can use :) Also has a Windows version.</p>

ContentLicense: CC BY-SA 2.5


问:
error :Unable to acquire a lockedBuffer, very likely client tries to lock more than maxImages buffers
I am using camera2 api for capturing image and displaying in thumnail .Everything is working fine in all devices but when using Micromax Q382 device then in thumnail preview its displaying black image.I am getting below Issue

```<code>Unable to acquire a lockedBuffer, very likely client tries to lock more than maxImages buffers
</code>```

i am using below code for capture listerner callback

```<code>final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback()
        {

            @Override
            public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request,
                                           TotalCaptureResult result)
            {

                super.onCaptureCompleted(session, request, result);

                startPreview();
            }

        };

        mCameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback()
        {

            @Override
            public void onConfigured(CameraCaptureSession session)
            {

                try {
                    session.capture(captureBuilder.build(), captureListener, backgroudHandler);
                } catch (CameraAccessException e) {
                    AppLogger.exception(myContext, getClass().getSimpleName(), e);
                    // e.printStackTrace();
                }
            }

            @Override
            public void onConfigureFailed(CameraCaptureSession session)
            {

            }
        }, backgroudHandler);

    } catch (CameraAccessException e) {
        AppLogger.exception(myContext, getClass().getSimpleName(), e);
        // e.printStackTrace();
    }
</code>```

and below code using for OnImageAvailableListener

```<code>ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener()
        {

            @Override
            public void onImageAvailable(ImageReader reader)
            {

                Image image = null;
                try {
                    image = reader.acquireLatestImage();
                    // ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    // final byte[] bytes = new byte[buffer.capacity()];

                    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    final byte[] bytes = new byte[buffer.remaining()];

                    buffer.get(bytes);
                    save(bytes);
                    buffer.clear();
                    runOnUiThread(new Runnable()
                    {

                        @Override
                        public void run()
                        {
                            mThumbnail.setVisibility(View.VISIBLE);
                            filePathLabel.setVisibility(View.VISIBLE);
                            filePathValue.setText(file.getAbsolutePath());

                            Bitmap bmp =
                                    UtilityMethods.getScaledBitmap(CameraImageTestActivityLoliipop.this, bytes);
                            mThumbnail.setImageBitmap(bmp);
                        }
                    });

                } catch (FileNotFoundException e) {
                    AppLogger.exception(myContext, getClass().getSimpleName(), e);
                    // e.printStackTrace();
                } catch (IOException e) {
                    AppLogger.exception(myContext, getClass().getSimpleName(), e);
                    // e.printStackTrace();
                } finally {
                    if (image != null) {
                        image.close();
                    }
                }
            }
</code>```

答:
From the documentation of ImageReader.acquireLatestImage():

Acquire the latest Image from the ImageReader's queue, dropping older
  images. Returns null if no new image is available. This operation will
  acquire all the images possible from the ImageReader, but close() all
  images that aren't the latest.

This function is recommended to use
  over acquireNextImage() for most use-cases, as it's more suited for
  real-time processing. Note that maxImages should be at least 2 for
  acquireLatestImage() to be any different than acquireNextImage() -
  discarding all-but-the-newest Image requires temporarily acquiring two
  Images at once.

Thus, for real-time processing use:

ImageReader.newInstance(..., maxImages = 2) with

imageReader.acquireLatestImage()

Of if your use-case is different (e.g. batch/background processing), use e.g.:

ImageReader.newInstance(..., maxImages = 1) with

imageReader.acquireNextImage()

Be aware, that (from documentation of acquireNextImage():

This operation will fail by throwing an IllegalStateException if
  maxImages have been acquired with acquireNextImage() or
  acquireLatestImage(). In particular a sequence of acquireNextImage()
  or acquireLatestImage() calls greater than maxImages without calling
  close() in-between will exhaust the underlying queue. At such a time,
  IllegalStateException will be thrown until more images are released
  with close().

Body:
I am using camera2 api for capturing image and displaying in thumnail .Everything is working fine in all devices but when using Micromax Q382 device then in thumnail preview its displaying black image.I am getting below Issue

Unable to acquire a lockedBuffer, very likely client tries to lock more than maxImages buffers

i am using below code for capture listerner callback

final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback()
        {

            @Override
            public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request,
                                           TotalCaptureResult result)
            {

                super.onCaptureCompleted(session, request, result);

                startPreview();
            }

        };

        mCameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback()
        {

            @Override
            public void onConfigured(CameraCaptureSession session)
            {

                try {
                    session.capture(captureBuilder.build(), captureListener, backgroudHandler);
                } catch (CameraAccessException e) {
                    AppLogger.exception(myContext, getClass().getSimpleName(), e);
                    // e.printStackTrace();
                }
            }

            @Override
            public void onConfigureFailed(CameraCaptureSession session)
            {

            }
        }, backgroudHandler);

    } catch (CameraAccessException e) {
        AppLogger.exception(myContext, getClass().getSimpleName(), e);
        // e.printStackTrace();
    }

and below code using for OnImageAvailableListener

ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener()
        {

            @Override
            public void onImageAvailable(ImageReader reader)
            {

                Image image = null;
                try {
                    image = reader.acquireLatestImage();
                    // ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    // final byte[] bytes = new byte[buffer.capacity()];

                    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    final byte[] bytes = new byte[buffer.remaining()];

                    buffer.get(bytes);
                    save(bytes);
                    buffer.clear();
                    runOnUiThread(new Runnable()
                    {

                        @Override
                        public void run()
                        {
                            mThumbnail.setVisibility(View.VISIBLE);
                            filePathLabel.setVisibility(View.VISIBLE);
                            filePathValue.setText(file.getAbsolutePath());

                            Bitmap bmp =
                                    UtilityMethods.getScaledBitmap(CameraImageTestActivityLoliipop.this, bytes);
                            mThumbnail.setImageBitmap(bmp);
                        }
                    });

                } catch (FileNotFoundException e) {
                    AppLogger.exception(myContext, getClass().getSimpleName(), e);
                    // e.printStackTrace();
                } catch (IOException e) {
                    AppLogger.exception(myContext, getClass().getSimpleName(), e);
                    // e.printStackTrace();
                } finally {
                    if (image != null) {
                        image.close();
                    }
                }
            }


问:
OpenGLRenderer: Davey
I have noticed that from time to time, android shows the following log message:

```<code>I/OpenGLRenderer( 4958): Davey! duration=1923ms; Flags=1, IntendedVsync=12247...
</code>```

Does anyone know the reason why my OpenGLRenderer is calling Davey!?

答:
"Davey" is a transliteration of the Russian "Дава́й"

It means "come on!" and is an expression used to mean anything from "GO!" (in the sense of 'watch out!') to "COME ON!!!" (in the sense of 'hurry up! go!')

The programmer adding this was probably not Russian but making some kind of Slavic language joke.

Title: OpenGLRenderer: Davey

Body:
I have noticed that from time to time, android shows the following log message:

I/OpenGLRenderer( 4958): Davey! duration=1923ms; Flags=1, IntendedVsync=12247...

Does anyone know the reason why my OpenGLRenderer is calling Davey!?


问:
How to find .pc files for pkg-config via Conan and CMake
How can I make pkg-config find both dependencies installed via Conan AND dependencies that are not in Conan?

My target package is built using CMake and finds its dependencies using pkg-config with pkg_check_modules(). One of the dependencies (glib-2.0) is installed via Conan, another (libsecret-1) isn't, as there's no package.

In my conanfile I'm configuring the pkg-config_installer as a build requirement (self.build_requires("pkg-config_installer/0.29.2@bincrafters/stable"). When building the package, CMake correctly invokes this pkg-config.

As a result, pkg-config finds glib just fine, but it cannot find libsecret. I assume it finds .pc files for dependencies installed via Conan, but doesn't find libsecret-1.pc, which is located in /usr/lib/pkgconfig/ on my system.

I tried telling Conan's CMake tool to use this path: tools.PkgConfig("libsecret-1").variables["pcfiledir"] tells me where it is and the CMake tool's configure method has a pkg_config_paths parameter. Unfortunately, this changes nothing.

答:
The following steps made it work for me:

set the PKG_CONFIG_PATH environment variable to the pcfiledir found by tools.PkgConfig

do not to pass any pkg_config_paths to tools.CMake.configure(), it doesn't handle absolute paths well and conflicts with the environment variable

add the system-wide installed lib (secret-1 in my case) to cpp_info.system_libs in the package_info step

Thanks @uilianries for the helpful comment!


问:
TS2339: Property 'sort' does not exist on type 'BehaviorSubject<AbstractControl[]
I am looking to create a dynamic table using angular material where i can add/remove data dynamically.
Being very new to Angular , i have referred follwing stackblitz to create the table.

https://stackblitz.com/edit/angular-material-editable-table-fazhbc

While all my changes work - i am not able to sort the data at

```<code> ngAfterViewInit() {
    this.dataSource.sort = this.matSort;
  }
</code>```

The error i get
TS2339:  Property 'sort' does not exist on type 'BehaviorSubject<AbstractControl[]

is the sorting isn't supported like in material table data source or am i missing something ?

答:
You can think of this as a news reporter talking on TV and giving latest updates to all similarly Behaviour Subject pass latest data.

Add one service as myService and add following code
public myData: BehaviorSubject = new BehaviorSubject([]); updateData(data): void { this.myData.next(data); }

then call updateDatafrom where you want to send data to others. this.myService.updateData("Test"); You can pass any type of data here like object,array etc. Then on other component where you want this data write following code this.myService.myData.subscribe((data) => { console.log(data); }); You will get data. You can write above in any component where you want data.

Body:
I am looking to create a dynamic table using angular material where i can add/remove data dynamically.
Being very new to Angular , i have referred follwing stackblitz to create the table.

https://stackblitz.com/edit/angular-material-editable-table-fazhbc

While all my changes work - i am not able to sort the data at

 ngAfterViewInit() {
    this.dataSource.sort = this.matSort;
  }

The error i get
TS2339:  Property 'sort' does not exist on type 'BehaviorSubject<AbstractControl[]

is the sorting isn't supported like in material table data source or am i missing something ?


问:
VirtualBox Cannot register the hard disk already exists
I created a virtual disk file VM_1_Ubuntu.vdi. Then I moved it into another folder. I tried to update VM settings (right click on virtual machine -> settings -> Storage -> Controller SATA tab, VM_1_Ubuntu.vdi path). I wanted to set a new path.

It says
Cannot register the hard disk already exists

答:
The solution that worked for me is as follows:

Make sure VirtualBox Manager is not running.

Back up the files  ~\.VirtualBox\VirtualBox.xml and ~\.VirtualBox\VirtualBox.xml-prev.

Edit these files to modify the <HardDisks>...</HardDisks> section to remove the duplicate entry of <HardDisk />.

Now run VirtualBox Manager.

Example:

```<code>  <HardDisks>
    <HardDisk uuid="{38f266bd-0959-4caf-a0de-27ac9d52e3663}" location="~/VirtualBox VMs/VM1/box-disk001.vmdk" format="VMDK" type="Normal"/>
    <HardDisk uuid="{a6708d79-7393-4d96-89da-2539f75c5465e}" location="~/VirtualBox VMs/VM2/box-disk001.vmdk" format="VMDK" type="Normal"/>
    <HardDisk uuid="{bdce5d4e-9a1c-4f57-acfd-e2acfc8920552}" location="~/VirtualBox VMs/VM2/box-disk001.vmdk" format="VMDK" type="Normal"/>
  </HardDisks>
</code>```

Note in the above fragment that the last two entries refer to the same VM but have different uuid's. One of them is invalid and should be removed. Which one is invalid can be found out by hit and trial -- first remove the second entry and try; if it doesn't work, remove the third entry.

Body:
The solution that worked for me is as follows:

Make sure VirtualBox Manager is not running.

Back up the files  ~\.VirtualBox\VirtualBox.xml and ~\.VirtualBox\VirtualBox.xml-prev.

Edit these files to modify the <HardDisks>...</HardDisks> section to remove the duplicate entry of <HardDisk />.

Now run VirtualBox Manager.

Example:

  <HardDisks>
    <HardDisk uuid="{38f266bd-0959-4caf-a0de-27ac9d52e3663}" location="~/VirtualBox VMs/VM1/box-disk001.vmdk" format="VMDK" type="Normal"/>
    <HardDisk uuid="{a6708d79-7393-4d96-89da-2539f75c5465e}" location="~/VirtualBox VMs/VM2/box-disk001.vmdk" format="VMDK" type="Normal"/>
    <HardDisk uuid="{bdce5d4e-9a1c-4f57-acfd-e2acfc8920552}" location="~/VirtualBox VMs/VM2/box-disk001.vmdk" format="VMDK" type="Normal"/>
  </HardDisks>

Note in the above fragment that the last two entries refer to the same VM but have different uuid's. One of them is invalid and should be removed. Which one is invalid can be found out by hit and trial -- first remove the second entry and try; if it doesn't work, remove the third entry.


问:
Ngrok auth token file location
In Mac and Window how to change the auth token of ngrok manually

Reference: https://github.com/inconshreveable/ngrok/issues/640

答:
To access configuration file of ngrok

In terminal follow the steps,

```<code>cd ~/
vi /Users/sriramkarthick/.ngrok2/ngrok.yml
</code>```

Title: Ngrok auth token file location

Body:
To access configuration file of ngrok

In terminal follow the steps,

cd ~/
vi /Users/sriramkarthick/.ngrok2/ngrok.yml


问:
Linq 2 Sql insert without relationship
I have 2 tables. eg: One of them is to store Users and the other is to store Orders. Orders table containing UserId as a foreign key. I'm using Linq 2 Sql for data access operations. I want to insert an Order without inserting a User row if the user already exists in the database.

How can I do that?

Thanks in advance,

Edit: Here is the code I have problems with:

```<code>try
{
    context.SocialEntities.InsertOnSubmit(entity);
    context.SubmitChanges();
}
catch (Exception ex)
{
    if (ex.Message.Contains("UserUniqueness"))
    {
        User user = context.Users.Where(u => u.SourceUserID == entity.User.SourceUserID).FirstOrDefault();
        if (user != null)
        {
            user.SocialEntities.Add(entity);
            context.SubmitChanges();
        }
    }
}
</code>```

UserUniqueness is a unique key constraint defined in the User table for a column named SocialSourceId. And it is not primary key.

答:
Add the new order to the existing user's Orders collection.

UPDATE:

I suggest, you do the check for the user before trying to insert it. I guess, that the user you tried to add somehow still is in your context and gets submitted again the next time you call SubmitChanges.

Title: Linq 2 Sql insert without relationship

Body:
I have 2 tables. eg: One of them is to store Users and the other is to store Orders. Orders table containing UserId as a foreign key. I'm using Linq 2 Sql for data access operations. I want to insert an Order without inserting a User row if the user already exists in the database.

How can I do that?

Thanks in advance,

Edit: Here is the code I have problems with:

try
{
    context.SocialEntities.InsertOnSubmit(entity);
    context.SubmitChanges();
}
catch (Exception ex)
{
    if (ex.Message.Contains("UserUniqueness"))
    {
        User user = context.Users.Where(u => u.SourceUserID == entity.User.SourceUserID).FirstOrDefault();
        if (user != null)
        {
            user.SocialEntities.Add(entity);
            context.SubmitChanges();
        }
    }
}

UserUniqueness is a unique key constraint defined in the User table for a column named SocialSourceId. And it is not primary key.


问:
How to make a simple rounded button in Storyboard?
I just started learning iOS development, cannot find how to make simple rounded button. I find resources for old versions. Do I need to set a custom background for a button? In Android, I would just use a 9 patch, but I know iOS does not have this capability.

答:
The extension is the best option for this problem. Create an extension of View or Button

```<code>public extension UIView {
  //Round the corners
  func roundCorners(){
    let radius = bounds.maxX / 16
    layer.cornerRadius = radius
  }
}
</code>```

Call it from the code

```<code>button.roundCorners()
</code>```

Body:
The extension is the best option for this problem. Create an extension of View or Button

public extension UIView {
  //Round the corners
  func roundCorners(){
    let radius = bounds.maxX / 16
    layer.cornerRadius = radius
  }
}

Call it from the code

button.roundCorners()


问:
Converting a Object[] array to an int [] array in java?
It appears there is no easy way of doing this, but this is what i've done so far and if someone could correct it to make it work that would be great. At "newarray [e] = array [i].intValue ();" i get an error "No method named "intValue" was found in type "java.lang.Object"."
Help!

```<code>/*
Description: A game that displays digits 0-9 and asks the user for a number N.
 It then reverses the first N numbers of the sequence. It continues this until
 all of the numbers are in order.
 numbers

*/

import hsa.Console;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;

public class ReversalGame3test

{
    static Console c;

    public static void main (String[] args)
{
    c = new Console ();

    c.println ("3. REVERSAL GAME");
    c.println ("");
    c.println ("Displayed below are the digits 0-9 in random order. You must then enter a");
    c.println ("number N after which the computer will reverse the first N numbers in the");
    c.println ("sequence. The goal of this game is to sort all of the numbers in the fewest");
    c.println ("number of reversals.");
    c.println (""); //introduction

    List numbers = new ArrayList ();
    numbers.add ("0");
    numbers.add ("1");
    numbers.add ("2");
    numbers.add ("3");
    numbers.add ("4");
    numbers.add ("5");
    numbers.add ("6");
    numbers.add ("7");
    numbers.add ("8");
    numbers.add ("9");
    Collections.shuffle (numbers);
    Object[] array = numbers.toArray (new String [10]); // declares + shuffles numbers and converts them to array

    c.print ("Random Order: ");
    for (int i = 0 ; i < 10 ; i++)
    {
        c.print ((array [i]) + " ");
    }
    c.println ("");

    boolean check = false;
    boolean check2 = false;
    String NS;
    int N = 0;
    int count = 0;
    int e = -1;
    int[] newarray = new int [10];

    //INPUT
    do
    {
        c.print ("Enter a number: ");
        NS = c.readString ();
        count += 1;

        check = isInteger (NS);
        if (check == true)
        {
            N = Integer.parseInt (NS);
            if (N < 1 || N > 10)
            {
                check = false;
                c.println ("ERROR - INPUT NOT VALID");
                c.println ("");
            }
            else
            {
                c.print ("Next Order: ");
                for (int i = N - 1 ; i > -1 ; i--)
                {
                    e += 1;
                    newarray [e] = array [i].intValue ();
                    c.print ((newarray [e]) + " ");
                }
                for (int i = N ; i < 10 ; i++)
                {
                    e += 1;
                    newarray [e] = array [i].intValue ();
                    c.print ((newarray [e]) + " ");
                }
                check2 = sorted (newarray);
            } // rearranges numbers if valid
        } // checks if N is valid number
    }
    while (check == false);
} // main method

public static boolean isInteger (String input)
{
    try
    {
        Integer.parseInt (input);
        return true;
    }
    catch (NumberFormatException nfe)
    {
        return false;
    }
} //isInteger method

public static boolean sorted (int array[])
{
    boolean isSorted = false;

    for (int i = 0 ; i < 10 ; i++)
    {
        if (array [i] < array [i + 1])
        {
            isSorted = true;
        }
        else if (array [i] > array [i + 1])
        {
            isSorted = true;
        }
        else
            isSorted = false;

        if (isSorted != true)
            return isSorted;
    }
    return isSorted;
} // sorted method
</code>```

}

答:
I know this is pretty late, but here are my 2 cents!!</p>

```<code>int[] newArray=new int[objectArray.length];
Object[] objectArray = {1,2,3,4,5};

for(int i=0;i<objectArray.length();i++){
    b[i]=(int)objectArray[i];
}
</code>```

Body:
It appears there is no easy way of doing this, but this is what i've done so far and if someone could correct it to make it work that would be great. At "newarray [e] = array [i].intValue ();" i get an error "No method named "intValue" was found in type "java.lang.Object"."
Help!

/*
Description: A game that displays digits 0-9 and asks the user for a number N.
 It then reverses the first N numbers of the sequence. It continues this until
 all of the numbers are in order.
 numbers

*/

import hsa.Console;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;

public class ReversalGame3test

{
    static Console c;

    public static void main (String[] args)
{
    c = new Console ();

    c.println ("3. REVERSAL GAME");
    c.println ("");
    c.println ("Displayed below are the digits 0-9 in random order. You must then enter a");
    c.println ("number N after which the computer will reverse the first N numbers in the");
    c.println ("sequence. The goal of this game is to sort all of the numbers in the fewest");
    c.println ("number of reversals.");
    c.println (""); //introduction

    List numbers = new ArrayList ();
    numbers.add ("0");
    numbers.add ("1");
    numbers.add ("2");
    numbers.add ("3");
    numbers.add ("4");
    numbers.add ("5");
    numbers.add ("6");
    numbers.add ("7");
    numbers.add ("8");
    numbers.add ("9");
    Collections.shuffle (numbers);
    Object[] array = numbers.toArray (new String [10]); // declares + shuffles numbers and converts them to array

    c.print ("Random Order: ");
    for (int i = 0 ; i < 10 ; i++)
    {
        c.print ((array [i]) + " ");
    }
    c.println ("");

    boolean check = false;
    boolean check2 = false;
    String NS;
    int N = 0;
    int count = 0;
    int e = -1;
    int[] newarray = new int [10];

    //INPUT
    do
    {
        c.print ("Enter a number: ");
        NS = c.readString ();
        count += 1;

        check = isInteger (NS);
        if (check == true)
        {
            N = Integer.parseInt (NS);
            if (N < 1 || N > 10)
            {
                check = false;
                c.println ("ERROR - INPUT NOT VALID");
                c.println ("");
            }
            else
            {
                c.print ("Next Order: ");
                for (int i = N - 1 ; i > -1 ; i--)
                {
                    e += 1;
                    newarray [e] = array [i].intValue ();
                    c.print ((newarray [e]) + " ");
                }
                for (int i = N ; i < 10 ; i++)
                {
                    e += 1;
                    newarray [e] = array [i].intValue ();
                    c.print ((newarray [e]) + " ");
                }
                check2 = sorted (newarray);
            } // rearranges numbers if valid
        } // checks if N is valid number
    }
    while (check == false);
} // main method

public static boolean isInteger (String input)
{
    try
    {
        Integer.parseInt (input);
        return true;
    }
    catch (NumberFormatException nfe)
    {
        return false;
    }
} //isInteger method

public static boolean sorted (int array[])
{
    boolean isSorted = false;

    for (int i = 0 ; i < 10 ; i++)
    {
        if (array [i] < array [i + 1])
        {
            isSorted = true;
        }
        else if (array [i] > array [i + 1])
        {
            isSorted = true;
        }
        else
            isSorted = false;

        if (isSorted != true)
            return isSorted;
    }
    return isSorted;
} // sorted method

}

Body:
I know this is pretty late, but here are my 2 cents!!

int[] newArray=new int[objectArray.length];
Object[] objectArray = {1,2,3,4,5};

for(int i=0;i<objectArray.length();i++){
    b[i]=(int)objectArray[i];
}


问:
angular-gridster2 grid size
I am currently working on the integration of angular-gridster2. The goal is to get a grid with a fixed row height, fixed column count and the size should be calculated. This is my current GridsterConfig:

```<code>{
  setGridSize: true,
  margin: 5,
  displayGrid: DisplayGrid.OnDragAndResize,
  gridType: GridType.VerticalFixed,
  keepFixedHeightInMobile: true,
  fixedRowHeight: 50,
  minCols: 6,
  maxCols: 6,
  swap: true,
  pushItems: true,
  resizable: { enabled: true },
  draggable: {enabled: true },
  enableEmptyCellDrop: true,
}
</code>```

With this config the grid height is calculates as expected (perfect). The problem is that the width stays the same after window resizing. When I set the setGridSize property to false the width calculation works as expected but the height is always 2 times the margin.

答:
I used the below configuration and it worked for me:

```<code>    itemChangeCallback: ((item: GridsterItem) => {
         // Your content here
      }),
      itemInitCallback: ((item: GridsterItem, itemComponent: GridsterItemComponentInterface) => {
         // Your content here
      }),
      setGridSize: true,
      gridType: 'verticalFixed',
      fixedRowHeight: 237,
      minRows: 2,
      maxRows: 100,
      minItemRows: 2,
      maxItemRows: 2,
      defaultItemRows: 1,
      minCols: 12,
      maxCols: 12,
      maxItemCols: 12,
      minItemCols: 1,
      defaultItemCols: 1,
      maxItemArea: 2500,
      minItemArea: 1,
      swap: true,
      displayGrid: 'onDrag&Resize',
      compactType: 'compactUp', // 'compactUp&Left',compactLeft&Up'
      pushItems: true,
      resizable: { enabled: true },
      draggable: {
        enabled: true
      }
</code>```

Hope this will help

Title: angular-gridster2 grid size

Body:
I am currently working on the integration of angular-gridster2. The goal is to get a grid with a fixed row height, fixed column count and the size should be calculated. This is my current GridsterConfig:

{
  setGridSize: true,
  margin: 5,
  displayGrid: DisplayGrid.OnDragAndResize,
  gridType: GridType.VerticalFixed,
  keepFixedHeightInMobile: true,
  fixedRowHeight: 50,
  minCols: 6,
  maxCols: 6,
  swap: true,
  pushItems: true,
  resizable: { enabled: true },
  draggable: {enabled: true },
  enableEmptyCellDrop: true,
}

With this config the grid height is calculates as expected (perfect). The problem is that the width stays the same after window resizing. When I set the setGridSize property to false the width calculation works as expected but the height is always 2 times the margin.

Body:
I used the below configuration and it worked for me:

    itemChangeCallback: ((item: GridsterItem) => {
         // Your content here
      }),
      itemInitCallback: ((item: GridsterItem, itemComponent: GridsterItemComponentInterface) => {
         // Your content here
      }),
      setGridSize: true,
      gridType: 'verticalFixed',
      fixedRowHeight: 237,
      minRows: 2,
      maxRows: 100,
      minItemRows: 2,
      maxItemRows: 2,
      defaultItemRows: 1,
      minCols: 12,
      maxCols: 12,
      maxItemCols: 12,
      minItemCols: 1,
      defaultItemCols: 1,
      maxItemArea: 2500,
      minItemArea: 1,
      swap: true,
      displayGrid: 'onDrag&Resize',
      compactType: 'compactUp', // 'compactUp&Left',compactLeft&Up'
      pushItems: true,
      resizable: { enabled: true },
      draggable: {
        enabled: true
      }

Hope this will help


问:
Typescript, map one object into another?
I have two objects, and my custom map function to map props of one object into values of another, e.g:

const obj1 = {
  host: 'clientNameHost',
  pass: 'clientNamePass',
};

const obj2 = {
  clientNamePass: '12345',
  clientNameHost: 'http://localhost:3000',
};

const mapParams = <T, K>(source: T, params: K) => Object.entries(params)
.reduce((acc, [param, sourceProp]) => ({ ...acc, [param]: source[sourceProp] }), {});

mapParams(obj2, obj1) //{host: "http://localhost:3000", pass: "12345"}
```

I'm having a hard time, trying to type this function. Is there some way to type properly mapParams function?

答:
The solution is to narrow the generic types in order to show the relation between keys and values in both arguments:

```<code>const obj1 = {
    host: 'clientNameHost',
    pass: 'clientNamePass',
  } as const;

  const obj2 = {
    clientNamePass: '12345',
    clientNameHost: 'http://localhost:3000',
  } as const;

  const mapParams = <T extends Record<string, any>, K extends keyof T, P extends Record<T[K], any>>(source: T, params: P) => Object.entries(params)
  .reduce((acc, [param, value]) => ({ ...acc, [param]: source[value as T[K]] }), {});

  console.log(mapParams(obj1, obj2)) //{host: "http://localhost:3000", pass: "12345"}
</code>```

Key parts:

T extends Record<string, any> first type is a Record with string keys

K extends keyof T respresents keys of the T

P extends Record<T[K], any> crucial part - we want object which will have keys equal values in T

as const was added in order to properly infer the narrowed types

Above types create a bound between first argument values and second argument keys.

PS. sorry for reverting arguments order.

Body:
I have two objects, and my custom map function to map props of one object into values of another, e.g:

const obj1 = {
  host: 'clientNameHost',
  pass: 'clientNamePass',
};

const obj2 = {
  clientNamePass: '12345',
  clientNameHost: 'http://localhost:3000',
};

const mapParams = <T, K>(source: T, params: K) => Object.entries(params)
.reduce((acc, [param, sourceProp]) => ({ ...acc, [param]: source[sourceProp] }), {});

mapParams(obj2, obj1) //{host: "http://localhost:3000", pass: "12345"}

I'm having a hard time, trying to type this function. Is there some way to type properly mapParams function?

Body:
The solution is to narrow the generic types in order to show the relation between keys and values in both arguments:

const obj1 = {
    host: 'clientNameHost',
    pass: 'clientNamePass',
  } as const;

  const obj2 = {
    clientNamePass: '12345',
    clientNameHost: 'http://localhost:3000',
  } as const;

  const mapParams = <T extends Record<string, any>, K extends keyof T, P extends Record<T[K], any>>(source: T, params: P) => Object.entries(params)
  .reduce((acc, [param, value]) => ({ ...acc, [param]: source[value as T[K]] }), {});

  console.log(mapParams(obj1, obj2)) //{host: "http://localhost:3000", pass: "12345"}

Key parts:

T extends Record<string, any> first type is a Record with string keys

K extends keyof T respresents keys of the T

P extends Record<T[K], any> crucial part - we want object which will have keys equal values in T

as const was added in order to properly infer the narrowed types

Above types create a bound between first argument values and second argument keys.

PS. sorry for reverting arguments order.


问:
keras classifier.fit() method showing shape error?
```<code>classifier = Sequential()
classifier.add(Dense(6,kernel_initializer='random_uniform',activation='relu',input_dim=11))
classifier.add(Dense(6,kernel_initializer='random_uniform',activation='relu'))
classifier.add(Dense(1,activation='sigmoid'))
classifier.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
classifier.fit(x_train, y_train, batch_size = 10, epochs = 100)
</code>```

ValueError: Error when checking input: expected dense_4_input to have shape (11,) but got array with shape (16934,)

答: You didn't gave us information on x_train shape but I guess that your x_train shape is (x, 16934), using the batch_size you're giving (10, 16934) while the input Dense layer is looking for data shaped as (10, 11) where x represent the number of samples in your x_train.

Body:
classifier = Sequential()
classifier.add(Dense(6,kernel_initializer='random_uniform',activation='relu',input_dim=11))
classifier.add(Dense(6,kernel_initializer='random_uniform',activation='relu'))
classifier.add(Dense(1,activation='sigmoid'))
classifier.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
classifier.fit(x_train, y_train, batch_size = 10, epochs = 100)

ValueError: Error when checking input: expected dense_4_input to have shape (11,) but got array with shape (16934,)