问:
Data at the root level is invalid. Line 1, position 1. XML is not valid
I have two errors in my code:

Data at the root level is invalid. Line 1, position 1.

Markup file is not valid. Specify a source markup file with an .xaml extension.

Why?

MainWindow.xaml:

```<code><Window x:Class="TestWpfApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Eight Ball Answer" Height="328" Width="412" >
    <Grid Name="grid1">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <TextBox VerticalAlignment="Stretch" HorizontalAlignment="Stretch"     Margin="10,10,13,10" Name="txtQuestion"      TextWrapping="Wrap" FontFamily="Verdana" FontSize="24"     Grid.Row="0">[Place question here.]</TextBox>
        <Button VerticalAlignment="Top" HorizontalAlignment="Left"     Margin="10,0,0,20" Width="127" Height="23" Name="cmdAnswer"     Click="cmdAnswer_Click" Grid.Row="1">Ask the Eight Ball</Button>
        <TextBox VerticalAlignment="Stretch" HorizontalAlignment="Stretch"     Margin="10,10,13,10" Name="txtAnswer" TextWrapping="Wrap"     IsReadOnly="True" FontFamily="Verdana" FontSize="24" Foreground="Green"     Grid.Row="2">[Answer will appear here.]</TextBox>
        <Grid.Background>
            <LinearGradientBrush>
                <LinearGradientBrush.GradientStops>
                    <GradientStop Offset="0.00" Color="Red" />
                    <GradientStop Offset="0.50" Color="Indigo" />
                    <GradientStop Offset="1.00" Color="Violet" />
                </LinearGradientBrush.GradientStops>
            </LinearGradientBrush>
        </Grid.Background>
    </Grid>
</Window>
</code>```

MainWindow.xaml.cs:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TestWpfApplication
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void cmdAnswer_Click(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;

            txtAnswer.Text = "AAA";
            this.Cursor = null;
        }
    }
}
</code>```

Update 1:

This page was created by copy&paste method, not by designer.

MainWindow.xaml has property BuildAction set to Page.

Is if helpful?

答:
Another solution:

Create a xml file Foo.xml

Copy the xaml file content to Foo.xml xml file

Copy the xaml file name

Delete the xaml file

And you should check your csporj file and make sure the new xaml file will be include as Page and compile
1. Rename the Foo.xml xml file name as the xaml file name

Body:
I have two errors in my code:

Data at the root level is invalid. Line 1, position 1.

Markup file is not valid. Specify a source markup file with an .xaml extension.

Why?

MainWindow.xaml:

<Window x:Class="TestWpfApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Eight Ball Answer" Height="328" Width="412" >
    <Grid Name="grid1">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <TextBox VerticalAlignment="Stretch" HorizontalAlignment="Stretch"     Margin="10,10,13,10" Name="txtQuestion"      TextWrapping="Wrap" FontFamily="Verdana" FontSize="24"     Grid.Row="0">[Place question here.]</TextBox>
        <Button VerticalAlignment="Top" HorizontalAlignment="Left"     Margin="10,0,0,20" Width="127" Height="23" Name="cmdAnswer"     Click="cmdAnswer_Click" Grid.Row="1">Ask the Eight Ball</Button>
        <TextBox VerticalAlignment="Stretch" HorizontalAlignment="Stretch"     Margin="10,10,13,10" Name="txtAnswer" TextWrapping="Wrap"     IsReadOnly="True" FontFamily="Verdana" FontSize="24" Foreground="Green"     Grid.Row="2">[Answer will appear here.]</TextBox>
        <Grid.Background>
            <LinearGradientBrush>
                <LinearGradientBrush.GradientStops>
                    <GradientStop Offset="0.00" Color="Red" />
                    <GradientStop Offset="0.50" Color="Indigo" />
                    <GradientStop Offset="1.00" Color="Violet" />
                </LinearGradientBrush.GradientStops>
            </LinearGradientBrush>
        </Grid.Background>
    </Grid>
</Window>

MainWindow.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TestWpfApplication
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void cmdAnswer_Click(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;

            txtAnswer.Text = "AAA";
            this.Cursor = null;
        }
    }
}

Update 1:

This page was created by copy&paste method, not by designer.

MainWindow.xaml has property BuildAction set to Page.

Is if helpful?


来源: stackexchange

问:
Restrict S3 sub-folder level bucket policy about private and public
We have a lot of information that we can make our bucket to public and private by bucket level. But I'm curious that we can make bucket policy to folder level even to sub-folders. Following is folder structure in my current S3 bucket.

```<code>companies/aa-company/public-folder
companies/aa-company/private-folder
companies/bb-company/public-folder
companies/bb-company/private-folder
</code>```

What I want to know is I want to make Public Read Access to public-folder in bucket policy. Is it possible to do?

答:
Yes you can, by means of wildcards:

You can use wildcards as part of the resource ARN. You can use wildcard characters (* and ?) within any ARN segment (the parts separated by colons). An asterisk (*) represents any combination of zero or more characters, and a question mark (?) represents any single character. You can use multiple * or ? characters in each segment, but a wildcard cannot span segments

Example policy can look as follows (based on this):

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::test-bucket-342-d/*/public-folder/*"
        }
    ]
}
</code>```

You will also need to disable block public access settings on the bucket.

ContentLicense: CC BY-SA 4.0

Body:
We have a lot of information that we can make our bucket to public and private by bucket level. But I'm curious that we can make bucket policy to folder level even to sub-folders. Following is folder structure in my current S3 bucket.

companies/aa-company/public-folder
companies/aa-company/private-folder
companies/bb-company/public-folder
companies/bb-company/private-folder

What I want to know is I want to make Public Read Access to public-folder in bucket policy. Is it possible to do?

Body:
Yes you can, by means of wildcards:

You can use wildcards as part of the resource ARN. You can use wildcard characters (* and ?) within any ARN segment (the parts separated by colons). An asterisk (*) represents any combination of zero or more characters, and a question mark (?) represents any single character. You can use multiple * or ? characters in each segment, but a wildcard cannot span segments

Example policy can look as follows (based on this):

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::test-bucket-342-d/*/public-folder/*"
        }
    ]
}

You will also need to disable block public access settings on the bucket.


问:
"breakpoint set but not yet bound" error when debugging node.js
I have configured my Visual studio code to debug nodejs, chrome(vuejs) application using the recipe in the link. I am however getting a "Failed to exec debug script" error when I debug "Meteor All" error in visual studio code.
If I add a breakpoint in the server side code I see a "breakpoint set but not yet bound". I am however able to debug client side code correctly.
What am I missing?

Launch.json in visual studio code:

```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Meteor: Chrome",
            "url": "http://localhost:3000",
            "webRoot": "${workspaceFolder}",
            "outputCapture": "std"
        },
        {
            "type": "node",
            "request": "launch",
            "name": "Meteor: Node",
            "runtimeExecutable": "npm",
            "runtimeArgs": ["run", "debug"],
            "outputCapture": "std",
            "port": 9229,
            "timeout": 30000
        }
    ],
    "compounds": [
        {
            "name": "Meteor: All",
            "configurations": ["Meteor: Node", "Meteor: Chrome"]
        }
    ]
}
</code>```

log in Visual Studio code:

```<code>C:\Program Files\nodejs\npm.cmd run debug

> vue-meteor-demo@ debug c:\temp\vuemeteor2
> meteor run meteor --settings settings.json --inspect-brk=9229

Unknown run target: meteor
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! vue-meteor-demo@ debug: `meteor run meteor --settings settings.json --inspect-brk=9229`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the vue-meteor-demo@ debug script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\AjitGoel\AppData\Roaming\npm-cache\_logs\2019-11-14T14_17_23_502Z-debug.log
</code>```

debug.log:

```<code>0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'debug' ]
2 info using npm@6.4.1
3 info using node@v10.15.0
4 verbose run-script [ 'predebug', 'debug', 'postdebug' ]
5 info lifecycle vue-meteor-demo@~predebug: vue-meteor-demo@
6 info lifecycle vue-meteor-demo@~debug: vue-meteor-demo@
7 verbose lifecycle vue-meteor-demo@~debug: unsafe-perm in lifecycle true
8 verbose lifecycle vue-meteor-demo@~debug: PATH: <Path>
9 verbose lifecycle vue-meteor-demo@~debug: CWD: c:\temp\vuemeteor2
10 silly lifecycle vue-meteor-demo@~debug: Args: [ '/d /s /c',
10 silly lifecycle   'meteor run meteor --settings settings.json --inspect-brk=9229' ]
11 silly lifecycle vue-meteor-demo@~debug: Returned: code: 1  signal: null
12 info lifecycle vue-meteor-demo@~debug: Failed to exec debug script
13 verbose stack Error: vue-meteor-demo@ debug: `meteor run meteor --settings settings.json --inspect-brk=9229`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:182:13)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:182:13)
13 verbose stack     at maybeClose (internal/child_process.js:962:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:251:5)
14 verbose pkgid vue-meteor-demo@
15 verbose cwd c:\temp\vuemeteor2
16 verbose Windows_NT 10.0.18362
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "debug"
18 verbose node v10.15.0
19 verbose npm  v6.4.1
20 error code ELIFECYCLE
21 error errno 1
22 error vue-meteor-demo@ debug: `meteor run meteor --settings settings.json --inspect-brk=9229`
22 error Exit status 1
23 error Failed at the vue-meteor-demo@ debug script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]
</code>```

答:
It seems this message shows up if the debugger cannot "reach" the breakpoint's file through the node process the debugger is attached to.

The error message is not well covered in VS Code documentation so it's hard to find out what causes it.

I tested this by adding a file to a project, putting a breakpoint in it but not include/require'ing it anywhere. When you run the debugger (on another file) the breakpoint you just added will be "set but not yet bound".
Conversely, if you include/require the new file, the breakpoint will be normal (even if your tests never reach the line the breakpoint is on).

In my case, I inherited a codebase and found out that if your script spawns child processes (e.g. through child_process.execFile), the debugger will not track the code in the child process. Instead, it will show breakpoints as "breakpoint set but not yet bound".

Body:
I have configured my Visual studio code to debug nodejs, chrome(vuejs) application using the recipe in the link. I am however getting a "Failed to exec debug script" error when I debug "Meteor All" error in visual studio code.
If I add a breakpoint in the server side code I see a "breakpoint set but not yet bound". I am however able to debug client side code correctly.
What am I missing?

Launch.json in visual studio code:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Meteor: Chrome",
            "url": "http://localhost:3000",
            "webRoot": "${workspaceFolder}",
            "outputCapture": "std"
        },
        {
            "type": "node",
            "request": "launch",
            "name": "Meteor: Node",
            "runtimeExecutable": "npm",
            "runtimeArgs": ["run", "debug"],
            "outputCapture": "std",
            "port": 9229,
            "timeout": 30000
        }
    ],
    "compounds": [
        {
            "name": "Meteor: All",
            "configurations": ["Meteor: Node", "Meteor: Chrome"]
        }
    ]
}

log in Visual Studio code:

C:\Program Files\nodejs\npm.cmd run debug

> vue-meteor-demo@ debug c:\temp\vuemeteor2
> meteor run meteor --settings settings.json --inspect-brk=9229

Unknown run target: meteor
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! vue-meteor-demo@ debug: `meteor run meteor --settings settings.json --inspect-brk=9229`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the vue-meteor-demo@ debug script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\AjitGoel\AppData\Roaming\npm-cache\_logs\2019-11-14T14_17_23_502Z-debug.log

debug.log:

0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'debug' ]
2 info using npm@6.4.1
3 info using node@v10.15.0
4 verbose run-script [ 'predebug', 'debug', 'postdebug' ]
5 info lifecycle vue-meteor-demo@~predebug: vue-meteor-demo@
6 info lifecycle vue-meteor-demo@~debug: vue-meteor-demo@
7 verbose lifecycle vue-meteor-demo@~debug: unsafe-perm in lifecycle true
8 verbose lifecycle vue-meteor-demo@~debug: PATH: <Path>
9 verbose lifecycle vue-meteor-demo@~debug: CWD: c:\temp\vuemeteor2
10 silly lifecycle vue-meteor-demo@~debug: Args: [ '/d /s /c',
10 silly lifecycle   'meteor run meteor --settings settings.json --inspect-brk=9229' ]
11 silly lifecycle vue-meteor-demo@~debug: Returned: code: 1  signal: null
12 info lifecycle vue-meteor-demo@~debug: Failed to exec debug script
13 verbose stack Error: vue-meteor-demo@ debug: `meteor run meteor --settings settings.json --inspect-brk=9229`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:182:13)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:182:13)
13 verbose stack     at maybeClose (internal/child_process.js:962:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:251:5)
14 verbose pkgid vue-meteor-demo@
15 verbose cwd c:\temp\vuemeteor2
16 verbose Windows_NT 10.0.18362
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "debug"
18 verbose node v10.15.0
19 verbose npm  v6.4.1
20 error code ELIFECYCLE
21 error errno 1
22 error vue-meteor-demo@ debug: `meteor run meteor --settings settings.json --inspect-brk=9229`
22 error Exit status 1
23 error Failed at the vue-meteor-demo@ debug script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]


问:
Parsing and converting exponential values to decimal in JavaScript
I want to parse and convert an exponential value into a decimal using JavaScript. 4.65661287307739E-10 should give 0.000000000465661287307739. What should I do to achieve this?

parseFloat(4.65661287307739E-10) returns 4.65661287307739e-10.

parseInt(4.65661287307739E-10) returns 4.

答:
Here is my short function code that converts Exponential (e-Notation) Numbers to Decimals, allowing the output of large number of decimal places.

It handles all the e-notation syntax permitted by Javascript which include the following:

```<code>Valid e-notation numbers in Javascript:
   123e1    ==>  1230
   123E1    ==>  1230
   123e+1   ==>  1230
   123.e+1  ==>  1230   (with missing fractional part)
   123e-1   ==>  12.3
   0.1e-1   ==>  0.01
   .1e-1    ==>  0.01   (with missing whole part)
  -123e1    ==> -1230
   0.0e1    ==>  0
  -0.0e4    ==> -0

</code>```

The function does not attempt to trap NaN or undefined inputs but does attempt to cater for normal (non-e-notation) numbers; such numbers are returned "as is".

I have tried to provide enough comments on each line and tried to avoid (as far as possible!) the use of short-circuiting and conditional (ternary) operators for better clarity.

I have used the toLocaleString() method to automatically detect the decimal separator sign, but this, of course, assumes that the input string representing the number follows the machine's locale (especially when manually passed to the function).

/********************************************************
* Converts Exponential (e-Notation) Numbers to Decimals
********************************************************
* @function numberExponentToLarge()
* @version  1.00
* @param   {string}  Number in exponent format.
*                   (other formats returned as is).
* @return  {string}  Returns a decimal number string.
* @author  Mohsen Alyafei
* @date    12 Jan 2020
*
* Notes: No check is made for NaN or undefined inputs
*
*******************************************************/

function numberExponentToLarge(numIn) {
 numIn +="";                                            // To cater to numric entries
 var sign="";                                           // To remember the number sign
 numIn.charAt(0)=="-" && (numIn =numIn.substring(1),sign ="-"); // remove - sign & remember it
 var str = numIn.split(/[eE]/g);                        // Split numberic string at e or E
 if (str.length<2) return sign+numIn;                   // Not an Exponent Number? Exit with orginal Num back
 var power = str[1];                                    // Get Exponent (Power) (could be + or -)

 var deciSp = 1.1.toLocaleString().substring(1,2);  // Get Deciaml Separator
 str = str[0].split(deciSp);                        // Split the Base Number into LH and RH at the decimal point
 var baseRH = str[1] || "",                         // RH Base part. Make sure we have a RH fraction else ""
     baseLH = str[0];                               // LH base part.

  if (power>=0) {   // ------- Positive Exponents (Process the RH Base Part)
     if (power> baseRH.length) baseRH +="0".repeat(power-baseRH.length); // Pad with "0" at RH
     baseRH = baseRH.slice(0,power) + deciSp + baseRH.slice(power);      // Insert decSep at the correct place into RH base
      if (baseRH.charAt(baseRH.length-1) ==deciSp) baseRH =baseRH.slice(0,-1); // If decSep at RH end? => remove it

  } else {         // ------- Negative exponents (Process the LH Base Part)
     num= Math.abs(power) - baseLH.length;                               // Delta necessary 0's
     if (num>0) baseLH = "0".repeat(num) + baseLH;                       // Pad with "0" at LH
     baseLH = baseLH.slice(0, power) + deciSp + baseLH.slice(power);     // Insert "." at the correct place into LH base
     if (baseLH.charAt(0) == deciSp) baseLH="0" + baseLH;                // If decSep at LH most? => add "0"

  }
  // Rremove leading and trailing 0's and Return the long number (with sign)
  return sign + (baseLH + baseRH).replace(/^0*(\d+|\d+\.\d+?)\.?0*$/,"$1");
}

//============ test codes ==================
function test(test,input,should){
var  out=numberExponentToLarge(input);
var r = (out===should) ? true : false;
if (!r) console.log(test+" Failed: "+out+" should be: "+should);
  else console.log("Passed");
}
// ------------- tests for e-notation numbers ---------------------

test(1,"123E0","123")
test(2,"123E0","123")
test(3,"-123e+0","-123")
test(4,"123e1","1230")
test(5,"123e3","123000")
test(6,"123e+3","123000")
test(7,"123E+7","1230000000")
test(8,"-123.456e+1","-1234.56")
test(9,"123.456e+4","1234560")
test(10,"123E-0","123")
test(11,"123.456e+50","12345600000000000000000000000000000000000000000000000")

test(12,"123e-0","123")
test(13,"123e-1","12.3")
test(14,"123e-3","0.123")
test(15,"-123e-7","-0.0000123")
test(16,"123.456E-1","12.3456")
test(17,"123.456e-4","0.0123456")
test(18,"123.456e-50","0.00000000000000000000000000000000000000000000000123456")
test(18-1,"-123.456e-50","-0.00000000000000000000000000000000000000000000000123456")

test(19,"1.e-5","0.00001")  // handle missing base fractional part
test(20,".123e3","123")     // handle missing base whole part

// The Electron's Mass:
test(21,"9.10938356e-31","0.000000000000000000000000000000910938356")
// The Earth's Mass:
test(22,"5.9724e+24","5972400000000000000000000")
// Planck constant:
test(23,"6.62607015e-34","0.000000000000000000000000000000000662607015")

test(24,"0.000e3","0")
test(25,"0.000000000000000e3","0")
test(26,"-0.0001e+9","-100000")
test(27,"-0.0e1","-0")
test(28,"-0.0000e1","-0")
test(28,"-000.0000e1","-0")    // this is an invalid Javascript number
test(28,"-000.0000e-1","-0")   // this is an invalid Javascript number
test(28,"-000.0000e+10","-0")  // this is an invalid Javascript number
test(28,"-000.0000e+2","-0")   // this is an invalid Javascript number

// ------------- testing for Non e-Notation Numbers -------------
test(29,"12345.7898","12345.7898") // no exponent
test(30,12345.7898,"12345.7898")   // no exponent
test(31,0.00000000000001,"0.00000000000001")    // from 1e-14
test(32,-0.0000000000000345,"-0.0000000000000345") // from -3.45e-14
test(33,-0,"0")
test(34,"1.2000e0","1.2")
test(35,"1.2000e-0","1.2")
test(35,"1.2000e+0","1.2")
test(35,"1.2000e+10","12000000000")```

Body:
Here is my short function code that converts Exponential (e-Notation) Numbers to Decimals, allowing the output of large number of decimal places.

It handles all the e-notation syntax permitted by Javascript which include the following:

Valid e-notation numbers in Javascript:
   123e1    ==>  1230
   123E1    ==>  1230
   123e+1   ==>  1230
   123.e+1  ==>  1230   (with missing fractional part)
   123e-1   ==>  12.3
   0.1e-1   ==>  0.01
   .1e-1    ==>  0.01   (with missing whole part)
  -123e1    ==> -1230
   0.0e1    ==>  0
  -0.0e4    ==> -0

The function does not attempt to trap NaN or undefined inputs but does attempt to cater for normal (non-e-notation) numbers; such numbers are returned "as is".

I have tried to provide enough comments on each line and tried to avoid (as far as possible!) the use of short-circuiting and conditional (ternary) operators for better clarity.

I have used the toLocaleString() method to automatically detect the decimal separator sign, but this, of course, assumes that the input string representing the number follows the machine's locale (especially when manually passed to the function).

/********************************************************
* Converts Exponential (e-Notation) Numbers to Decimals
********************************************************
* @function numberExponentToLarge()
* @version  1.00
* @param   {string}  Number in exponent format.
*                   (other formats returned as is).
* @return  {string}  Returns a decimal number string.
* @author  Mohsen Alyafei
* @date    12 Jan 2020
*
* Notes: No check is made for NaN or undefined inputs
*
*******************************************************/

function numberExponentToLarge(numIn) {
 numIn +="";                                            // To cater to numric entries
 var sign="";                                           // To remember the number sign
 numIn.charAt(0)=="-" && (numIn =numIn.substring(1),sign ="-"); // remove - sign & remember it
 var str = numIn.split(/[eE]/g);                        // Split numberic string at e or E
 if (str.length<2) return sign+numIn;                   // Not an Exponent Number? Exit with orginal Num back
 var power = str[1];                                    // Get Exponent (Power) (could be + or -)

 var deciSp = 1.1.toLocaleString().substring(1,2);  // Get Deciaml Separator
 str = str[0].split(deciSp);                        // Split the Base Number into LH and RH at the decimal point
 var baseRH = str[1] || "",                         // RH Base part. Make sure we have a RH fraction else ""
     baseLH = str[0];                               // LH base part.

  if (power>=0) {   // ------- Positive Exponents (Process the RH Base Part)
     if (power> baseRH.length) baseRH +="0".repeat(power-baseRH.length); // Pad with "0" at RH
     baseRH = baseRH.slice(0,power) + deciSp + baseRH.slice(power);      // Insert decSep at the correct place into RH base
      if (baseRH.charAt(baseRH.length-1) ==deciSp) baseRH =baseRH.slice(0,-1); // If decSep at RH end? => remove it

  } else {         // ------- Negative exponents (Process the LH Base Part)
     num= Math.abs(power) - baseLH.length;                               // Delta necessary 0's
     if (num>0) baseLH = "0".repeat(num) + baseLH;                       // Pad with "0" at LH
     baseLH = baseLH.slice(0, power) + deciSp + baseLH.slice(power);     // Insert "." at the correct place into LH base
     if (baseLH.charAt(0) == deciSp) baseLH="0" + baseLH;                // If decSep at LH most? => add "0"

  }
  // Rremove leading and trailing 0's and Return the long number (with sign)
  return sign + (baseLH + baseRH).replace(/^0*(\d+|\d+\.\d+?)\.?0*$/,"$1");
}

//============ test codes ==================
function test(test,input,should){
var  out=numberExponentToLarge(input);
var r = (out===should) ? true : false;
if (!r) console.log(test+" Failed: "+out+" should be: "+should);
  else console.log("Passed");
}
// ------------- tests for e-notation numbers ---------------------

test(1,"123E0","123")
test(2,"123E0","123")
test(3,"-123e+0","-123")
test(4,"123e1","1230")
test(5,"123e3","123000")
test(6,"123e+3","123000")
test(7,"123E+7","1230000000")
test(8,"-123.456e+1","-1234.56")
test(9,"123.456e+4","1234560")
test(10,"123E-0","123")
test(11,"123.456e+50","12345600000000000000000000000000000000000000000000000")

test(12,"123e-0","123")
test(13,"123e-1","12.3")
test(14,"123e-3","0.123")
test(15,"-123e-7","-0.0000123")
test(16,"123.456E-1","12.3456")
test(17,"123.456e-4","0.0123456")
test(18,"123.456e-50","0.00000000000000000000000000000000000000000000000123456")
test(18-1,"-123.456e-50","-0.00000000000000000000000000000000000000000000000123456")

test(19,"1.e-5","0.00001")  // handle missing base fractional part
test(20,".123e3","123")     // handle missing base whole part

// The Electron's Mass:
test(21,"9.10938356e-31","0.000000000000000000000000000000910938356")
// The Earth's Mass:
test(22,"5.9724e+24","5972400000000000000000000")
// Planck constant:
test(23,"6.62607015e-34","0.000000000000000000000000000000000662607015")

test(24,"0.000e3","0")
test(25,"0.000000000000000e3","0")
test(26,"-0.0001e+9","-100000")
test(27,"-0.0e1","-0")
test(28,"-0.0000e1","-0")
test(28,"-000.0000e1","-0")    // this is an invalid Javascript number
test(28,"-000.0000e-1","-0")   // this is an invalid Javascript number
test(28,"-000.0000e+10","-0")  // this is an invalid Javascript number
test(28,"-000.0000e+2","-0")   // this is an invalid Javascript number

// ------------- testing for Non e-Notation Numbers -------------
test(29,"12345.7898","12345.7898") // no exponent
test(30,12345.7898,"12345.7898")   // no exponent
test(31,0.00000000000001,"0.00000000000001")    // from 1e-14
test(32,-0.0000000000000345,"-0.0000000000000345") // from -3.45e-14
test(33,-0,"0")
test(34,"1.2000e0","1.2")
test(35,"1.2000e-0","1.2")
test(35,"1.2000e+0","1.2")
test(35,"1.2000e+10","12000000000")


问:
ERROR:tensorflow:Couldn't understand architecture name ''
I'm following the instruction from google code lab

When I ran the following command I got some error.

```<code>python -m scripts.retrain \
    --bottleneck_dir=tf_files/bottlenecks \
    --how_many_training_steps=500 \
    --model_dir=tf_files/models/ \
    --summaries_dir=tf_files/training_summaries/"${ARCHITECTURE}" \
    --output_graph=tf_files/retrained_graph.pb \
    --output_labels=tf_files/retrained_labels.txt \
    --architecture="${ARCHITECTURE}" \
    --image_dir=tf_files/flower_photos
</code>```

the error are

```<code>ERROR:tensorflow:Couldn't understand architecture name ''
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/Users/nutron/Documents/android-codelab-projects/google-codelab-tensorflow-for-poets-2/scripts/retrain.py", line 1326, in <module>
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
  File "/Users/nutron/tensorflow/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "/Users/nutron/Documents/android-codelab-projects/google-codelab-tensorflow-for-poets-2/scripts/retrain.py", line 976, in main
    model_info = create_model_info(FLAGS.architecture)
  File "/Users/nutron/Documents/android-codelab-projects/google-codelab-tensorflow-for-poets-2/scripts/retrain.py", line 923, in create_model_info
    raise ValueError('Unknown architecture', architecture)
ValueError: ('Unknown architecture', '')
</code>```

What I did it wrong or what should I do?

Thanks

答:
If Max' answer does not work for you on Linux, Try replacing "${ARCHITECTURE}" with "mobilenet_0.50_224"</p>

```<code>python -m scripts.retrain
--bottleneck_dir=tf_files/bottlenecks
--how_many_training_steps=500
--model_dir=tf_files/models/
--summaries_dir=tf_files/training_summaries/"mobilenet_0.50_224"
--output_graph=tf_files/retrained_graph.pb
--output_labels=tf_files/retrained_labels.txt
--architecture="mobilenet_0.50_224"
--image_dir=tf_files/flower_photos
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm following the instruction from google code lab

When I ran the following command I got some error.

python -m scripts.retrain \
    --bottleneck_dir=tf_files/bottlenecks \
    --how_many_training_steps=500 \
    --model_dir=tf_files/models/ \
    --summaries_dir=tf_files/training_summaries/"${ARCHITECTURE}" \
    --output_graph=tf_files/retrained_graph.pb \
    --output_labels=tf_files/retrained_labels.txt \
    --architecture="${ARCHITECTURE}" \
    --image_dir=tf_files/flower_photos

the error are

ERROR:tensorflow:Couldn't understand architecture name ''
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/Users/nutron/Documents/android-codelab-projects/google-codelab-tensorflow-for-poets-2/scripts/retrain.py", line 1326, in <module>
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
  File "/Users/nutron/tensorflow/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "/Users/nutron/Documents/android-codelab-projects/google-codelab-tensorflow-for-poets-2/scripts/retrain.py", line 976, in main
    model_info = create_model_info(FLAGS.architecture)
  File "/Users/nutron/Documents/android-codelab-projects/google-codelab-tensorflow-for-poets-2/scripts/retrain.py", line 923, in create_model_info
    raise ValueError('Unknown architecture', architecture)
ValueError: ('Unknown architecture', '')

What I did it wrong or what should I do?

Thanks

Body:
If Max' answer does not work for you on Linux, Try replacing "${ARCHITECTURE}" with "mobilenet_0.50_224"

python -m scripts.retrain
--bottleneck_dir=tf_files/bottlenecks
--how_many_training_steps=500
--model_dir=tf_files/models/
--summaries_dir=tf_files/training_summaries/"mobilenet_0.50_224"
--output_graph=tf_files/retrained_graph.pb
--output_labels=tf_files/retrained_labels.txt
--architecture="mobilenet_0.50_224"
--image_dir=tf_files/flower_photos


问:
RecyclerView remove divider / decorator after the last item
I have a quite simple RecyclerView.

This is how I set the divider:

```<code>DividerItemDecoration itemDecorator = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
itemDecorator.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.news_divider));
recyclerView.addItemDecoration(itemDecorator);
</code>```

And this is drawable/news_divider.xml:

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="@color/white_two"/>
    <size android:height="1dp"/>
</shape>
</code>```

The problem is for some reason the divider is not just created in between the items. But also after the last item. And I want it only in between the items not after every item.

Any idea how to prevent the divider from showing after the last item?

答:
Extension function for Kotlin:

```<code>fun RecyclerView.addItemDecorationWithoutLastDivider() {

    if (layoutManager !is LinearLayoutManager)
        return

    addItemDecoration(object :
        DividerItemDecoration(context, (layoutManager as LinearLayoutManager).orientation) {

        override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
            super.getItemOffsets(outRect, view, parent, state)

            if (parent.getChildAdapterPosition(view) == state.itemCount - 1)
                outRect.setEmpty()
            else
                super.getItemOffsets(outRect, view, parent, state)
        }
    })
}
</code>```

You can use it easily:

```<code>recyclerView.addItemDecorationWithoutLastDivider()
</code>```

Body:
I have a quite simple RecyclerView.

This is how I set the divider:

DividerItemDecoration itemDecorator = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
itemDecorator.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.news_divider));
recyclerView.addItemDecoration(itemDecorator);

And this is drawable/news_divider.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="@color/white_two"/>
    <size android:height="1dp"/>
</shape>

The problem is for some reason the divider is not just created in between the items. But also after the last item. And I want it only in between the items not after every item.

Any idea how to prevent the divider from showing after the last item?

Body:
Extension function for Kotlin:

fun RecyclerView.addItemDecorationWithoutLastDivider() {

    if (layoutManager !is LinearLayoutManager)
        return

    addItemDecoration(object :
        DividerItemDecoration(context, (layoutManager as LinearLayoutManager).orientation) {

        override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
            super.getItemOffsets(outRect, view, parent, state)

            if (parent.getChildAdapterPosition(view) == state.itemCount - 1)
                outRect.setEmpty()
            else
                super.getItemOffsets(outRect, view, parent, state)
        }
    })
}

You can use it easily:

recyclerView.addItemDecorationWithoutLastDivider()


问:
Environment Variable error while initializing kubernetes
All,

I tried setting up Kubernetes on my two Ubuntu v20.0 using the below link -

https://www.edureka.co/blog/install-kubernetes-on-ubuntu

But I get an error when the Ubuntu was rebooted and since then I have not been able to proceed forward.

```<code>invalid variable assignment ignoring cgroup-driver=systemd/cgroup-driver=cgroupfs
</code>```

The Docker info has the entry "Cgroup driver = cgroupfs"

The below article mentions about configuring cgroup driver:

```<code>https://unofficial-kubernetes.readthedocs.io/en/latest/tasks/administer-cluster/reserve-compute-resources/
</code>```

What am I missing?

Thanks,
rgn

答: The issued to be with the various versions of the softwares/modules that are needed. I was able to find a simple installation steps to accomplish the same</p>

Body:
All,

I tried setting up Kubernetes on my two Ubuntu v20.0 using the below link -

https://www.edureka.co/blog/install-kubernetes-on-ubuntu

But I get an error when the Ubuntu was rebooted and since then I have not been able to proceed forward.

invalid variable assignment ignoring cgroup-driver=systemd/cgroup-driver=cgroupfs

The Docker info has the entry "Cgroup driver = cgroupfs"

The below article mentions about configuring cgroup driver:

https://unofficial-kubernetes.readthedocs.io/en/latest/tasks/administer-cluster/reserve-compute-resources/

What am I missing?

Thanks,
rgn


问:
Should you use a zero "enum" value to indicate an invalid value
Having used C for decades I got into the habit of using the zero value of an enum as a special undefined/unknown/error value.  Over the years I believe this has saved me not hours or even days but months of debugging time since it makes it obvious when a value has not been initialized.  (I wouldn't do this for simple enums where there is a sensible default value and no possibility of uninitialized values.)

It seems to me that this practice is even more useful in Go as values are automatically zero-initialised for you.  However, I have been told that "idiomatic" Go zero-values should be valid values. I think this "rule" was invented for structs, where it makes a lot of sense (in the absence of constructors) to have a newly created "zeroed" struct ready for use, but there are cases where there is no logical default value (for structs and enums).

If you need it here is an example:

```<code>type Base int

const (
        Invalid Base = iota
        A
        C
        T
        G
)
</code>```

Note that I have searched extensively for this question on SO and was surprised that this specific topic has not been covered.  I realise that my question is somewhat subjective and may be flagged but I think it is useful.  I am looking for evidence that using zero values to indicate error conditions is acceptable Go practice.  Any examples of this use, eg. from the standard Go library, would be appreciated.

答:
A true enum type should only be assigned a value from a list of pre-defined constant values. The go language, however, does not have such a type-value enforcement.

go has const which typically uses a derivative type of say int. There is no compile/run-time mechanism to enforce a value is strictly within a pre-defined list.

So what does this mean in practice?

Is your enum value mandatory or optional? That is, when deserializing the 'enum' value, is it:

optional - then use the zero-value signifies the default value

mandatory - then the zero-value indicates an initialization error

Depending on your common use-case, choose one of these two options.

EDIT:
Deserializing is not the only concern. One has to be careful when branching on enum values. For example:

```<code>type role int
const (
    user role = iota
    helpdesk
    admin
)

func greet(r role) {
    switch r {
        case admin:
            fmt.Println("hi admin")
        case helpdesk:
            fmt.Println("hi helpdesk")
        default:
            fmt.Println("hi user") // right?
    }
}
</code>```

This works:

```<code>var r role
r = admin
greet(r) // hi admin
</code>```

But what about this?

```<code>r = 12
greet(r) // 'hi user' ?!!
</code>```

So be sure to pedantically validate on valid values only:

```<code>func validateRole(r role) (err error) {
    switch r {
    case user, helpdesk, admin: // all valid values
    default:
        err = fmt.Errorf("invalid `role` enum %d", r)
    }
    return
}
</code>```

Playground

Body:
Having used C for decades I got into the habit of using the zero value of an enum as a special undefined/unknown/error value.  Over the years I believe this has saved me not hours or even days but months of debugging time since it makes it obvious when a value has not been initialized.  (I wouldn't do this for simple enums where there is a sensible default value and no possibility of uninitialized values.)

It seems to me that this practice is even more useful in Go as values are automatically zero-initialised for you.  However, I have been told that "idiomatic" Go zero-values should be valid values. I think this "rule" was invented for structs, where it makes a lot of sense (in the absence of constructors) to have a newly created "zeroed" struct ready for use, but there are cases where there is no logical default value (for structs and enums).

If you need it here is an example:

type Base int

const (
        Invalid Base = iota
        A
        C
        T
        G
)

Note that I have searched extensively for this question on SO and was surprised that this specific topic has not been covered.  I realise that my question is somewhat subjective and may be flagged but I think it is useful.  I am looking for evidence that using zero values to indicate error conditions is acceptable Go practice.  Any examples of this use, eg. from the standard Go library, would be appreciated.

Body:
A true enum type should only be assigned a value from a list of pre-defined constant values. The go language, however, does not have such a type-value enforcement.

go has const which typically uses a derivative type of say int. There is no compile/run-time mechanism to enforce a value is strictly within a pre-defined list.

So what does this mean in practice?

Is your enum value mandatory or optional? That is, when deserializing the 'enum' value, is it:

optional - then use the zero-value signifies the default value

mandatory - then the zero-value indicates an initialization error

Depending on your common use-case, choose one of these two options.

EDIT:
Deserializing is not the only concern. One has to be careful when branching on enum values. For example:

type role int
const (
    user role = iota
    helpdesk
    admin
)

func greet(r role) {
    switch r {
        case admin:
            fmt.Println("hi admin")
        case helpdesk:
            fmt.Println("hi helpdesk")
        default:
            fmt.Println("hi user") // right?
    }
}

This works:

var r role
r = admin
greet(r) // hi admin

But what about this?

r = 12
greet(r) // 'hi user' ?!!

So be sure to pedantically validate on valid values only:

func validateRole(r role) (err error) {
    switch r {
    case user, helpdesk, admin: // all valid values
    default:
        err = fmt.Errorf("invalid `role` enum %d", r)
    }
    return
}

Playground


问:
How to connect from Azure pipeline to private Container Instance?
I've got a pipeline building an RPM package which I'd like to upload to our Nexus server. The Nexus server runs on an ACI (Azure Container Instance). The ACI is using a private network.

IF I've got it right the intended way is:

Create a Generic service connection containing the url, credentials and root directory of the ACI.

Use the cUrl task to select the file and use the Generic service to perform the upload.

The problem however is that the pipeline vm can not connect to the ACI (no route to host).

Can somebody help me to fix this ? Or give me pointers to online resources ?

答:
As I know, when you create the ACI in the private network, it means you cannot access it outside directly. But you can use the Azure Application Gateway to access the ACI by adding the private IP address to the backend. And you can also use this way to upload files to the ACI.

And there is also another way to upload files to the ACI in the private network. In this way, you need to mount the Azure File Share to the ACI in the creation time and then you can upload files to that Azure File Share. You can access these files in the mount point of the ACI. I recommend this way more than others.


问:
How to use the crypto processor on the dev board?
On the data sheet, the SoM comes with an ATECC608A crypographic coprocessor, but there are no documentations on how to use it. Are there some usecase for this HW and any instructions on how to use it?</p>

答:
This library is included in the coral-cloud repo. It is generally installed with the Coral cloudiot package (python3-coral-cloudiot) but could also directly installed with python3-cryptoauthlib.

```<code>echo "deb https://packages.cloud.google.com/apt coral-cloud-stable main" | sudo tee /etc/apt/sources.list.d/coral-cloud.list
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
sudo apt update
sudo apt install python3-coral-cloudiot
</code>```

The sdk can be found here: https://github.com/MicrochipTech/cryptoauthlib

Body:
This library is included in the coral-cloud repo. It is generally installed with the Coral cloudiot package (python3-coral-cloudiot) but could also directly installed with python3-cryptoauthlib.

echo "deb https://packages.cloud.google.com/apt coral-cloud-stable main" | sudo tee /etc/apt/sources.list.d/coral-cloud.list
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
sudo apt update
sudo apt install python3-coral-cloudiot

The sdk can be found here: https://github.com/MicrochipTech/cryptoauthlib


问:
Use 12 different date ranges in join statement-SQL without re-running the join 12 times
Supposedly I have 2 tables in the formats below:

Table 1: Visits

```<code>Customer | Website_visit_id  | Time_of_visit
</code>```

Table 2: Booking

```<code>Customer | Hotel_booking_id  | Time_of_booking
</code>```

I created a table that has customer's id, their booking, and all the visits they made to the website within 30 days prior to making the booking using this:

```<code>select customer, booking_id, website_visit_id
from visits a
  join booking b
    on a.customer = b.customer
   and Time_of_visit between dateadd(days, -30, time_of_booking) and time_of_booking
</code>```

My question is- if I want to expand this time frame to look at how many visits within 60,90,120...365 days prior to making the booking, how do I do that most efficiently (instead of having to run the join 12 times with the dateadd number changed? Is there a way to add a parameter in place of the '30' days in the join statement?

The output can be in the form of a list of booking and their corresponding visits/ timeframe, or a table of bookings and total of visits for each time frame (something that looks like this:

```<code>Time_frame| Customer | Hotel_booking_id | Number of visits
T30D      | Mike     | 1A               | 5
T60D      | Mike     | 1A               | 15
T90D      | Mike     | 1A               | 22
T120D     | Mike     | 1A               | 27

Thank you in advance

</code>```

答:
If you are looking to dynamically build a query, you should look to see if your DB supports dynamic queries/sql. Essentially, instead of running a query, you would run a stored procedure with logic to identify what your query parameters should be. From there, you would be able to dynamically create your query based on your preferred logic and execute it.

I'm not sure which DB you are using however I know that MySQL and Oracle DBs support this.

Please see links below for further information:

Oracle Documentation
MySQL Documentation

Body:
Supposedly I have 2 tables in the formats below:

Table 1: Visits

Customer | Website_visit_id  | Time_of_visit

Table 2: Booking

Customer | Hotel_booking_id  | Time_of_booking

I created a table that has customer's id, their booking, and all the visits they made to the website within 30 days prior to making the booking using this:

select customer, booking_id, website_visit_id
from visits a
  join booking b
    on a.customer = b.customer
   and Time_of_visit between dateadd(days, -30, time_of_booking) and time_of_booking

My question is- if I want to expand this time frame to look at how many visits within 60,90,120...365 days prior to making the booking, how do I do that most efficiently (instead of having to run the join 12 times with the dateadd number changed? Is there a way to add a parameter in place of the '30' days in the join statement?

The output can be in the form of a list of booking and their corresponding visits/ timeframe, or a table of bookings and total of visits for each time frame (something that looks like this:

Time_frame| Customer | Hotel_booking_id | Number of visits
T30D      | Mike     | 1A               | 5
T60D      | Mike     | 1A               | 15
T90D      | Mike     | 1A               | 22
T120D     | Mike     | 1A               | 27

Thank you in advance


问:
Codename One API to append / merge files
To merge Storage files in Codename One I elaborated this solution:

```<code>    /**
     * Merges the given list of Storage files in the output Storage file.
     * @param toBeMerged
     * @param output
     * @throws IOException
     */
    public static synchronized void mergeStorageFiles(List<String> toBeMerged, String output) throws IOException {

        if (toBeMerged.contains(output)) {
            throw new IllegalArgumentException("The output file cannot be contained in the toBeMerged list of input files.");
        }

        // Note: the temporary file used for merging is placed in the FileSystemStorage because it offers the method
        // openOutputStream(String file, int offset) that allows appending to a stream. Storage doesn't have a such method.

        long writtenBytes = 0;
        String tempFile = FileSystemStorage.getInstance().getAppHomePath() + "/tempFileUsedInMerge";
        for (String partialFile : toBeMerged) {
            InputStream in = Storage.getInstance().createInputStream(partialFile);
            OutputStream out = FileSystemStorage.getInstance().openOutputStream(tempFile, (int) writtenBytes);
            Util.copy(in, out);
            writtenBytes = FileSystemStorage.getInstance().getLength(tempFile);
        }
        Util.copy(FileSystemStorage.getInstance().openInputStream(tempFile), Storage.getInstance().createOutputStream(output));
        FileSystemStorage.getInstance().delete(tempFile);
    }
</code>```

This solution is based on the API FileSystemStorage.openOutputStream(String file, int offset), that is the only API that I found to allow to append the content of a file to another.

Are there other API that can be used to append or merge files?

Thank you

答:
Since you end up copying everything to a Storage entry I don't see the value of using FileSystemStorage as an intermediate merging tool.

The only reason I can think of is integrity of the output file (e.g. if failure happens while writing) but that can happen here too. You can guarantee integrity by setting a flag e.g. creating a file called "writeLock" and deleting it when write has finished successfully.

To be clear I would copy like this which is simpler/faster:

```<code>try(OutputStream out = Storage.getInstance().createOutputStream(output)) {
    for (String partialFile : toBeMerged) {
        try(InputStream in = Storage.getInstance().createInputStream(partialFile)) {
            Util.copyNoClose(in, out, 8192);
        }
    }
}
</code>```

Body:
To merge Storage files in Codename One I elaborated this solution:

    /**
     * Merges the given list of Storage files in the output Storage file.
     * @param toBeMerged
     * @param output
     * @throws IOException
     */
    public static synchronized void mergeStorageFiles(List<String> toBeMerged, String output) throws IOException {

        if (toBeMerged.contains(output)) {
            throw new IllegalArgumentException("The output file cannot be contained in the toBeMerged list of input files.");
        }

        // Note: the temporary file used for merging is placed in the FileSystemStorage because it offers the method
        // openOutputStream(String file, int offset) that allows appending to a stream. Storage doesn't have a such method.

        long writtenBytes = 0;
        String tempFile = FileSystemStorage.getInstance().getAppHomePath() + "/tempFileUsedInMerge";
        for (String partialFile : toBeMerged) {
            InputStream in = Storage.getInstance().createInputStream(partialFile);
            OutputStream out = FileSystemStorage.getInstance().openOutputStream(tempFile, (int) writtenBytes);
            Util.copy(in, out);
            writtenBytes = FileSystemStorage.getInstance().getLength(tempFile);
        }
        Util.copy(FileSystemStorage.getInstance().openInputStream(tempFile), Storage.getInstance().createOutputStream(output));
        FileSystemStorage.getInstance().delete(tempFile);
    }

This solution is based on the API FileSystemStorage.openOutputStream(String file, int offset), that is the only API that I found to allow to append the content of a file to another.

Are there other API that can be used to append or merge files?

Thank you

Body:
Since you end up copying everything to a Storage entry I don't see the value of using FileSystemStorage as an intermediate merging tool.

The only reason I can think of is integrity of the output file (e.g. if failure happens while writing) but that can happen here too. You can guarantee integrity by setting a flag e.g. creating a file called "writeLock" and deleting it when write has finished successfully.

To be clear I would copy like this which is simpler/faster:

try(OutputStream out = Storage.getInstance().createOutputStream(output)) {
    for (String partialFile : toBeMerged) {
        try(InputStream in = Storage.getInstance().createInputStream(partialFile)) {
            Util.copyNoClose(in, out, 8192);
        }
    }
}


问:
CSV reading with Python
I have about 20 rows of data with 4 columns each.
How do I print only a certain row. Like for instance print only Row 15, Row 16 and Row 17.
When I try row[0] it only prints out the first column but not the entire row. I am confused here.

Right now I can read out each of the rows by doing:

for lines in reader:
    print(lines)

答:
Try iloc method</p>

```<code>import pandas as pd
## suppose you want 15 row only
data=pd.read_csv("data.csv").iloc[14,:]
</code>```

Title: CSV reading with Python

Body:
Try iloc method

import pandas as pd
## suppose you want 15 row only
data=pd.read_csv("data.csv").iloc[14,:]


答:
If you have relatively small dataset you can read the entire thing and select the rows you want

```<code>reader = csv.reader(open("somefile.csv"))
table = list(reader) # reads entire file
for row in table[15:18]:
    print(row)
</code>```

You could also save a bit of time by only reading as much as you need

```<code>with open("somefile.csv") as f:
    reader = csv.reader(f)
    for _ in range(14):
        next(reader)  # dicarc
    for _ in range(3):
        print(next(reader))
</code>```

Title: CSV reading with Python

Body:
I have about 20 rows of data with 4 columns each.
How do I print only a certain row. Like for instance print only Row 15, Row 16 and Row 17.
When I try row[0] it only prints out the first column but not the entire row. I am confused here.

Right now I can read out each of the rows by doing:

for lines in reader:
    print(lines)

Body:
If you have relatively small dataset you can read the entire thing and select the rows you want

reader = csv.reader(open("somefile.csv"))
table = list(reader) # reads entire file
for row in table[15:18]:
    print(row)

You could also save a bit of time by only reading as much as you need

with open("somefile.csv") as f:
    reader = csv.reader(f)
    for _ in range(14):
        next(reader)  # dicarc
    for _ in range(3):
        print(next(reader))


问:
Set WTForms submit button to icon
I want a submit button that displays an icon rather than text.  The button is a field in a WTForms form.  I am using Bootstrap and Open Iconic for styling and icons.  How do I set the submit field to display an icon?

```<code>class MyForm(Form):
    submit = SubmitField('')
</code>```

```<code>{{ form.submit }}
</code>```

This post refers to an icon method, but I can't find any more information on it.

答:
I had a similar problem, so, you can do this to use wtforms, and simply call {{ render_temple(form) }} in html to get this result.

```<code>class InlineButtonWidget(object):
    def __init__(self, class_=None):
        self.class_ = class_

    def __call__(self, field, **kwargs):
        kwargs.setdefault('type', 'submit')
        kwargs["class"] = self.class_
        title = kwargs.pop('title', field.description or '')
        params = html_params(title=title, **kwargs)

        html = '<button %s>%s</button>'
        return HTMLString(html % (params, escape(field.label.text)))

class InlineButton(Field):
    widget = InlineButtonWidget()

    def __init__(self, label=None, validators=None, text='Save', **kwargs):
        super(InlineButton, self).__init__(label, validators, **kwargs)
        self.text = text

    def _value(self):
        if self.data:
            return u''.join(self.data)
        else:
            return u''
</code>```

Usage:

```<code>class BookForm(FlaskForm):
    text = Markup('<i class="fas fa-sign-in-alt"></i> Submit')
    submit = SubmitField(text, widget=InlineButtonWidget(class_="btn btn-info")) #This class_ param it's applied in the class of the button in HTML.
</code>```

Output:

Html code

Display

My reply is based on this post WTForms creating a custom widget.

Title: Set WTForms submit button to icon

Body:
I want a submit button that displays an icon rather than text.  The button is a field in a WTForms form.  I am using Bootstrap and Open Iconic for styling and icons.  How do I set the submit field to display an icon?

class MyForm(Form):
    submit = SubmitField('')

{{ form.submit }}

This post refers to an icon method, but I can't find any more information on it.

Body:
I had a similar problem, so, you can do this to use wtforms, and simply call {{ render_temple(form) }} in html to get this result.

class InlineButtonWidget(object):
    def __init__(self, class_=None):
        self.class_ = class_

    def __call__(self, field, **kwargs):
        kwargs.setdefault('type', 'submit')
        kwargs["class"] = self.class_
        title = kwargs.pop('title', field.description or '')
        params = html_params(title=title, **kwargs)

        html = '<button %s>%s</button>'
        return HTMLString(html % (params, escape(field.label.text)))

class InlineButton(Field):
    widget = InlineButtonWidget()

    def __init__(self, label=None, validators=None, text='Save', **kwargs):
        super(InlineButton, self).__init__(label, validators, **kwargs)
        self.text = text

    def _value(self):
        if self.data:
            return u''.join(self.data)
        else:
            return u''

Usage:

class BookForm(FlaskForm):
    text = Markup('<i class="fas fa-sign-in-alt"></i> Submit')
    submit = SubmitField(text, widget=InlineButtonWidget(class_="btn btn-info")) #This class_ param it's applied in the class of the button in HTML.

Output:

Html code

Display

My reply is based on this post WTForms creating a custom widget.


问:
Is there a way to set the "select" options on a per-cell or per-row basis within a column in Tabulator?
I would like to know if there is a way to set the Tabulator select options by both row and column?  For example, the following Tabulator table setup contains a column definition with a "select" editor and parameters:

```<code>var table = new Tabulator("#myDiv"), {
    height: "100%",
    data: [],
    columns: [
        { title: "Project ID", field: "Projectid", responsive: 0, hozAlign: "center", editor: "autocomplete", editorParams: { values: projectIdList } },
        { title: "Phase Code", field: "Phasecode", responsive: 0, hozAlign: "center", editor: "select", editorParams: { values: laborPhaseCodes } }
    ]
});
</code>```

The "select" editor refers to an array to acquire its values inside the editorParams.  This creates the same dropdown list of options for each row/cell in the Phasecode column.

What I would like to do is populate the values list with a set of options applicable to the selected value from the Projectid column on a row-by-row basis.  Stated differently, the Projectid code will be different for each row and the Phasecode options are unique for each Projectid.  Consequently, when the user makes a Projectid selection, I would like to refresh the Phasecode options for that row only.

Can it be done?

Any assistance is greatly appreciated.

答:
Found the answer in the Tabulator documentation.  Yes, it is possible to trigger each cell in a column to load its own list of options.  From the Tabluator documentation:

```<code>editorParams: function (cell) { return { values: myArray}; }
</code>```

Body:
I would like to know if there is a way to set the Tabulator select options by both row and column?  For example, the following Tabulator table setup contains a column definition with a "select" editor and parameters:

var table = new Tabulator("#myDiv"), {
    height: "100%",
    data: [],
    columns: [
        { title: "Project ID", field: "Projectid", responsive: 0, hozAlign: "center", editor: "autocomplete", editorParams: { values: projectIdList } },
        { title: "Phase Code", field: "Phasecode", responsive: 0, hozAlign: "center", editor: "select", editorParams: { values: laborPhaseCodes } }
    ]
});

The "select" editor refers to an array to acquire its values inside the editorParams.  This creates the same dropdown list of options for each row/cell in the Phasecode column.

What I would like to do is populate the values list with a set of options applicable to the selected value from the Projectid column on a row-by-row basis.  Stated differently, the Projectid code will be different for each row and the Phasecode options are unique for each Projectid.  Consequently, when the user makes a Projectid selection, I would like to refresh the Phasecode options for that row only.

Can it be done?

Any assistance is greatly appreciated.

Body:
Found the answer in the Tabulator documentation.  Yes, it is possible to trigger each cell in a column to load its own list of options.  From the Tabluator documentation:

editorParams: function (cell) { return { values: myArray}; }


问:
Efficiency of numpy.dot with dynamic vs. static arrays
I have to do a lot of dot products in my data processing pipeline. So, I was experimenting with the following two pieces of code where one is 3 times efficient (in terms of runtime) when compared to its slowest counterpart.

slowest method (with arrays created on the fly)

```<code>In [33]: %timeit np.dot(np.arange(200000), np.arange(200000, 400000))
352 µs ± 958 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code>```

fastest method (with static arrays)

```<code>In [34]: vec1_arr = np.arange(200000)
In [35]: vec2_arr = np.arange(200000, 400000)

In [36]: %timeit np.dot(vec1_arr, vec2_arr)
121 µs ± 90.3 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code>```

why is the first method of dynamically generating arrays 3x slower when compared to second method? Is it because in the first method much of these extra time is spent in allocating memory for the elements? Or some other factors contributing to this degradation?

To gain little more understanding, I also replicated the setup in pure Python. And surprisingly there is no performance difference between doing it one way or the other, although it is slower than the numpy implementation, which is obvious and expected.

```<code>In [42]: %timeit sum(map(operator.mul, range(200000), range(200000, 400000)))
12.5 ms ± 71.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

```<code>In [38]: vec1 = range(200000)
In [39]: vec2 = range(200000, 400000)

In [40]: %timeit sum(map(operator.mul, vec1, vec2))
12.5 ms ± 27.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

The behaviour in the case of pure Python is clear because range function doesn't actually create all those elements. It does lazy evaluation (i.e. it is generated on the fly).

Note: The pure Python impl. is just to make myself convinced that the array allocation might be the factor that is causing the drag. It's not meant to compare it with NumPy implementation.

答:
The difference in speed is due to allocating the arrays in the slower case. I pasted the output of %timeit that takes into account the allocation of arrays in the two cases. The OP's timeit commands only took into account allocation in the slower case but not in the faster case.

```<code>%timeit np.dot(np.arange(200000), np.arange(200000, 400000))
# 524 µs ± 11.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code>```

```<code>%timeit vec1_arr = np.arange(200000);  vec2_arr = np.arange(200000, 400000); np.dot(vec1_arr, vec2_arr)
# 523 µs ± 17.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code>```

The allocation of both arrays takes about 360 microseconds on my machine, and the np.dot operation takes 169 microseconds. The sum of those two durations is 529 microseconds, which is equivalent to the output of %timeit output above.

```<code>%timeit vec1_arr = np.arange(200000);  vec2_arr = np.arange(200000, 400000)
# 360 µs ± 16.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

vec1_arr = np.arange(200000)
vec2_arr = np.arange(200000, 400000)

%timeit np.dot(vec1_arr, vec2_arr)
# 169 µs ± 5.24 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code>```

Body:
I have to do a lot of dot products in my data processing pipeline. So, I was experimenting with the following two pieces of code where one is 3 times efficient (in terms of runtime) when compared to its slowest counterpart.

slowest method (with arrays created on the fly)

In [33]: %timeit np.dot(np.arange(200000), np.arange(200000, 400000))
352 µs ± 958 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)

fastest method (with static arrays)

In [34]: vec1_arr = np.arange(200000)
In [35]: vec2_arr = np.arange(200000, 400000)

In [36]: %timeit np.dot(vec1_arr, vec2_arr)
121 µs ± 90.3 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

why is the first method of dynamically generating arrays 3x slower when compared to second method? Is it because in the first method much of these extra time is spent in allocating memory for the elements? Or some other factors contributing to this degradation?

To gain little more understanding, I also replicated the setup in pure Python. And surprisingly there is no performance difference between doing it one way or the other, although it is slower than the numpy implementation, which is obvious and expected.

In [42]: %timeit sum(map(operator.mul, range(200000), range(200000, 400000)))
12.5 ms ± 71.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [38]: vec1 = range(200000)
In [39]: vec2 = range(200000, 400000)

In [40]: %timeit sum(map(operator.mul, vec1, vec2))
12.5 ms ± 27.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

The behaviour in the case of pure Python is clear because range function doesn't actually create all those elements. It does lazy evaluation (i.e. it is generated on the fly).

Note: The pure Python impl. is just to make myself convinced that the array allocation might be the factor that is causing the drag. It's not meant to compare it with NumPy implementation.

Body:
The difference in speed is due to allocating the arrays in the slower case. I pasted the output of %timeit that takes into account the allocation of arrays in the two cases. The OP's timeit commands only took into account allocation in the slower case but not in the faster case.

%timeit np.dot(np.arange(200000), np.arange(200000, 400000))
# 524 µs ± 11.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit vec1_arr = np.arange(200000);  vec2_arr = np.arange(200000, 400000); np.dot(vec1_arr, vec2_arr)
# 523 µs ± 17.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

The allocation of both arrays takes about 360 microseconds on my machine, and the np.dot operation takes 169 microseconds. The sum of those two durations is 529 microseconds, which is equivalent to the output of %timeit output above.

%timeit vec1_arr = np.arange(200000);  vec2_arr = np.arange(200000, 400000)
# 360 µs ± 16.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

vec1_arr = np.arange(200000)
vec2_arr = np.arange(200000, 400000)

%timeit np.dot(vec1_arr, vec2_arr)
# 169 µs ± 5.24 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)


问:
Macro to Save As spreadsheet in same folder
I am trying to Save As an excel spreadsheet into the same folder that the original Excel file is in.

Currently, the file is saved on my Desktop.

However, when I run this code, it saves it to my Documents folder.

I do not want to hard code it to save to my Desktop everytime, but wherever the original Excel happens to be.

My attempt below. Thank you for your help!

```<code>ActiveWorkbook.SaveAs filename:="Name"
</code>```

答:
here for ur ref.</p>

```<code>Sub testSave()
'using Application.PathSeparator to identfy the "/" or "\"
strPath = ThisWorkbook.Path & Application.PathSeparator
fName = "yourfilename"

' 51 means *.xlsx, for detais, check https://learn.microsoft.com/zh-cn/office/vba/api/excel.xlfileformat

ActiveWorkbook.SaveAs Filename:=strPath & fName, FileFormat:=51

End Sub
</code>```

Body:
I am trying to Save As an excel spreadsheet into the same folder that the original Excel file is in.

Currently, the file is saved on my Desktop.

However, when I run this code, it saves it to my Documents folder.

I do not want to hard code it to save to my Desktop everytime, but wherever the original Excel happens to be.

My attempt below. Thank you for your help!

ActiveWorkbook.SaveAs filename:="Name"

Body:
here for ur ref.

Sub testSave()
'using Application.PathSeparator to identfy the "/" or "\"
strPath = ThisWorkbook.Path & Application.PathSeparator
fName = "yourfilename"

' 51 means *.xlsx, for detais, check https://learn.microsoft.com/zh-cn/office/vba/api/excel.xlfileformat

ActiveWorkbook.SaveAs Filename:=strPath & fName, FileFormat:=51

End Sub


问:
Basic HTTP authentication with Node and Express 4
It looks like implementing basic HTTP authentication with Express v3 was trivial:

```<code>app.use(express.basicAuth('username', 'password'));
</code>```

Version 4 (I'm using 4.2) removed the basicAuth middleware, though, so I'm a little stuck. I have the following code, but it doesn't cause the browser to prompt the user for credentials, which is what I'd like (and what I imagine the old method did):

```<code>app.use(function(req, res, next) {
    var user = auth(req);

    if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
        res.writeHead(401, 'Access invalid for user', {'Content-Type' : 'text/plain'});
        res.end('Invalid credentials');
    } else {
        next();
    }
});
</code>```

答:
```<code>function auth (req, res, next) {
  console.log(req.headers);
  var authHeader = req.headers.authorization;
  if (!authHeader) {
      var err = new Error('You are not authenticated!');
      res.setHeader('WWW-Authenticate', 'Basic');
      err.status = 401;
      next(err);
      return;
  }
  var auth = new Buffer.from(authHeader.split(' ')[1], 'base64').toString().split(':');
  var user = auth[0];
  var pass = auth[1];
  if (user == 'admin' && pass == 'password') {
      next(); // authorized
  } else {
      var err = new Error('You are not authenticated!');
      res.setHeader('WWW-Authenticate', 'Basic');
      err.status = 401;
      next(err);
  }
}
app.use(auth);
</code>```

Body:
It looks like implementing basic HTTP authentication with Express v3 was trivial:

app.use(express.basicAuth('username', 'password'));

Version 4 (I'm using 4.2) removed the basicAuth middleware, though, so I'm a little stuck. I have the following code, but it doesn't cause the browser to prompt the user for credentials, which is what I'd like (and what I imagine the old method did):

app.use(function(req, res, next) {
    var user = auth(req);

    if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
        res.writeHead(401, 'Access invalid for user', {'Content-Type' : 'text/plain'});
        res.end('Invalid credentials');
    } else {
        next();
    }
});


问:
How can moment.js be imported with typescript?
I'm trying to learn Typescript. While I don't think it's relevant, I'm using VSCode for this demo.

I have a package.json that has these pieces in it:

```<code>{
  "devDependencies": {
    "gulp": "^3.9.1",
    "jspm": "^0.16.33",
    "typescript": "^1.8.10"
  },
  "jspm": {
    "moment": "npm:moment@^2.12.0"
  }
}
</code>```

Then I have a Typescript class main.js like this:

```<code>import moment from 'moment';
export class Main {
}
</code>```

My gulpfile.js looks like this:

```<code>var gulp = require('gulp');
var typescript = require('gulp-tsb');
var compilerOptions = {
                        "rootDir": "src/",
                        "sourceMap": true,
                        "target": "es5",
                        "module": "amd",
                        "declaration": false,
                        "noImplicitAny": false,
                        "noResolve": true,
                        "removeComments": true,
                        "noLib": false,
                        "emitDecoratorMetadata": true,
                        "experimentalDecorators": true
                      };
var typescriptCompiler = typescript.create(compilerOptions);
gulp.task('build', function() {
  return gulp.src('/src')
    .pipe(typescriptCompiler())
    .pipe(gulp.dest('/dest'));
});
</code>```

When I run gulp build, I get the message: "../main.ts(1,25): Cannot file module 'moment'."

If I use import moment = require('moment'); then jspm will work and bring in the module when I run the application, but I'm still receiving the build error.
I also tried:

```<code>npm install typings -g
typings install moment --ambient --save
</code>```

Instead of making the problem better though, it got worse. Now I get the above error on build as well as the following: "../typings/browser/ambient/moment/index.d.ts(9,21): Cannot find namespace 'moment'."

If I go to the file provided by typings and add at the bottom of the file:

```<code>declare module "moment" { export = moment; }
</code>```

I can get the second error to go away, but I still need the require statement to get moment to work in my main.ts file and am still getting the first build error.

Do I need to create my own .d.ts file for moment or is there just some setup piece I'm missing?

答:
Still broken? Try uninstalling @types/moment.

So, I removed @types/moment package from the package.json file and it worked using:

import * as moment from 'moment'
```

Newer versions of moment don't require the @types/moment package as types are already included.

Body:
I'm trying to learn Typescript. While I don't think it's relevant, I'm using VSCode for this demo.

I have a package.json that has these pieces in it:

{
  "devDependencies": {
    "gulp": "^3.9.1",
    "jspm": "^0.16.33",
    "typescript": "^1.8.10"
  },
  "jspm": {
    "moment": "npm:moment@^2.12.0"
  }
}

Then I have a Typescript class main.js like this:

import moment from 'moment';
export class Main {
}

My gulpfile.js looks like this:

var gulp = require('gulp');
var typescript = require('gulp-tsb');
var compilerOptions = {
                        "rootDir": "src/",
                        "sourceMap": true,
                        "target": "es5",
                        "module": "amd",
                        "declaration": false,
                        "noImplicitAny": false,
                        "noResolve": true,
                        "removeComments": true,
                        "noLib": false,
                        "emitDecoratorMetadata": true,
                        "experimentalDecorators": true
                      };
var typescriptCompiler = typescript.create(compilerOptions);
gulp.task('build', function() {
  return gulp.src('/src')
    .pipe(typescriptCompiler())
    .pipe(gulp.dest('/dest'));
});

When I run gulp build, I get the message: "../main.ts(1,25): Cannot file module 'moment'."

If I use import moment = require('moment'); then jspm will work and bring in the module when I run the application, but I'm still receiving the build error.
I also tried:

npm install typings -g
typings install moment --ambient --save

Instead of making the problem better though, it got worse. Now I get the above error on build as well as the following: "../typings/browser/ambient/moment/index.d.ts(9,21): Cannot find namespace 'moment'."

If I go to the file provided by typings and add at the bottom of the file:

declare module "moment" { export = moment; }

I can get the second error to go away, but I still need the require statement to get moment to work in my main.ts file and am still getting the first build error.

Do I need to create my own .d.ts file for moment or is there just some setup piece I'm missing?

Body:
Still broken? Try uninstalling @types/moment.

So, I removed @types/moment package from the package.json file and it worked using:

import * as moment from 'moment'

Newer versions of moment don't require the @types/moment package as types are already included.


问:
How can I multiply together every nth cell in a row to get the product?
I want to calculate the product of the investment returns (compound interest), which in this instance would give a return of 162%:

Additional stock return data will be added in future, so I need a formula that compounds every nth (2nd) value. I am able to sum the cells using:
=SUMIF(ARRAYFORMULA(MOD((COLUMN(A2:H2)-COLUMN(A2)+1),2)),0,A2:H2)

However I cannot find an equivalent 'PRODUCTIF' function and have not been able to make a formula that works. Writing the formula out long hand would be:
=B2*D2*F2*H2

答:
I guess i'm a little confused.  doesn't PRODUCT() just ignore text?

Doesn't =PRODUCT(2:2) work?


问:
ASP.NET Web Service Application in .net 4
I was going through the MSDN walkthrough on using client application services.
http://msdn.microsoft.com/en-us/library/bb546195.aspx

This is for .net 3.5..but i need to do it in .net 4. The thing is that it doesn't have any ASP.NET Web Service Applications listed. Has it introduced any replacement for that? Or is there any workaround?

Regards.

答:
Instead web services use WCF, it has more features than asp.net Web Services

http://msdn.microsoft.com/en-us/library/ms731082.aspx


问:
Input/Output Operators Overloading in C++
Stuck with ostream/istream operator overloading
Q1. why we are using ostream& operator as friend?
Q2. Why we are passing two arguments in ostream & operator << (ostream &out, const Complex &c)
Q3. why we are referencing to Cout and in ? istream & operator >> (istream &in, Complex &c).

Ref to: Overloading stream Oerator overloading- Geeks4Geeks

HERE IS THE CODE

```<code>#include <iostream>
using namespace std;

class Complex
{
private:
    int real, imag;
public:
    Complex(int r = 0, int i =0)
    { real = r; imag = i; }
    friend ostream & operator << (ostream &out, const Complex &c);
    friend istream & operator >> (istream &in, Complex &c);
};

ostream & operator << (ostream &out, const Complex &c)
{
    out << c.real;
    out << "+i" << c.imag << endl;
    return out;
}

istream & operator >> (istream &in, Complex &c)
{
    cout << "Enter Real Part ";
    in >> c.real;
    cout << "Enter Imaginary Part ";
    in >> c.imag;
    return in;
}

int main()
{
Complex c1;
cin >> c1;
cout << "The complex object is ";
cout << c1;
return 0;
}

</code>```

答:
A1. To access the private members

A2. The first argument is the stream and the second is the object. operator<< and operator>> expect two arguments

A3. Because they are modified in the function. The functions read from resp. write into the stream.

In addition:

Don't use using namespace std;

Don't initialize members in the constructor body. Use the constructor initializer list

```<code>Complex(int r = 0, int i =0)
{ real = r; imag = i; }
</code>```

should be

```<code>Complex(int r = 0, int i = 0) : real(r), imag(i) {}
</code>```

Body:
Stuck with ostream/istream operator overloading
Q1. why we are using ostream& operator as friend?
Q2. Why we are passing two arguments in ostream & operator << (ostream &out, const Complex &c)
Q3. why we are referencing to Cout and in ? istream & operator >> (istream &in, Complex &c).

Ref to: Overloading stream Oerator overloading- Geeks4Geeks

HERE IS THE CODE

#include <iostream>
using namespace std;

class Complex
{
private:
    int real, imag;
public:
    Complex(int r = 0, int i =0)
    { real = r; imag = i; }
    friend ostream & operator << (ostream &out, const Complex &c);
    friend istream & operator >> (istream &in, Complex &c);
};

ostream & operator << (ostream &out, const Complex &c)
{
    out << c.real;
    out << "+i" << c.imag << endl;
    return out;
}

istream & operator >> (istream &in, Complex &c)
{
    cout << "Enter Real Part ";
    in >> c.real;
    cout << "Enter Imaginary Part ";
    in >> c.imag;
    return in;
}

int main()
{
Complex c1;
cin >> c1;
cout << "The complex object is ";
cout << c1;
return 0;
}

Body:
A1. To access the private members

A2. The first argument is the stream and the second is the object. operator<< and operator>> expect two arguments

A3. Because they are modified in the function. The functions read from resp. write into the stream.

In addition:

Don't use using namespace std;

Don't initialize members in the constructor body. Use the constructor initializer list

Complex(int r = 0, int i =0)
{ real = r; imag = i; }

should be

Complex(int r = 0, int i = 0) : real(r), imag(i) {}


问:
Why the gameobject blue axis is facing forward but the gun is on the red axis and not the blue?
I tried to create a empty gameobject and put the first gameobject as child but it didn't fix the problem.
Just rotating the object a script is fine but if I'm using LookAt it's not rotating good since the gun is pointing on the red axis and the blue axis is on the body.

Wrong axis

I tried simple LookAt :

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LookAT : MonoBehaviour
{
    private GameObject target;

    // Use this for initialization
    void Start()
    {
       target = GameObject.FindGameObjectWithTag("Enemy");
    }
    // Update is called once per frame
    void Update()
    {
        transform.LookAt(target.transform);
    }
}
</code>```

Then I tried this : This was a bit better it seems like it was facing with the red axis forward with the gun but not perfect still it didn't target perfect the target I think not sure and not sure if this is a good solution :

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LookAT : MonoBehaviour
{
    public float speed;

    private GameObject target;

    // Use this for initialization
    void Start()
    {
        target = GameObject.FindGameObjectWithTag("Enemy");
    }
    // Update is called once per frame
    void Update()
    {
        Vector3 direction = target.transform.position - transform.position;
        Quaternion toRotation = Quaternion.FromToRotation(transform.right, direction);
        transform.rotation = Quaternion.Lerp(transform.rotation, toRotation, speed * Time.time);
    }
}
</code>```

The second solution I tried seems the red axis with the gun is facing the target now but the gun and the rings on the base are stuttering and the rings rotating too but they should not rotate I think or they should not be part of the looking on the target.

In this screenshot the whole rings on the base are kind of looking at the target and make the whole turret looks strange. So I'm not sure how ot make this rings and other stuff rotating while only the turret turn object will face the target.

Wrong stuff is rotating and looking facing the target

答:
Looks like the model has axis that don't line up with how you want to use it. Its reccomended that you fix the model, but alternatively you can also add a parent transform on top so you can add some rotation to your model.

Check this out for a more detailed explanation.

To get the two discrete axis of rotation thing I think you are describing at the end of your post you can add two parents as described in the post I linked and apply rotations to each of those parents individually.

Body:
I tried to create a empty gameobject and put the first gameobject as child but it didn't fix the problem.
Just rotating the object a script is fine but if I'm using LookAt it's not rotating good since the gun is pointing on the red axis and the blue axis is on the body.

Wrong axis

I tried simple LookAt :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LookAT : MonoBehaviour
{
    private GameObject target;

    // Use this for initialization
    void Start()
    {
       target = GameObject.FindGameObjectWithTag("Enemy");
    }
    // Update is called once per frame
    void Update()
    {
        transform.LookAt(target.transform);
    }
}

Then I tried this : This was a bit better it seems like it was facing with the red axis forward with the gun but not perfect still it didn't target perfect the target I think not sure and not sure if this is a good solution :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LookAT : MonoBehaviour
{
    public float speed;

    private GameObject target;

    // Use this for initialization
    void Start()
    {
        target = GameObject.FindGameObjectWithTag("Enemy");
    }
    // Update is called once per frame
    void Update()
    {
        Vector3 direction = target.transform.position - transform.position;
        Quaternion toRotation = Quaternion.FromToRotation(transform.right, direction);
        transform.rotation = Quaternion.Lerp(transform.rotation, toRotation, speed * Time.time);
    }
}

The second solution I tried seems the red axis with the gun is facing the target now but the gun and the rings on the base are stuttering and the rings rotating too but they should not rotate I think or they should not be part of the looking on the target.

In this screenshot the whole rings on the base are kind of looking at the target and make the whole turret looks strange. So I'm not sure how ot make this rings and other stuff rotating while only the turret turn object will face the target.

Wrong stuff is rotating and looking facing the target


答:
The pure Python test is not fair. Because np.arange(200000) really returns an array while range(200000) only returns a generator. So these two methods both create arrays on the fly.

```<code>import operator

%timeit sum(map(operator.mul, range(200000), range(200000, 400000)))
# 15.1 ms ± 45.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

vec1 = range(200000)
vec2 = range(200000, 400000)
%timeit sum(map(operator.mul, vec1, vec2))
# 15.2 ms ± 117 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

vec1 = list(range(200000))
vec2 = list(range(200000, 400000))

%timeit sum(map(operator.mul, vec1, vec2))
# 12.4 ms ± 716 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

And we can see the time cost on allocation:

```<code>import numpy as np

%timeit np.arange(200000), np.arange(200000, 400000)
# 632 µs ± 9.45 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit np.dot(np.arange(200000), np.arange(200000, 400000))
# 703 µs ± 5.27 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

vec1_arr = np.arange(200000)
vec2_arr = np.arange(200000, 400000)

%timeit np.dot(vec1_arr, vec2_arr)
# 77.7 µs ± 427 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code>```

Make sense.

Title: Efficiency of numpy.dot with dynamic vs. static arrays

Body:
The pure Python test is not fair. Because np.arange(200000) really returns an array while range(200000) only returns a generator. So these two methods both create arrays on the fly.

import operator

%timeit sum(map(operator.mul, range(200000), range(200000, 400000)))
# 15.1 ms ± 45.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

vec1 = range(200000)
vec2 = range(200000, 400000)
%timeit sum(map(operator.mul, vec1, vec2))
# 15.2 ms ± 117 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

vec1 = list(range(200000))
vec2 = list(range(200000, 400000))

%timeit sum(map(operator.mul, vec1, vec2))
# 12.4 ms ± 716 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

And we can see the time cost on allocation:

import numpy as np

%timeit np.arange(200000), np.arange(200000, 400000)
# 632 µs ± 9.45 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit np.dot(np.arange(200000), np.arange(200000, 400000))
# 703 µs ± 5.27 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

vec1_arr = np.arange(200000)
vec2_arr = np.arange(200000, 400000)

%timeit np.dot(vec1_arr, vec2_arr)
# 77.7 µs ± 427 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Make sense.


问:
Trying to segment characters using opencv - Ilumination problem
My code it's not detecting well binary image!

```<code>LpImg = cv2.imread('/content/drive/My Drive/TESTING/Placas_detectadas/CPVL92.png')

if (len(LpImg)): #check if there is at least one license image
    # Scales, calculates absolute values, and converts the result to 8-bit.

    plate_image = cv2.convertScaleAbs(LpImg[0], alpha=(255.0))
    plate_image = LpImg #image_cropped

    # convert to grayscale and blur the image
    gray = cv2.cvtColor(plate_image, cv2.COLOR_BGR2GRAY)

    blur = cv2.GaussianBlur(gray,(7,7),0)

    # Applied inversed thresh_binary
    thresh_inv = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 39, 1)
    #binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

    kernel3 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    thre_mor = cv2.morphologyEx(thresh_inv, cv2.MORPH_DILATE, kernel3)

# visualize results
fig = plt.figure(figsize=(12,7))
plt.rcParams.update({"font.size":18})
grid = gridspec.GridSpec(ncols=2,nrows=3,figure = fig)
plot_image = [plate_image, gray, blur, thresh_inv,thre_mor]
plot_name = ["plate_image","gray","blur","binary","dilation"]

for i in range(len(plot_image)):
    fig.add_subplot(grid[i])
    plt.axis(False)
    plt.title(plot_name[i])
    if i ==0:
        plt.imshow(plot_image[i])
    else:
        plt.imshow(plot_image[i],cmap="gray")
</code>```

This is the image:

With this results:

If I use adaptive threshhold

```<code>binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
</code>```

to this line

```<code>thresh_inv = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 39, 1)
</code>```

I have got this result:

Why this is happening? How can I solve it?

I was thinking use this:

```<code>LpImg = cv2.imread('/content/image.png')

# Set scaling factors and add
gamma1 = 0.3
gamma2 = 1.5
Iout = gamma1*Ioutlow[0:rows,0:cols] + gamma2*Iouthigh[0:rows,0:cols]

# Anti-log then rescale to [0,1]
Ihmf = np.expm1(Iout)
Ihmf = (Ihmf - np.min(Ihmf)) / (np.max(Ihmf) - np.min(Ihmf))
Ihmf2 = np.array(255*LpImg, dtype="uint8")

# Threshold the image - Anything below intensity 65 gets set to white
Ithresh = Ihmf2 < 65 #65
Ithresh = 255*Ithresh.astype("uint8")
Ihmf2 = np.array(255*Ihmf, dtype="uint8")

# Threshold the image - Anything below intensity 65 gets set to white
Ithresh = Ihmf2 < 65 #65

Ithresh = 255*Ithresh.astype("uint8")
</code>```

That have this result:

But I still want to use this filters:

Grayscale

Blur

Binarization

Segmentation

答:
Another approach is to use division normalization in Python/OpenCV.

Read the input

Convert to gray

Apply morphology dilation

Divide the input by the dilated image

Threshold

Save the results

Input:

```<code>import cv2
import numpy as np

# read the image
img = cv2.imread('license_chile.png')

# convert to gray
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# apply morphology
kernel = cv2.getStructuringElement(cv2.MORPH_RECT , (75,75))
smooth = cv2.morphologyEx(gray, cv2.MORPH_DILATE, kernel)

# divide gray by morphology image
division = cv2.divide(gray, smooth, scale=255)

# threshold
result = cv2.threshold(division, 0, 255, cv2.THRESH_OTSU )[1]

# save results
cv2.imwrite('license_chile_thresh.jpg',result)

# show results
cv2.imshow('smooth', smooth)
cv2.imshow('division', division)
cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Result:

Body:
My code it's not detecting well binary image!

LpImg = cv2.imread('/content/drive/My Drive/TESTING/Placas_detectadas/CPVL92.png')

if (len(LpImg)): #check if there is at least one license image
    # Scales, calculates absolute values, and converts the result to 8-bit.

    plate_image = cv2.convertScaleAbs(LpImg[0], alpha=(255.0))
    plate_image = LpImg #image_cropped

    # convert to grayscale and blur the image
    gray = cv2.cvtColor(plate_image, cv2.COLOR_BGR2GRAY)

    blur = cv2.GaussianBlur(gray,(7,7),0)

    # Applied inversed thresh_binary
    thresh_inv = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 39, 1)
    #binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

    kernel3 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    thre_mor = cv2.morphologyEx(thresh_inv, cv2.MORPH_DILATE, kernel3)

# visualize results
fig = plt.figure(figsize=(12,7))
plt.rcParams.update({"font.size":18})
grid = gridspec.GridSpec(ncols=2,nrows=3,figure = fig)
plot_image = [plate_image, gray, blur, thresh_inv,thre_mor]
plot_name = ["plate_image","gray","blur","binary","dilation"]

for i in range(len(plot_image)):
    fig.add_subplot(grid[i])
    plt.axis(False)
    plt.title(plot_name[i])
    if i ==0:
        plt.imshow(plot_image[i])
    else:
        plt.imshow(plot_image[i],cmap="gray")

This is the image:

With this results:

If I use adaptive threshhold

binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

to this line

thresh_inv = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 39, 1)

I have got this result:

Why this is happening? How can I solve it?

I was thinking use this:

LpImg = cv2.imread('/content/image.png')

# Set scaling factors and add
gamma1 = 0.3
gamma2 = 1.5
Iout = gamma1*Ioutlow[0:rows,0:cols] + gamma2*Iouthigh[0:rows,0:cols]

# Anti-log then rescale to [0,1]
Ihmf = np.expm1(Iout)
Ihmf = (Ihmf - np.min(Ihmf)) / (np.max(Ihmf) - np.min(Ihmf))
Ihmf2 = np.array(255*LpImg, dtype="uint8")

# Threshold the image - Anything below intensity 65 gets set to white
Ithresh = Ihmf2 < 65 #65
Ithresh = 255*Ithresh.astype("uint8")
Ihmf2 = np.array(255*Ihmf, dtype="uint8")

# Threshold the image - Anything below intensity 65 gets set to white
Ithresh = Ihmf2 < 65 #65

Ithresh = 255*Ithresh.astype("uint8")

That have this result:

But I still want to use this filters:

Grayscale

Blur

Binarization

Segmentation

Body:
Another approach is to use division normalization in Python/OpenCV.

Read the input

Convert to gray

Apply morphology dilation

Divide the input by the dilated image

Threshold

Save the results

Input:

import cv2
import numpy as np

# read the image
img = cv2.imread('license_chile.png')

# convert to gray
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# apply morphology
kernel = cv2.getStructuringElement(cv2.MORPH_RECT , (75,75))
smooth = cv2.morphologyEx(gray, cv2.MORPH_DILATE, kernel)

# divide gray by morphology image
division = cv2.divide(gray, smooth, scale=255)

# threshold
result = cv2.threshold(division, 0, 255, cv2.THRESH_OTSU )[1]

# save results
cv2.imwrite('license_chile_thresh.jpg',result)

# show results
cv2.imshow('smooth', smooth)
cv2.imshow('division', division)
cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result: