问:
insert multiple rows with one query using ms access db
I am trying to get multiple rows into a table hence my attempt to get the row number and put it into a for loop, the countC is exactly the same number of rows as the select statement, so the issue is not there

I'm using an oledb connection as my code is in vb asp.net but my database is in ms access 2003

```<code>For c As Integer = 1 To countC
        Dim cmdstring As String
        cmdstring = " INSERT INTO [KN - ProductionMachineAllocation] (BatchNo, ComponentID)
                  SELECT POH.BatchNo, SSCDD.ComponentID
                FROM (
                    SELECT ROW_NUMBER() OVER (ORDER BY BatchNo ASC) AS rownumber
                    ([KN - ProductionOrderHeader] AS POH
                    INNER JOIN [FG - End Product Codes] AS EPC
                        ON POH.ProductID = EPC.ProductID)
                    INNER JOIN ([KN - ProductionOrderDetails] AS POD
                    INNER JOIN [FG - Style Size Comp Def Details]  AS SSCDD
                        ON POD.SizeID = SSCDD.SizeID)
                        ON (POH.BatchNo = POD.BatchNo)
                            AND (EPC.StyleID = SSCDD.StyleID)
                    WHERE POH.BatchNo = '" & BatchNo & "'
                     )  AS temptablename
                WHERE rownumber IN (" & c & ");"
        Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Shantara Production IT.mdb")
        Dim cmd As New OleDbCommand(cmdstring)
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        cmd.Connection.Open()
        cmd.ExecuteNonQuery()
        cmd.Connection.Close()
    Next
</code>```

I found out that ms access doesn't support ROW_NUMBER() so I need to find another going through each row since ms access doesn't support multi row insert by insert into select statement such as mine, any suggestions around my problem?

答:
OK SO I finally found a way around it, it's a bit of a long process but basically I loaded the SELECT statement(with multiple rows) into a gridview table and the used a for loop to insert it into my insert into statement. bellow is my code:

Displaying into a table

```<code>    Dim Adapter As New OleDbDataAdapter
    Dim Data As New DataTable
    Dim SQL As String
    Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Shantara Production IT.mdb")
    Dim cmd As New OleDbCommand()
    grdvmachincomp.Visible = false
    SQL = "SELECT DISTINCT POH.BatchNo, SSCDD.ComponentID
                    FROM ([KN - ProductionOrderHeader] AS POH
                    INNER Join [FG - End Product Codes] AS EPC
                        On POH.ProductID = EPC.ProductID)
                    INNER Join([KN - ProductionOrderDetails] AS POD
                    INNER Join [FG - Style Size Comp Def Details]  AS SSCDD
                        On POD.SizeID = SSCDD.SizeID)
                        On (POH.BatchNo = POD.BatchNo)
                            And (EPC.StyleID = SSCDD.StyleID)
                    WHERE POH.BatchNo = '" & BatchNo & "'"
    con.Open()
    cmd.Connection = con
    cmd.CommandText = SQL

    Adapter.SelectCommand = cmd
    Adapter.Fill(Data)

    grdvmachincomp.DataSource = Data
    grdvmachincomp.DataBind()
    cmd.Connection.Close()
</code>```

Insert into through for loop

```<code>For c As Integer = 0 To grdvmachincomp.Rows.Count - 1
        Dim cmdstring As String
        cmdstring = " INSERT INTO [KN - ProductionMachineAllocation] (BatchNo, ComponentID) VALUES('" & grdvmachincomp.Rows(c).Cells(0).Text & "', " & grdvmachincomp.Rows(c).Cells(1).Text & ");"
        Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Shantara Production IT.mdb")
        Dim cmd As New OleDbCommand(cmdstring)
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        cmd.Connection.Open()
        cmd.ExecuteNonQuery()
        cmd.Connection.Close()
    Next
</code>```

Body:
I am trying to get multiple rows into a table hence my attempt to get the row number and put it into a for loop, the countC is exactly the same number of rows as the select statement, so the issue is not there

I'm using an oledb connection as my code is in vb asp.net but my database is in ms access 2003

For c As Integer = 1 To countC
        Dim cmdstring As String
        cmdstring = " INSERT INTO [KN - ProductionMachineAllocation] (BatchNo, ComponentID)
                  SELECT POH.BatchNo, SSCDD.ComponentID
                FROM (
                    SELECT ROW_NUMBER() OVER (ORDER BY BatchNo ASC) AS rownumber
                    ([KN - ProductionOrderHeader] AS POH
                    INNER JOIN [FG - End Product Codes] AS EPC
                        ON POH.ProductID = EPC.ProductID)
                    INNER JOIN ([KN - ProductionOrderDetails] AS POD
                    INNER JOIN [FG - Style Size Comp Def Details]  AS SSCDD
                        ON POD.SizeID = SSCDD.SizeID)
                        ON (POH.BatchNo = POD.BatchNo)
                            AND (EPC.StyleID = SSCDD.StyleID)
                    WHERE POH.BatchNo = '" & BatchNo & "'
                     )  AS temptablename
                WHERE rownumber IN (" & c & ");"
        Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Shantara Production IT.mdb")
        Dim cmd As New OleDbCommand(cmdstring)
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        cmd.Connection.Open()
        cmd.ExecuteNonQuery()
        cmd.Connection.Close()
    Next

I found out that ms access doesn't support ROW_NUMBER() so I need to find another going through each row since ms access doesn't support multi row insert by insert into select statement such as mine, any suggestions around my problem?

Body:
OK SO I finally found a way around it, it's a bit of a long process but basically I loaded the SELECT statement(with multiple rows) into a gridview table and the used a for loop to insert it into my insert into statement. bellow is my code:

Displaying into a table

    Dim Adapter As New OleDbDataAdapter
    Dim Data As New DataTable
    Dim SQL As String
    Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Shantara Production IT.mdb")
    Dim cmd As New OleDbCommand()
    grdvmachincomp.Visible = false
    SQL = "SELECT DISTINCT POH.BatchNo, SSCDD.ComponentID
                    FROM ([KN - ProductionOrderHeader] AS POH
                    INNER Join [FG - End Product Codes] AS EPC
                        On POH.ProductID = EPC.ProductID)
                    INNER Join([KN - ProductionOrderDetails] AS POD
                    INNER Join [FG - Style Size Comp Def Details]  AS SSCDD
                        On POD.SizeID = SSCDD.SizeID)
                        On (POH.BatchNo = POD.BatchNo)
                            And (EPC.StyleID = SSCDD.StyleID)
                    WHERE POH.BatchNo = '" & BatchNo & "'"
    con.Open()
    cmd.Connection = con
    cmd.CommandText = SQL

    Adapter.SelectCommand = cmd
    Adapter.Fill(Data)

    grdvmachincomp.DataSource = Data
    grdvmachincomp.DataBind()
    cmd.Connection.Close()

Insert into through for loop

For c As Integer = 0 To grdvmachincomp.Rows.Count - 1
        Dim cmdstring As String
        cmdstring = " INSERT INTO [KN - ProductionMachineAllocation] (BatchNo, ComponentID) VALUES('" & grdvmachincomp.Rows(c).Cells(0).Text & "', " & grdvmachincomp.Rows(c).Cells(1).Text & ");"
        Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Shantara Production IT.mdb")
        Dim cmd As New OleDbCommand(cmdstring)
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        cmd.Connection.Open()
        cmd.ExecuteNonQuery()
        cmd.Connection.Close()
    Next


来源: stackexchange

问:
Why do you need functions such as these (*>) or (<*) if they discard the first or second argument?
The type signature of the function (*>) is such:

```<code>(*>) :: f a -> f b -> f b
</code>```

Sequence actions, discarding the value of the first argument.

Can someone please explain why this is useful?  Seems counter-intuitive if the first argument is discarded.

Please illustrate with examples.  Thanks.

答:
Let’s suppose our applicative functor here is already a monad. We might implement *> and <* like this:

```<code>x *> y = do
  x
  y

x <* y = do
  result <- x
  y
  return result
</code>```

So you can use <* and *> to write simple things like:

```<code>askForNumber :: IO Int
askForNumber = putStr "Please enter a number: " *> readLn <* putStrLn "Thank you."
</code>```

So you can see that while the “result” is discarded, the result is only one part of a monadic action or applicative functor action.

ContentLicense: CC BY-SA 3.0

Body:
The type signature of the function (*>) is such:

(*>) :: f a -> f b -> f b

Sequence actions, discarding the value of the first argument.

Can someone please explain why this is useful?  Seems counter-intuitive if the first argument is discarded.

Please illustrate with examples.  Thanks.

Body:
Let’s suppose our applicative functor here is already a monad. We might implement *> and <* like this:

x *> y = do
  x
  y

x <* y = do
  result <- x
  y
  return result

So you can use <* and *> to write simple things like:

askForNumber :: IO Int
askForNumber = putStr "Please enter a number: " *> readLn <* putStrLn "Thank you."

So you can see that while the “result” is discarded, the result is only one part of a monadic action or applicative functor action.


问:
How do I get Html created by javascript using HtmlUnit in Java and then parse it with Jsoup?
I am trying to access some content on a web page that is created by some Javascript. However, the content that I wish to access is created by the javascript after the page has loaded so this chunk of Html source is no where to be found when I try and parse it with Jsoup.

My code for getting the Html source, using HtmlUnit is as follows:

```<code>public static void main(String[] args) throws IOException {
           java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);

    WebClient webClient = new WebClient(BrowserVersion.CHROME);
    webClient.getOptions().setThrowExceptionOnScriptError(false);
    webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);

    String url = "myUrl.com";
    out.println("accessing " + url);

    HtmlPage page = webClient.getPage(url);

    out.println("waiting for js");
    webClient.waitForBackgroundJavaScriptStartingBefore(200);
    webClient.waitForBackgroundJavaScript(20000);

    out.println(page.asXml());

    webClient.close();
}
</code>```

But when I run it, the Html that is supposed to be created is not printed. I was wondering how do I get this Html source, created by the Javascript, using HtmlUnit and then getting said result and passing it to Jsoup for parsing?

答:
Jsoup is server side processing framework,

I am not sure what is your final goal, I assume you want to use it in the same page so I will go with Ajax so you can do:

On document ready, capture the document dom

Send it for processing on server side

Display the results on the same page

Something like:

.

```<code>$( document ).ready(function() {
    var allClientSideHtml = $("html").html();

var dataToSend = JSON.stringify({'htmlSendToSever':allClientSideHtml });
 $.ajax({ url: "your_Jsoup_server_url.jsp_or_php/YourJsoupParser",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: dataToSend , // pass that text to the server as a JSON String
        success: function (msg) { alert(msg.d); },
        error: function (type) { alert("ERROR!!" + type.responseText); }

    });

});
</code>```

Body:
I am trying to access some content on a web page that is created by some Javascript. However, the content that I wish to access is created by the javascript after the page has loaded so this chunk of Html source is no where to be found when I try and parse it with Jsoup.

My code for getting the Html source, using HtmlUnit is as follows:

public static void main(String[] args) throws IOException {
           java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);

    WebClient webClient = new WebClient(BrowserVersion.CHROME);
    webClient.getOptions().setThrowExceptionOnScriptError(false);
    webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);

    String url = "myUrl.com";
    out.println("accessing " + url);

    HtmlPage page = webClient.getPage(url);

    out.println("waiting for js");
    webClient.waitForBackgroundJavaScriptStartingBefore(200);
    webClient.waitForBackgroundJavaScript(20000);

    out.println(page.asXml());

    webClient.close();
}

But when I run it, the Html that is supposed to be created is not printed. I was wondering how do I get this Html source, created by the Javascript, using HtmlUnit and then getting said result and passing it to Jsoup for parsing?

Body:
Jsoup is server side processing framework,

I am not sure what is your final goal, I assume you want to use it in the same page so I will go with Ajax so you can do:

On document ready, capture the document dom

Send it for processing on server side

Display the results on the same page

Something like:

.

$( document ).ready(function() {
    var allClientSideHtml = $("html").html();

var dataToSend = JSON.stringify({'htmlSendToSever':allClientSideHtml });
 $.ajax({ url: "your_Jsoup_server_url.jsp_or_php/YourJsoupParser",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: dataToSend , // pass that text to the server as a JSON String
        success: function (msg) { alert(msg.d); },
        error: function (type) { alert("ERROR!!" + type.responseText); }

    });

});

ContentLicense: CC BY-SA 4.0


问:
SQL Restore DB frozen at 100% [SQL SERVER 2008 R2]
This is the second time I've restored my DB and it freezes at 100% not sure why.

```<code>10 percent processed.
20 percent processed.
30 percent processed.
40 percent processed.
50 percent processed.
60 percent processed.
70 percent processed.
80 percent processed.
90 percent processed.
100 percent processed.
Processed 16305440 pages for database 'db1', file 'db1' on file 1.
Processed 74479 pages for database 'db1', file 'db1_log' on file 1.
</code>```

I've tried using the console for restoring and also running the command directly into the window and it stays at 100%, it took 63m to completely restore and now is being sometime since then.

```<code>session_id  command Percent Complete    ETA Completion Time Elapsed Min ETA Min ETA Hours
61  RESTORE DATABASE    100.00  2017-11-13 16:02:54 69  0.00    0.00
</code>```

What is going on?

```<code>RESTORE DATABASE [db1] FROM  DISK = N'D:\DATA\db1.bak' WITH  FILE = 1,  MOVE N'db1' TO N'D:\DATA\db1.mdf',  MOVE N'db1_log' TO N'D:\DATA\db1_1.ldf',  NOUNLOAD,  STATS = 10
</code>```

SQL SERVER 2008 R2

答:
Normally, after restoring a database backup file without restoring the transaction log backup file, it will leave the database inaccessible, because the database is waiting for the latest transaction log backup. If you need to bring your database back to accessible and you are sure that .bak is the last one your need to restore, try RESTORE DATABASE db_name WITH RECOVERY.

So generally, the order of restoring a database:

```<code>Restore database name from ... with norecovery --'.bak'
Restore database name from ... with norecovery --'.dif'
Restore database name from ... with recovery --'.TRN'
</code>```

If you are not sure if there is any .TRN available, you could add RESTORE DATABASE name WITH RECOVERY at the very end to make sure database can be accessed after restoring jobs. It wont be hurt if the database has been restored with recovery before or not, just a 2nd defense xD

Body:
This is the second time I've restored my DB and it freezes at 100% not sure why.

10 percent processed.
20 percent processed.
30 percent processed.
40 percent processed.
50 percent processed.
60 percent processed.
70 percent processed.
80 percent processed.
90 percent processed.
100 percent processed.
Processed 16305440 pages for database 'db1', file 'db1' on file 1.
Processed 74479 pages for database 'db1', file 'db1_log' on file 1.

I've tried using the console for restoring and also running the command directly into the window and it stays at 100%, it took 63m to completely restore and now is being sometime since then.

session_id  command Percent Complete    ETA Completion Time Elapsed Min ETA Min ETA Hours
61  RESTORE DATABASE    100.00  2017-11-13 16:02:54 69  0.00    0.00

What is going on?

RESTORE DATABASE [db1] FROM  DISK = N'D:\DATA\db1.bak' WITH  FILE = 1,  MOVE N'db1' TO N'D:\DATA\db1.mdf',  MOVE N'db1_log' TO N'D:\DATA\db1_1.ldf',  NOUNLOAD,  STATS = 10

SQL SERVER 2008 R2

Body:
Normally, after restoring a database backup file without restoring the transaction log backup file, it will leave the database inaccessible, because the database is waiting for the latest transaction log backup. If you need to bring your database back to accessible and you are sure that .bak is the last one your need to restore, try RESTORE DATABASE db_name WITH RECOVERY.

So generally, the order of restoring a database:

Restore database name from ... with norecovery --'.bak'
Restore database name from ... with norecovery --'.dif'
Restore database name from ... with recovery --'.TRN'

If you are not sure if there is any .TRN available, you could add RESTORE DATABASE name WITH RECOVERY at the very end to make sure database can be accessed after restoring jobs. It wont be hurt if the database has been restored with recovery before or not, just a 2nd defense xD


问:
How to read file data from CURL param?
In my sinatra application, I am using following curl command to post a file in route /test.

```<code>curl -H "Content-Type: text/xml" -vv -X POST -d file_data=@test.xml
        http://localhost:4567/test
</code>```

At my Sinatra post method I want read file like

```<code>post '/test' do

   data = params[:file_data] #Here file_data param name of CURL command.
end
</code>```

But, here data is NULL. How should I configure my CURL command to read file from file_data param ?

答:
Quick answer: Remove -H "Content-Type: text/xml" and it should work.

The problem is that when a file is sent, the Content-Type header should be multipart/form-data, which curl sets automatically when you use -F. From curls documentation:

-F, --form
                (HTTP)  This  lets  curl emulate a filled-in form in which a user has pressed the submit
                button. This causes curl to POST data using the Content-Type multipart/form-data according to RFC 2388. This enables uploading of binary files etc.

However, you are overwriting this header with -H, so your app is expecting something that is not a file.

If, in addition to sending the file with curl, you want to include information about its type, you should instead do this:

```<code>curl -X POST -F "file_data=@test.xml;type=text/xml" http://localhost:4567/test
</code>```

(The content type comes after the file name and a semicolon.)

To see how a raw form submission request ends up looking like with multipart/form-data, check the answers to this question.

Title: How to read file data from CURL param?

Body:
In my sinatra application, I am using following curl command to post a file in route /test.

curl -H "Content-Type: text/xml" -vv -X POST -d file_data=@test.xml
        http://localhost:4567/test

At my Sinatra post method I want read file like

post '/test' do

   data = params[:file_data] #Here file_data param name of CURL command.
end

But, here data is NULL. How should I configure my CURL command to read file from file_data param ?

Body:
Quick answer: Remove -H "Content-Type: text/xml" and it should work.

The problem is that when a file is sent, the Content-Type header should be multipart/form-data, which curl sets automatically when you use -F. From curls documentation:

-F, --form
                (HTTP)  This  lets  curl emulate a filled-in form in which a user has pressed the submit
                button. This causes curl to POST data using the Content-Type multipart/form-data according to RFC 2388. This enables uploading of binary files etc.

However, you are overwriting this header with -H, so your app is expecting something that is not a file.

If, in addition to sending the file with curl, you want to include information about its type, you should instead do this:

curl -X POST -F "file_data=@test.xml;type=text/xml" http://localhost:4567/test

(The content type comes after the file name and a semicolon.)

To see how a raw form submission request ends up looking like with multipart/form-data, check the answers to this question.


问:
Between and within scatter matrix
Can someone help me to create a matlab code for these 2 matrixes?

this are the formulas

答:
```<code>w = 0;

for i = 1:k
    for j = 1:N(i)
        x_diff = x(i,j) - mean(x(i,:));
        w = w + (x_diff * x_diff^T);
    end
end

b = 0;

for i = 1:k
    x_diff = mean(x(i,:)) - mean(x);
    b = b + (N(i) * x_diff * x_diff^T);
end
</code>```

Title: Between and within scatter matrix


问:
ASP.Net: constant communication channel with Android clients
I am running an ASP.Net Web Forms application in an Azure Cloud. Now I have a special requirement that I have no idea how to solve: the server has to accept incoming connections over the internet from Android clients and then keep that connection open (or on standby) for a long period of time (days). So after hours or even days, the server has to find it's way to the Android client and send some data to it. I can use whatever technology works for both partners, but since the internet is in between, http/https is prefered as protocol (although WCF with TCP endpoints might also work when the connection is initiated by the client). The only thing I can think of is having the clients constantly poll the server if there is a command/data available, but that solution is ugly and wastes a lot of ressources. The client should react within seconds when the server has something to do for it, so I'd have to use a polling interval of ~10s. I know that http "keep alive" exists and can be utilizied in C# WebClients, but I doubt that it will work with my requirements? Is there any other possibility to achieve this?

答: Based on Niraj's response, I found Google Firebase Cloud Messaging. After that, I read up on the XMPP protocol and the SignalR technology available for .Net and finally decided to go with SignalR as it's implementation is most simple and does not require involvement of a 3rd party.</p>


问:
Uncaught SyntaxError: Unexpected token import; After updating from Angular 2 RC5 to Angular 2 Final;
I have ust updated my app from Angular 2 RC5 to Angular 2 final. After that i am getting error Uncaught SyntaxError: Unexpected token import;

I have all packages of latest version even updated the node to 6.7.0. I am using:

Visual Studio 2015 Update 3
Angular 2 Final
Angular 2 Material
WebPack

Package.json

```<code>{
  "name": "app",
  "version": "1.0.0",
  "description": "App development",
  "scripts": {
    "setup": "npm install",
    "build": "rimraf dist && webpack --config config/webpack.prod.js --progress --profile --bail",
    "postinstall": "typings install"
  },
  "dependencies": {
    "@angular/common": "^2.0.2",
    "@angular/compiler": "^2.0.2",
    "@angular/core": "^2.0.2",
    "@angular/forms": "^2.0.2",
    "@angular/http": "^2.0.2",
    "@angular/platform-browser": "^2.0.2",
    "@angular/platform-browser-dynamic": "^2.0.2",
    "@angular/router": "^3.0.2",
    "@angular2-material/button": "^2.0.0-alpha.8-2",
    "@angular2-material/card": "^2.0.0-alpha.8-2",
    "@angular2-material/core": "^2.0.0-alpha.8-2",
    "@angular2-material/icon": "^2.0.0-alpha.8-2",
    "@angular2-material/menu": "^2.0.0-alpha.8-2",
    "@angular2-material/toolbar": "^2.0.0-alpha.8-2",
    "core-js": "^2.4.1",
    "lodash": "^4.16.4",
    "reflect-metadata": "^0.1.8",
    "rxjs": "^5.0.0-beta.12",
    "zone.js": "^0.6.25"
  },
  "devDependencies": {
    "less": "^2.7.1",
    "css-loader": "^0.23.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.8.5",
    "html-loader": "^0.4.3",
    "html-webpack-plugin": "^2.20.0",
    "null-loader": "^0.1.1",
    "raw-loader": "^0.5.1",
    "rimraf": "^2.5.2",
    "style-loader": "^0.13.1",
    "ts-loader": "^0.8.2",
    "typescript": "^3.10.3",
    "typings": "^1.0.4",
    "webpack": "^1.13.1",
    "webpack-merge": "^0.14.0"
  },
  "repository": {
    "type": "git",
    "url": "https://optimint.visualstudio.com/defaultcollection/_git/HRP"
  },
  "author": "Deepak Dalal",
  "license": "ISC",
  "-vs-binding": {
    "AfterBuild": [],
    "ProjectOpened": [
      "setup"
    ]
  }
}
</code>```

tsconfig

```<code>{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}
</code>```

typings

```<code>{
  "name": "app",
  "resolution": "app/Scripts/typings",
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "hammerjs": "registry:dt/hammerjs#2.0.8+20160724063812",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160909174046"
  }
}
</code>```

Thanks in advance!!!

答:
Check your import statements.They should be like this,</p>

```<code>import { MdRippleModule } from '@angular2-material/core';
import { MdButtonModule } from '@angular2-material/button';
</code>```

Body:
I have ust updated my app from Angular 2 RC5 to Angular 2 final. After that i am getting error Uncaught SyntaxError: Unexpected token import;

I have all packages of latest version even updated the node to 6.7.0. I am using:

Visual Studio 2015 Update 3
Angular 2 Final
Angular 2 Material
WebPack

Package.json

{
  "name": "app",
  "version": "1.0.0",
  "description": "App development",
  "scripts": {
    "setup": "npm install",
    "build": "rimraf dist && webpack --config config/webpack.prod.js --progress --profile --bail",
    "postinstall": "typings install"
  },
  "dependencies": {
    "@angular/common": "^2.0.2",
    "@angular/compiler": "^2.0.2",
    "@angular/core": "^2.0.2",
    "@angular/forms": "^2.0.2",
    "@angular/http": "^2.0.2",
    "@angular/platform-browser": "^2.0.2",
    "@angular/platform-browser-dynamic": "^2.0.2",
    "@angular/router": "^3.0.2",
    "@angular2-material/button": "^2.0.0-alpha.8-2",
    "@angular2-material/card": "^2.0.0-alpha.8-2",
    "@angular2-material/core": "^2.0.0-alpha.8-2",
    "@angular2-material/icon": "^2.0.0-alpha.8-2",
    "@angular2-material/menu": "^2.0.0-alpha.8-2",
    "@angular2-material/toolbar": "^2.0.0-alpha.8-2",
    "core-js": "^2.4.1",
    "lodash": "^4.16.4",
    "reflect-metadata": "^0.1.8",
    "rxjs": "^5.0.0-beta.12",
    "zone.js": "^0.6.25"
  },
  "devDependencies": {
    "less": "^2.7.1",
    "css-loader": "^0.23.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.8.5",
    "html-loader": "^0.4.3",
    "html-webpack-plugin": "^2.20.0",
    "null-loader": "^0.1.1",
    "raw-loader": "^0.5.1",
    "rimraf": "^2.5.2",
    "style-loader": "^0.13.1",
    "ts-loader": "^0.8.2",
    "typescript": "^3.10.3",
    "typings": "^1.0.4",
    "webpack": "^1.13.1",
    "webpack-merge": "^0.14.0"
  },
  "repository": {
    "type": "git",
    "url": "https://optimint.visualstudio.com/defaultcollection/_git/HRP"
  },
  "author": "Deepak Dalal",
  "license": "ISC",
  "-vs-binding": {
    "AfterBuild": [],
    "ProjectOpened": [
      "setup"
    ]
  }
}

tsconfig

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

typings

{
  "name": "app",
  "resolution": "app/Scripts/typings",
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "hammerjs": "registry:dt/hammerjs#2.0.8+20160724063812",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160909174046"
  }
}

Thanks in advance!!!

Body:
Check your import statements.They should be like this,

import { MdRippleModule } from '@angular2-material/core';
import { MdButtonModule } from '@angular2-material/button';


问:
Internationalization of dynamic content in Angular?
Angular.io describes the i18n tag as follows:

The Angular i18n attribute marks translatable content. Place it on
  every element tag whose fixed text is to be translated.

So my question is this. What if I have an element whose content is dynamic? Take for example this below table that shows a list of assets. The column, "Description" needs to be in some cases English, and in some cases some other language.

```<code>    <table class="asset-table">
      <thead>
        <tr>
          <th i18n="@@alarm-list-timeon">Time On</th>
          <th i18n="@@alarm-list-timeoff">Time Off</th>
          <th i18n="@@alarm-list-asset">Asset</th>
          <th i18n="@@alarm-list-description">Description</th>
        </tr>
      </thead>
      <tbody *ngIf="showAssets">
        <tr *ngFor="let asset of pageItems">
          <td>{{asset.timeon}}</td>
          <td>{{asset.timeoff}}</td>
          <td>{{asset.assetlabel}}</td>
          <td i18n>{{asset.description}}</td>
        </tr>
      </tbody>
    </table>
</code>```

I was thinking something like this:

```<code>    <table class="asset-table">
      <thead>
        <tr>
          <th i18n="@@alarm-list-timeon">Time On</th>
          <th i18n="@@alarm-list-timeoff">Time Off</th>
          <th i18n="@@alarm-list-asset">Asset</th>
          <th i18n="@@alarm-list-description">Description</th>
        </tr>
      </thead>
      <tbody *ngIf="showAssets">
        <tr *ngFor="let asset of pageItems">
          <td>{{asset.timeon}}</td>
          <td>{{asset.timeoff}}</td>
          <td>{{asset.assetlabel}}</td>
          <td i18n="@@{{asset.description}}">{{asset.description}}</td>
        </tr>
      </tbody>
    </table>
</code>```

...but I was mistaken. Any suggestions?

答:
First, the i18n value is an ID, so it would always be static.

Second, as far as translating content that changes, the only success I have had is a workaround using NgSwitch in the template.

In this example, thingStatus is your variable, and its possible values are 'good', 'bad', and 'unknown'. All of these would each be a separate translation item, with its own i18n ID value.

Obviously, this would fail if thingStatus could have an unmanageable number of possibilities.

```<code>    <div [ngSwitch]="thingStatus">
        <p *ngSwitchCase="good" i18n="status_good>Good</p>
        <p *ngSwitchCase="bad" i18n="status_bad>Bad</p>
        <p *ngSwitchCase="unknown" i18n="status_unknown>Unknown</p>
    </div>
</code>```

Body:
Angular.io describes the i18n tag as follows:

The Angular i18n attribute marks translatable content. Place it on
  every element tag whose fixed text is to be translated.

So my question is this. What if I have an element whose content is dynamic? Take for example this below table that shows a list of assets. The column, "Description" needs to be in some cases English, and in some cases some other language.

          Time On
          Time Off
          Asset
          Description

          {{asset.timeon}}
          {{asset.timeoff}}
          {{asset.assetlabel}}
          {{asset.description}}

I was thinking something like this:

          Time On
          Time Off
          Asset
          Description

          {{asset.timeon}}
          {{asset.timeoff}}
          {{asset.assetlabel}}
          {{asset.description}}

...but I was mistaken. Any suggestions?

Body:
First, the i18n value is an ID, so it would always be static.

Second, as far as translating content that changes, the only success I have had is a workaround using NgSwitch in the template.

In this example, thingStatus is your variable, and its possible values are 'good', 'bad', and 'unknown'. All of these would each be a separate translation item, with its own i18n ID value.

Obviously, this would fail if thingStatus could have an unmanageable number of possibilities.

    <div [ngSwitch]="thingStatus">
        <p *ngSwitchCase="good" i18n="status_good>Good</p>
        <p *ngSwitchCase="bad" i18n="status_bad>Bad</p>
        <p *ngSwitchCase="unknown" i18n="status_unknown>Unknown</p>
    </div>


问:
How to connect observations containing NAs using ggplot for facetting?
Just aiming to use connect observations containing NAs using ggplot and the facet option

```<code>df <- data.frame(
    time = 1:5,
    y1 = c(4, 2, 3, 1, NA),
    y2 = c(4, 5, NA, 6, 10),
    y3 = c(8, 7, NA, 4, 5)
  )

  library(ggplot2)
  ggplot(df, aes(x=time, y=y2)) + geom_line() # no connection between observations

  ggplot(na.omit(df), aes(x=time, y=y2)) + geom_line() # a way to connect is to omit NAs but this works only when one variable

  library(tidyr)
  df2 <- df %>% gather(key = "var", value = "values", 2:4)  # gather values from variables

  ggplot(df2, aes(x=time, y=values, colour = var)) + geom_line()+
  facet_wrap(~ var) # no connection between observations ==> issue !
</code>```

Any ideas ?

答:
You can set na.rm = TRUE when using the gather function to remove NA values and then plot the data.

```<code>library(tidyr)
df2 <- df %>% gather(key = "var", value = "values", 2:4, na.rm = TRUE)

ggplot(df2, aes(x = time, y = values, colour = var)) +
  geom_line() +
  facet_wrap(~var)
</code>```

Body:
Just aiming to use connect observations containing NAs using ggplot and the facet option

df <- data.frame(
    time = 1:5,
    y1 = c(4, 2, 3, 1, NA),
    y2 = c(4, 5, NA, 6, 10),
    y3 = c(8, 7, NA, 4, 5)
  )

  library(ggplot2)
  ggplot(df, aes(x=time, y=y2)) + geom_line() # no connection between observations

  ggplot(na.omit(df), aes(x=time, y=y2)) + geom_line() # a way to connect is to omit NAs but this works only when one variable

  library(tidyr)
  df2 <- df %>% gather(key = "var", value = "values", 2:4)  # gather values from variables

  ggplot(df2, aes(x=time, y=values, colour = var)) + geom_line()+
  facet_wrap(~ var) # no connection between observations ==> issue !

Any ideas ?

Body:
You can set na.rm = TRUE when using the gather function to remove NA values and then plot the data.

library(tidyr)
df2 <- df %>% gather(key = "var", value = "values", 2:4, na.rm = TRUE)

ggplot(df2, aes(x = time, y = values, colour = var)) +
  geom_line() +
  facet_wrap(~var)


问:
Set aws tags and instance name with ec2 driver in test kitchen?
Is there a way to set aws tags and an instance name with ec2 driver in test kitchen?</p>

答:
Since the documentation does not make it overly clear for people new to Chef/Ruby. Here is a YAML sample from my .kitchen.yml file. </p>

```<code>driver:
  name: ec2
  instance_type: t2.medium
  region: us-east-1
  security_group_ids:
    - sg-1234567abcd
  subnet_id: subnet-12345677
  tags:
    Name: 'test-kitchen WinCustomAMI'
    Environment: 'test'
    SN Project: 'Custom AMI'
    SN Platform: 'Windows 2012R2'
    SN Owner: 'Some Team'
</code>```

Body:
Since the documentation does not make it overly clear for people new to Chef/Ruby. Here is a YAML sample from my .kitchen.yml file.

driver:
  name: ec2
  instance_type: t2.medium
  region: us-east-1
  security_group_ids:
    - sg-1234567abcd
  subnet_id: subnet-12345677
  tags:
    Name: 'test-kitchen WinCustomAMI'
    Environment: 'test'
    SN Project: 'Custom AMI'
    SN Platform: 'Windows 2012R2'
    SN Owner: 'Some Team'


问:
aws cloudformation WAF geo location condition
Trying to create a cloud formation template to configure WAF with geo location condition. Couldnt find the right template yet. Any pointers would be appreciated.

http://docs.aws.amazon.com/waf/latest/developerguide/web-acl-geo-conditions.html

答:
I'm afraid that your question is too vague to solicit a helpful response. The CloudFormation User Guide (pdf) defines many different WAF / CloudFront / R53 resources that will perform various forms of geo match / geo blocking capabilities. The link you provide seems a subset of Web Access Control Lists (Web ACL) - see AWS::WAF::WebACL on page 2540.

I suggest you have a look and if you are still stuck, actually describe what it is you are trying to achieve.

Note that the term you used: "geo location condition" doesn't directly relate to an AWS capability that I'm aware of.

Finally, if you are referring to https://aws.amazon.com/about-aws/whats-new/2017/10/aws-waf-now-supports-geographic-match/, then the latest Cloudformation User Guide doesn't seem to have been updated yet to reflect this.


问:
download a file from ftp using curl and php
I'm trying to download a file from an ftp server using curl and php but I can't find any documentation to help

```<code>$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,"ftp://$_FTP[server]");
curl_setopt($curl, CURLOPT_FTPLISTONLY, 1);
curl_setopt($curl, CURLOPT_USERPWD, "$_FTP[username]:$_FTP[password]");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec ($curl);
</code>```

i can get a list of files but thats about it

答:
```<code>$ftp_location = put your ftp adress here;
$location_login = put your login here;
$location_pwd = put your password here;
$conn_id = ftp_connect("$ftp_location");
$login_result = ftp_login($conn_id, $location_login, $location_pwd);

if ((!$conn_id) || (!$login_result)) {
    echo "FTP connection has failed!";
    exit;
} else {
    echo "Connected";
}

// get the file
// change products.csv to the file you want
$local = fopen("products.csv","w");
$result = ftp_fget($conn_id, $local,"products.csv", FTP_BINARY);
fwrite($local, $result); fclose($local);

// check upload status
if (!$result) {
    echo "FTP download has failed!";
} else {
    echo "Downloaded ";
}

// close the FTP stream
ftp_close($conn_id);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to download a file from an ftp server using curl and php but I can't find any documentation to help

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,"ftp://$_FTP[server]");
curl_setopt($curl, CURLOPT_FTPLISTONLY, 1);
curl_setopt($curl, CURLOPT_USERPWD, "$_FTP[username]:$_FTP[password]");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec ($curl);

i can get a list of files but thats about it


问:
Choose cell contents based on MAX result
Long time reader of SO but my first time posting a question. Hoping you can help with my dilemma and understand my formatting (not a coder!)

I have three rows of numbers. The first is a date, the second is a target number, the third is an

Date     01/11   02/11   03/11

Target      10      20          30

Actual      11    100        30

I have a formula to highlight the max number (we have a 'best ever' type celebration)

It's basic and pulls back the number: "=MAX(B3:CI3)". So above this would give me '100' as the result.

What I want to be able to do is have it pull back the associated date so I don't have to update it manually.

So I would end up with something like the below in the summary sheet I'm doing...

Best Date:  02/11

Best Score: 100

...where the '02/11' is automatically calculated.

Can someone help me pick the value? Struggling to do it at the moment. I have tried using R1C1 references and doing things like =RC[-2] and trying to get that in the MAX formula but just can't make it work.

Many thanks

Body:
Use:

=INDEX(1:1,MATCH(MAX(3:3),3:3,0)


问:
How to change djangos default User Creation Form
I extended the Django User Model and added a required ForeignKeyField called company. Now I also need to Change the default user creation Form. What I tried so far was:

Creating a new Form that Inherits from the default UserCreationForm form:

```<code>class MyUserCreationForm(UserCreationForm):
    company = forms.ModelChoiceField(queryset=Company.objects.all())

    class Meta:
        model = MyUser
        fields = ('username', 'company')
</code>```

Adding it to my extended Django Admin:

```<code>class ExtendedUserAdmin(UserAdmin):
    add_form = MyUserCreationForm
    ...
admin.site.register(MyUser, ExtendedUserAdmin)
</code>```

This does not work. What am I missing?

答:
Turns out you don't need to change add_form. All you need to do is add the following to ExtendedUserAdmin:

```<code>def __init__(self, model, admin_site):
    super().__init__(model, admin_site)
    self.add_fieldsets[0][1]['fields'] = ('username', 'password1', 'password2', 'company')
</code>```

Body:
I extended the Django User Model and added a required ForeignKeyField called company. Now I also need to Change the default user creation Form. What I tried so far was:

Creating a new Form that Inherits from the default UserCreationForm form:

class MyUserCreationForm(UserCreationForm):
    company = forms.ModelChoiceField(queryset=Company.objects.all())

    class Meta:
        model = MyUser
        fields = ('username', 'company')

Adding it to my extended Django Admin:

class ExtendedUserAdmin(UserAdmin):
    add_form = MyUserCreationForm
    ...
admin.site.register(MyUser, ExtendedUserAdmin)

This does not work. What am I missing?

Body:
Turns out you don't need to change add_form. All you need to do is add the following to ExtendedUserAdmin:

def __init__(self, model, admin_site):
    super().__init__(model, admin_site)
    self.add_fieldsets[0][1]['fields'] = ('username', 'password1', 'password2', 'company')


问:
"Accessed JArray values with invalid key value: "id". Int32 array index expected" crash when gathering json
I am currently gathering json from a url but i recieve an error that i have never experienced before looking like this:

Accessed JArray values with invalid key value: "id". Int32 array index expected

This is how the JSON looks (an example of 1 item, there are more of these):

```<code>[
   {
      "id":19205,
      "company_id":2658,
      "external_link":"",
      "county":{
         "id":12,
         "name":" ",
         "future":"",
         "infrastructure":""
      },
      "category":{
         "id":5,
         "name":""
      },
      "company":{
         "id":2658,
         "company_info":[

         ]
      },
      "merits":[

      ],
      "reqs":[
         {
            "id":56548,
            "ad_id":19205
         },
         {
            "id":56549,
            "ad_id":19205
         },
         {
            "id":56550,
            "ad_id":19205
         },
         {
            "id":56551,
            "ad_id":19205
         },
         {
            "id":56552,
            "ad_id":19205
         }
      ],
      "contact":null
   }
]
</code>```

How i gather the json:

```<code>static public async Task<JArray> getData()
    {
        var httpClientRequest = new HttpClient();
        try
        {
            var result = await httpClientRequest.GetAsync("https://mydata.com");
            var resultString = await result.Content.ReadAsStringAsync();
            var jsonResult = JArray.Parse(resultString);
            return jsonResult;
        }

        catch
        {
            return null;
        }
    }
</code>```

How i try to use it and where the error occurs:

```<code>var getData = await dataApi.getData();

foreach (var jobs in getData)
{
    System.Diagnostics.Debug.WriteLine(getData["id"].ToString()); //CRASH: `Accessed JArray values with invalid key value: "id". Int32 array index expected
}
</code>```

How would I need to adjust my code in order to successfully gather the JSON?

答:
You are trying to reference the array within the for loop, try:

```<code>System.Diagnostics.Debug.WriteLine(jobs["id"].ToString());
</code>```

or

```<code>System.Diagnostics.Debug.WriteLine(jobs.id.ToString());
</code>```

You might also need to parse your Json for it to be interpreted by c# code
see this post about parsing Json with c#

Body:
I am currently gathering json from a url but i recieve an error that i have never experienced before looking like this:

Accessed JArray values with invalid key value: "id". Int32 array index expected

This is how the JSON looks (an example of 1 item, there are more of these):

[
   {
      "id":19205,
      "company_id":2658,
      "external_link":"",
      "county":{
         "id":12,
         "name":" ",
         "future":"",
         "infrastructure":""
      },
      "category":{
         "id":5,
         "name":""
      },
      "company":{
         "id":2658,
         "company_info":[

         ]
      },
      "merits":[

      ],
      "reqs":[
         {
            "id":56548,
            "ad_id":19205
         },
         {
            "id":56549,
            "ad_id":19205
         },
         {
            "id":56550,
            "ad_id":19205
         },
         {
            "id":56551,
            "ad_id":19205
         },
         {
            "id":56552,
            "ad_id":19205
         }
      ],
      "contact":null
   }
]

How i gather the json:

static public async Task<JArray> getData()
    {
        var httpClientRequest = new HttpClient();
        try
        {
            var result = await httpClientRequest.GetAsync("https://mydata.com");
            var resultString = await result.Content.ReadAsStringAsync();
            var jsonResult = JArray.Parse(resultString);
            return jsonResult;
        }

        catch
        {
            return null;
        }
    }

How i try to use it and where the error occurs:

var getData = await dataApi.getData();

foreach (var jobs in getData)
{
    System.Diagnostics.Debug.WriteLine(getData["id"].ToString()); //CRASH: `Accessed JArray values with invalid key value: "id". Int32 array index expected
}

How would I need to adjust my code in order to successfully gather the JSON?

Body:
You are trying to reference the array within the for loop, try:

System.Diagnostics.Debug.WriteLine(jobs["id"].ToString());

or

System.Diagnostics.Debug.WriteLine(jobs.id.ToString());

You might also need to parse your Json for it to be interpreted by c# code
see this post about parsing Json with c#


问:
What data structure should I use if I want to search an object in different ways according to different attributes?
I'm programming in java, but that's just a detail.
I have  this object person class with attributes like: name, age, weight... And I need to have people stored in my application and being able to search them. Now, I can search them by name, age, weight... all that person's attributes. What's the best data structure/implementation that allows me to do this efficiently?</p>

答:
What's your end-goal? If you just want to see trends between different people ad-hoc, I'd recommend just using R or Python PANDAS. That way you can quickly look up, compare, and visualize groups/individuals based on different attributes.

If you want to make an application in Java with multiple searchable options, and you don't care too much about space, I'd use multiple hash tables, with each hash corresponding to a different attribute. Have the values in an array be pointers pointing to a person. https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

K is your attribute (age, sex, etc.) and V are pointers to people.


问:
Dealing with binary data and mb_function overloading?
I have a piece of code here which I need either assurance, or "no no no!" about in regards to if I'm thinking about this in the right or entirely wrong way.

This has to deal with cutting a variable of binary data at a specific spot, and also dealing with multi-byte overloaded functions. For example substr is actually mb_substr and strlen is mb_strlen etc.

Our server is set to UTF-8 internal encoding, and so theres this weird little thing I do to circumvent it for this binary data manipulation:

```<code>// $binary_data is the incoming variable with binary
// $clip_size is generally 16, 32 or 64 etc
$curenc = mb_internal_encoding();// this should be "UTF-8"
mb_internal_encoding('ISO-8859-1');// change so mb_ overloading doesnt screw this up
if (strlen($binary_data) >= $clip_size) {
    $first_hunk = substr($binary_data,0,$clip_size);
    $rest_of_it = substr($binary_data,$clip_size);
} else {
    // skip since its shorter than expected
}
mb_internal_encoding($curenc);// put this back now
</code>```

I can't really show input and output results, since its binary data. But tests using the above appear to be working just fine and nothing is breaking...

However, parts of my brain are screaming "what are you doing... this can't be the way to handle this"!

Notes:

The binary data coming in, is a concatenation of those two parts to begin with.

The first part's size is always known (but changes).

The second part's size is entirely unknown.

This is pretty darn close to encryption and stuffing the IV on front and ripping it off again (which oddly, I found some old code which does this same thing lol ugh).

So, I guess my question is:

Is this actually fine to be doing?

Or is there something super obvious I'm overlooking?

答:
MY SOLUTION TO THE WORRY

I dislike answering my own questions... but I wanted to share what I have decided on nonetheless.

Although what I had, "worked", I still wanted to change the hack-job-altering of the charset encoding. It was old code I admit, but for some reason, I never looked at hex2bin bin2hex for doing this. So I decided to change it to use those.

The resulting new code:

```<code>// $clip_size remains the same value for continuity later,
// only spot-adjusted here... which is why the *2.
   $hex_data   = bin2hex( $binary_data );
   $first_hunk = hex2bin( substr($hex_data,0,($clip_size*2)) );
   $rest_of_it = hex2bin( substr($hex_data,($clip_size*2)) );
   if ( !empty($rest_of_it) ) { /* process the result for reasons */ }
</code>```

Using the hex functions, turns the mess into something mb will not screw with either way. A 1 million bench loop, showed the process wasn't anything to be worried about (and its safer to run in parallel to itself than the mb_encoding mangle method).

So I'm going with this. It sits better in my mind, and resolves my question for now... until I revisit this old code again in a few years and go "what was I thinking ?!".

Body:
I have a piece of code here which I need either assurance, or "no no no!" about in regards to if I'm thinking about this in the right or entirely wrong way.

This has to deal with cutting a variable of binary data at a specific spot, and also dealing with multi-byte overloaded functions. For example substr is actually mb_substr and strlen is mb_strlen etc.

Our server is set to UTF-8 internal encoding, and so theres this weird little thing I do to circumvent it for this binary data manipulation:

// $binary_data is the incoming variable with binary
// $clip_size is generally 16, 32 or 64 etc
$curenc = mb_internal_encoding();// this should be "UTF-8"
mb_internal_encoding('ISO-8859-1');// change so mb_ overloading doesnt screw this up
if (strlen($binary_data) >= $clip_size) {
    $first_hunk = substr($binary_data,0,$clip_size);
    $rest_of_it = substr($binary_data,$clip_size);
} else {
    // skip since its shorter than expected
}
mb_internal_encoding($curenc);// put this back now

I can't really show input and output results, since its binary data. But tests using the above appear to be working just fine and nothing is breaking...

However, parts of my brain are screaming "what are you doing... this can't be the way to handle this"!

Notes:

The binary data coming in, is a concatenation of those two parts to begin with.

The first part's size is always known (but changes).

The second part's size is entirely unknown.

This is pretty darn close to encryption and stuffing the IV on front and ripping it off again (which oddly, I found some old code which does this same thing lol ugh).

So, I guess my question is:

Is this actually fine to be doing?

Or is there something super obvious I'm overlooking?

Body:
MY SOLUTION TO THE WORRY

I dislike answering my own questions... but I wanted to share what I have decided on nonetheless.

Although what I had, "worked", I still wanted to change the hack-job-altering of the charset encoding. It was old code I admit, but for some reason, I never looked at hex2bin bin2hex for doing this. So I decided to change it to use those.

The resulting new code:

// $clip_size remains the same value for continuity later,
// only spot-adjusted here... which is why the *2.
   $hex_data   = bin2hex( $binary_data );
   $first_hunk = hex2bin( substr($hex_data,0,($clip_size*2)) );
   $rest_of_it = hex2bin( substr($hex_data,($clip_size*2)) );
   if ( !empty($rest_of_it) ) { /* process the result for reasons */ }

Using the hex functions, turns the mess into something mb will not screw with either way. A 1 million bench loop, showed the process wasn't anything to be worried about (and its safer to run in parallel to itself than the mb_encoding mangle method).

So I'm going with this. It sits better in my mind, and resolves my question for now... until I revisit this old code again in a few years and go "what was I thinking ?!".


问:
Treating 1D array (pointer) as 3D matrix at run time in C++
I receive some image data as unsigned char *image = load_image(…);

This data is a 3D matrix: x (char),y (char) and channel (RGB) (char).

How can I access each element as image[x][y][channel] by overloading []? E.g. row 999, column 10000, green channel: image[999][10000][1]

Clarifications:

I'd like to use C multi-dimensional array syntax: array[x][y][z], not array[x * height * channels + y * channels + z]

I can access a 1D array as a 2D array:

```<code>unsigned char (*imageMatrix)[height] = (unsigned char (*)[height])image
imageMatrix[x][y] = 100
</code>```

I already asked how to do it in pure C. Here I want to know how it can be better achieved in C++.

答:
You can create Image class with a function that will get what you want

```<code>class Image {
    int imgSize;
    char * img;

public:
    Image(): imgSize(0), img(nullptr) {}
    Image(char* image, int size): imgSize(size), img(image) {}

    char getPixel(int x, int y, int z) {
        if(x < imgSize && y < imgSize && z < imgSize) {
            return img[x * imgSize * imgSize + y * imgSize + z];
        } else {
            // Error
        }
    }

    char operator(int x, int y, int z) {
        // The same as getPixel
    }
}
</code>```

getPixel is in my opinion the best approach because whenever you call it, you (and people working with your code) will exactly know what you do thanks to its name (even after 6 months you will immediately know you get a pixel). Overloading operator() is also a good approach, but I wouldn't use it were it to cause confusion or unwanted behavior. Both hide the internal structure of your class and don't require any proxy classes.

Overloading operator[] is an option, but to support chaining like [][][] you need proxy classes which will badly affect the performance of your code if not designed correctly.

You can read C++ FAQ to learn more.

Body:
I receive some image data as unsigned char *image = load_image(…);

This data is a 3D matrix: x (char),y (char) and channel (RGB) (char).

How can I access each element as image[x][y][channel] by overloading []? E.g. row 999, column 10000, green channel: image[999][10000][1]

Clarifications:

I'd like to use C multi-dimensional array syntax: array[x][y][z], not array[x * height * channels + y * channels + z]

I can access a 1D array as a 2D array:

unsigned char (*imageMatrix)[height] = (unsigned char (*)[height])image
imageMatrix[x][y] = 100

I already asked how to do it in pure C. Here I want to know how it can be better achieved in C++.

Body:
You can create Image class with a function that will get what you want

class Image {
    int imgSize;
    char * img;

public:
    Image(): imgSize(0), img(nullptr) {}
    Image(char* image, int size): imgSize(size), img(image) {}

    char getPixel(int x, int y, int z) {
        if(x < imgSize && y < imgSize && z < imgSize) {
            return img[x * imgSize * imgSize + y * imgSize + z];
        } else {
            // Error
        }
    }

    char operator(int x, int y, int z) {
        // The same as getPixel
    }
}

getPixel is in my opinion the best approach because whenever you call it, you (and people working with your code) will exactly know what you do thanks to its name (even after 6 months you will immediately know you get a pixel). Overloading operator() is also a good approach, but I wouldn't use it were it to cause confusion or unwanted behavior. Both hide the internal structure of your class and don't require any proxy classes.

Overloading operator[] is an option, but to support chaining like [][][] you need proxy classes which will badly affect the performance of your code if not designed correctly.

You can read C++ FAQ to learn more.


问:
jss how to change opacity for a color
Currently I am using the following code to add a color to an element using jss.

const styleSheet = theme => ({
  root: {
     backgroundColor: theme.colors.red,
  },
})```

I would like to know if exist a function to add opacity based on colortheme.colors.red.

example smt like:
backgroundColor: color(theme.colors.red, .05),

答:
You can use RGBA values

```<code>const styleSheet = theme => ({
  root: {
     backgroundColor: 'rgba(255, 255, 255, 0.5)',
  },
})
</code>```

https://facebook.github.io/react-native/docs/colors.html

Title: jss how to change opacity for a color

Body:
Currently I am using the following code to add a color to an element using jss.

const styleSheet = theme => ({
  root: {
     backgroundColor: theme.colors.red,
  },
})

I would like to know if exist a function to add opacity based on colortheme.colors.red.

example smt like:
backgroundColor: color(theme.colors.red, .05),

Body:
You can use RGBA values

const styleSheet = theme => ({
  root: {
     backgroundColor: 'rgba(255, 255, 255, 0.5)',
  },
})

https://facebook.github.io/react-native/docs/colors.html


问:
C++ Variadic parameters with out first one
it's any possibility to use a variadic parameters with out specification of first one?

For example:

This code is perfectly fine:

```<code>void something(const char* layoutAndButton, ...)
{
    va_list ap;
    va_start(ap, layoutAndButton);
    std::map<std::string, std::string> data;
    while (*layoutAndButton != '\0') {
        std::string layout = va_arg(ap, const char*);
        ++layoutAndButton;
        std::string button = va_arg(ap, const char*);
        ++layoutAndButton;
        data.insert(std::make_pair(layout, button));
    }
    for (auto const& x : data)
    {
        std::cout << x.first << ':' << x.second << std::endl;
    }
    va_end(ap);
}
</code>```

But I would like to have the something function in this way:

```<code>void something(const char*...)
</code>```

It's any possibility to do something like that? and after that to access the members? if yes, how?

Thanks

答:
If you can use C++14 (std::index_sequence and std::make_index_sequence) you can avoid recursion wrapping your args... in a std::tuple, generating a list of indexes and initializing the std::map with indexes and std::get().

I mean: if you write an helper function as follows

```<code>template <typename ... Args, std::size_t ... Is>
std::map<std::string, std::string> getMap
   (std::tuple<Args...> const & t, std::index_sequence<Is...> const &)
 { return { {std::get<(Is<<1)>(t), std::get<(Is<<1)+1U>(t)} ... }; }
</code>```

in something() you can initialize data as follows

```<code>auto data = getMap(std::tie(args...),
                   std::make_index_sequence<(sizeof...(Args)>>1)>{});
</code>```

but I also suggest to precede this line with a static_assert() to check that the number of args... is even; something like

```<code>static_assert( (sizeof...(Args) & 1U) == 0U, "#Args is odd!");
</code>```

The following is a full working example

```<code>#include <map>
#include <tuple>
#include <iostream>
#include <type_traits>

template <typename ... Args, std::size_t ... Is>
std::map<std::string, std::string> getMap
   (std::tuple<Args...> const & t, std::index_sequence<Is...> const &)
 { return { {std::get<(Is<<1)>(t), std::get<(Is<<1)+1U>(t)} ... }; }

template <typename... Args>
void something (Args... args)
 {
   static_assert( (sizeof...(Args) & 1U) == 0U, "#Args is odd!");

   auto data = getMap(std::tie(args...),
                      std::make_index_sequence<(sizeof...(Args)>>1)>{});

   for ( auto const & p : data )
      std::cout << '[' << p.first << ',' << p.second << ']';

   std::cout << std::endl;
 }

int main ()
 {
   something("k1", "v1", "k2", "v2", "k3", "v3"); // compile
   //something("k1", "v1", "k2", "v2", "odd!"); // static_assert() failure
 }
</code>```

Body:
it's any possibility to use a variadic parameters with out specification of first one?

For example:

This code is perfectly fine:

void something(const char* layoutAndButton, ...)
{
    va_list ap;
    va_start(ap, layoutAndButton);
    std::map<std::string, std::string> data;
    while (*layoutAndButton != '\0') {
        std::string layout = va_arg(ap, const char*);
        ++layoutAndButton;
        std::string button = va_arg(ap, const char*);
        ++layoutAndButton;
        data.insert(std::make_pair(layout, button));
    }
    for (auto const& x : data)
    {
        std::cout << x.first << ':' << x.second << std::endl;
    }
    va_end(ap);
}

But I would like to have the something function in this way:

void something(const char*...)

It's any possibility to do something like that? and after that to access the members? if yes, how?

Thanks

Body:
If you can use C++14 (std::index_sequence and std::make_index_sequence) you can avoid recursion wrapping your args... in a std::tuple, generating a list of indexes and initializing the std::map with indexes and std::get().

I mean: if you write an helper function as follows

template <typename ... Args, std::size_t ... Is>
std::map<std::string, std::string> getMap
   (std::tuple<Args...> const & t, std::index_sequence<Is...> const &)
 { return { {std::get<(Is<<1)>(t), std::get<(Is<<1)+1U>(t)} ... }; }

in something() you can initialize data as follows

auto data = getMap(std::tie(args...),
                   std::make_index_sequence<(sizeof...(Args)>>1)>{});

but I also suggest to precede this line with a static_assert() to check that the number of args... is even; something like

static_assert( (sizeof...(Args) & 1U) == 0U, "#Args is odd!");

The following is a full working example

#include <map>
#include <tuple>
#include <iostream>
#include <type_traits>

template <typename ... Args, std::size_t ... Is>
std::map<std::string, std::string> getMap
   (std::tuple<Args...> const & t, std::index_sequence<Is...> const &)
 { return { {std::get<(Is<<1)>(t), std::get<(Is<<1)+1U>(t)} ... }; }

template <typename... Args>
void something (Args... args)
 {
   static_assert( (sizeof...(Args) & 1U) == 0U, "#Args is odd!");

   auto data = getMap(std::tie(args...),
                      std::make_index_sequence<(sizeof...(Args)>>1)>{});

   for ( auto const & p : data )
      std::cout << '[' << p.first << ',' << p.second << ']';

   std::cout << std::endl;
 }

int main ()
 {
   something("k1", "v1", "k2", "v2", "k3", "v3"); // compile
   //something("k1", "v1", "k2", "v2", "odd!"); // static_assert() failure
 }


问:
Firebase Auth only for devices using my app
I have a question about Firebase Auth.
I'm working on my app and, even if I downloaded Firebase Auth Protocol using Pods, I realized that I really don't need them.

The aim of my app is to show some random quote about users but I don't need to Auth them 'cause I don't want and I don't need to implement an Auth system.

In few words: if you're using my app, you can submit a random quote anonymously.

How do I have to set the Authentication from Firebase Dashboard in order to allow ONLY the users who use my app to do that? How can I prevent people not to submit info if they're not using an iOS device?

答:
You could have the user sign in anonymously and have a rule in Firebase that you have to be signed in to post quotes. If you also have to be signed in to read the quotes the rules would look like this.</p>

```<code>{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}
</code>```

Body:
You could have the user sign in anonymously and have a rule in Firebase that you have to be signed in to post quotes. If you also have to be signed in to read the quotes the rules would look like this.

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}


问:
Marshalling an XML file as a Spring bean
Can anyone give me a hint how could I marshall a bean from a static XML file (main/resources/config.xml) in Spring? I'd like to get Spring to do all the work for me, hopefully with some magic in the spring applicationContext.xml file.

For example, I have the following:

```<code>@XmlRootElement(name="config")
public class MyConfig
{
  private List<FooBar> foobars;

  //constructor, getter + setter
}

@XmlType(name="fooBar")
public class FooBar
{
  private String name;
  private Foo foo;
  private Bar bar;

  //constructor, getters + setters
}

@XmlType(name="foo")
public class Foo
{
  private String name;

  //constructor, getters + setters
}

@XmlType(name="bar")
public class Bar
{
  private String name;

  //constructor, getters + setters
}
</code>```

And I want a bean loading with this XML;

```<code><config>
  <fooBar>
    <name>foobar1</name>
    <foo>
      <name>foo1</name>
    </foo>
    <bar>
      <name>bar1</name>
    </bar>
  </fooBar>
  <fooBar>
    <name>foobar2</name>
    <foo>
      <name>foo2</name>
    </foo>
    <bar>
      <name>bar2</name>
    </bar>
  </fooBar>
</config>
</code>```

I could just write a constructor and pass in the XML file as a resource, but I have the feeling that Spring has already solved the problem for me, I just can't find out how.

答: I believe that Spring does not include any non-spring configuration related xml processing.  This may be the solution you want though: castor.  This is not the only tool like this.  It is; however, the only one that I can think of atm.</p>

Body:
Can anyone give me a hint how could I marshall a bean from a static XML file (main/resources/config.xml) in Spring? I'd like to get Spring to do all the work for me, hopefully with some magic in the spring applicationContext.xml file.

For example, I have the following:

@XmlRootElement(name="config")
public class MyConfig
{
  private List<FooBar> foobars;

  //constructor, getter + setter
}

@XmlType(name="fooBar")
public class FooBar
{
  private String name;
  private Foo foo;
  private Bar bar;

  //constructor, getters + setters
}

@XmlType(name="foo")
public class Foo
{
  private String name;

  //constructor, getters + setters
}

@XmlType(name="bar")
public class Bar
{
  private String name;

  //constructor, getters + setters
}

And I want a bean loading with this XML;

<config>
  <fooBar>
    <name>foobar1</name>
    <foo>
      <name>foo1</name>
    </foo>
    <bar>
      <name>bar1</name>
    </bar>
  </fooBar>
  <fooBar>
    <name>foobar2</name>
    <foo>
      <name>foo2</name>
    </foo>
    <bar>
      <name>bar2</name>
    </bar>
  </fooBar>
</config>

I could just write a constructor and pass in the XML file as a resource, but I have the feeling that Spring has already solved the problem for me, I just can't find out how.


问:
UDF in Spark works very slow
I have a UDF in spark (running on EMR), written in scala that parses device from user agent using uaparser library for scala (uap-scala). When working on small sets it works fine (5000 rows) but when running on larger sets (2M) it works very slow.
I tried collecting the Dataframe to list and looping over it on the driver, and that was also very slow, what makes me believe that the UDF runs on the driver and not the workers

How can I establish this? does anyone have another theory?

if that is the case, why can this happen?

This is the udf code:

```<code>def calcDevice(userAgent: String): String = {

val userAgentVal = Option(userAgent).getOrElse("")
Parser.get.parse(userAgentVal).device.family
}

val calcDeviceValUDF: UserDefinedFunction = udf(calcDevice _)
</code>```

usage:

```<code>.withColumn("agentDevice", udfDefinitions.calcDeviceValUDF($"userAgent"))
</code>```

Thanks
Nir

答:
Given Parser.get.parse is missing from the question, it is possible to judge only udf part.

For performance you can remove Option:

```<code>def calcDevice(userAgent: String): String = {
  val userAgentVal = if(userAgent == null) "" else userAgent
  Parser.get.parse(userAgentVal).device.family
}
</code>```

Title: UDF in Spark works very slow

Body:
I have a UDF in spark (running on EMR), written in scala that parses device from user agent using uaparser library for scala (uap-scala). When working on small sets it works fine (5000 rows) but when running on larger sets (2M) it works very slow.
I tried collecting the Dataframe to list and looping over it on the driver, and that was also very slow, what makes me believe that the UDF runs on the driver and not the workers

How can I establish this? does anyone have another theory?

if that is the case, why can this happen?

This is the udf code:

def calcDevice(userAgent: String): String = {

val userAgentVal = Option(userAgent).getOrElse("")
Parser.get.parse(userAgentVal).device.family
}

val calcDeviceValUDF: UserDefinedFunction = udf(calcDevice _)

usage:

.withColumn("agentDevice", udfDefinitions.calcDeviceValUDF($"userAgent"))

Thanks
Nir

Body:
Given Parser.get.parse is missing from the question, it is possible to judge only udf part.

For performance you can remove Option:

def calcDevice(userAgent: String): String = {
  val userAgentVal = if(userAgent == null) "" else userAgent
  Parser.get.parse(userAgentVal).device.family
}


问:
Extracting text from generated PDF document with variables
I'm extracting text from a PDF document.
This PDF was generated using a WS reading Data From AS400 . So when printing text, the output is like :

```<code>orem ipsum dolor sit amet, **«VS123»**  In eros risus, «VS124» sed felis quis, commodo interdum tellus. Donec vitae massa
</code>```

And «VS123» , «VS124» are variables from AS400.The Java APi is not able to read Value from variable and its printing Variable name instead of variable values.

I'm using PDFBox https://pdfbox.apache.org/ to extract text.
The code source is like :

```<code>import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.form.PDNonTerminalField;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;

public class App
{
     public static void main( String[] args ) throws IOException
        {
        try (PDDocument document = PDDocument.load(new File("C:/my.pdf"))) {

            document.getClass();

            if (!document.isEncrypted()) {

                PDFTextStripperByArea stripper = new PDFTextStripperByArea();
                stripper.setSortByPosition(true);

                PDFTextStripper tStripper = new PDFTextStripper();

                String pdfFileInText = tStripper.getText(document);

                // split by whitespace
                String lines[] = pdfFileInText.split("\\r?\\n");
                for (String line : lines) {
                    System.out.println(line);
                }
                document.close();
            }
        }
    }
}
</code>```

The output starts with this stack of error :

AVERTISSEMENT: Invalid ToUnicode CMap in font ArialMT nov. 16, 2017
  8:08:24 PM org.apache.pdfbox.pdmodel.font.PDType0Font toUnicode
  AVERTISSEMENT: No Unicode mapping for CID+77 (77) in font ArialMT nov.
  16, 2017 8:08:24 PM org.apache.pdfbox.pdmodel.font.PDType0Font
  toUnicode AVERTISSEMENT: No Unicode mapping for CID+111 (111) in font
  ArialMT nov. 16, 2017 8:08:24 PM
  org.apache.pdfbox.pdmodel.font.PDType0Font toUnicode AVERTISSEMENT: No
  Unicode mapping for CID+110 (110) in font ArialMT nov. 16, 2017
  8:08:24 PM org.apache.pdfbox.pdmodel.font.PDType0Font toUnicode
  AVERTISSEMENT: No Unicode mapping for CID+116 (116) in font ArialMT
  nov. 16, 2017 8:08:24 PM org.apache.pdfbox.pdmodel.font.PDType0Font
  toUnicode AVERTISSEMENT: No Unicode mapping for CID+97 (97) in font
  ArialMT nov. 16, 2017 8:08:24 PM
  org.apache.pdfbox.pdmodel.font.PDType0Font toUnicode AVERTISSEMENT: No
  Unicode mapping for CID+32 (32) in font ArialMT

I'tried also to exract text using iText :

```<code>import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

import java.io.IOException;

public class App {
    private static final String FILE_NAME = "C:/my.pdf";

    public static void main(String[] args) {

        PdfReader reader;

        try {

            reader = new PdfReader(FILE_NAME);

            String textFromPage = PdfTextExtractor.getTextFromPage(reader, 1);

            System.out.println(textFromPage);

            reader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
</code>```

Here is the part of the PDF document :

When Tryin to extract text, or with Copy-paste, The output will be this :

CLIENT N° «VS35» « VS36 »
CONTRAT N° «VS28»

The link to the PDF File:
https://drive.google.com/file/d/1RNea028nCReIVS8nRWNlBwUwBsDOhDYg/view?usp=sharing

答:
The variables are rendered white in the PDF, as can be seen with PDFDebugger (excerpt from the second content stream of page 1):

```<code>BT
  /F3 9 Tf
  1 0 0 1 70.944 30.6 Tm
  1 g
  1 G
  [ (\253) ] TJ
ET
BT
  1 0 0 1 75.984 30.6 Tm
  [ (VS1) -2 (1) -3 (3) ] TJ
ET
</code>```

"1 g" is maximum from /DeviceGray so that is white. So that part puts out "«VS113".

The values come much later in the PDF... One of them appears at the end of the content stream of the XObject form (a sequence of PDF operations) "X2":

```<code>BT
  1.0 0.0 0.0 1.0 153.3 457.35144 Tm
  0.0 3.57696 Td
  0 Tr
  /DeviceRGB cs
  0.0 0.0 0.0 sc
  /TCCZPJ+ArialMT 11.04 Tf
  [ (\0003\0001\0008\000 \0009\0007\0008\000 \0000\0001\0002) ] TJ
  0.0 -3.57696 Td
ET
</code>```

"0.0 0.0 0.0 sc" means black, and the next-to-next line has 318 978 012. This can't be extracted due to an error reading the /ToUnicode stream. That stream should map each code to a unicode but that is missing. (You may think that it is visually obvious here, but things are not always so).

The only thing that is weird is that Adobe Reader gets the values.

From looking at the components of the PDF, it seems that in the first step, a PDF is generated with these "variables" printed white on white. In a second step, a second software finds these variables and prints the actual text at their place.

Body:
I'm extracting text from a PDF document.
This PDF was generated using a WS reading Data From AS400 . So when printing text, the output is like :

orem ipsum dolor sit amet, **«VS123»**  In eros risus, «VS124» sed felis quis, commodo interdum tellus. Donec vitae massa

And «VS123» , «VS124» are variables from AS400.The Java APi is not able to read Value from variable and its printing Variable name instead of variable values.

I'm using PDFBox https://pdfbox.apache.org/ to extract text.
The code source is like :

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.form.PDNonTerminalField;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;

public class App
{
     public static void main( String[] args ) throws IOException
        {
        try (PDDocument document = PDDocument.load(new File("C:/my.pdf"))) {

            document.getClass();

            if (!document.isEncrypted()) {

                PDFTextStripperByArea stripper = new PDFTextStripperByArea();
                stripper.setSortByPosition(true);

                PDFTextStripper tStripper = new PDFTextStripper();

                String pdfFileInText = tStripper.getText(document);

                // split by whitespace
                String lines[] = pdfFileInText.split("\\r?\\n");
                for (String line : lines) {
                    System.out.println(line);
                }
                document.close();
            }
        }
    }
}

The output starts with this stack of error :

AVERTISSEMENT: Invalid ToUnicode CMap in font ArialMT nov. 16, 2017
  8:08:24 PM org.apache.pdfbox.pdmodel.font.PDType0Font toUnicode
  AVERTISSEMENT: No Unicode mapping for CID+77 (77) in font ArialMT nov.
  16, 2017 8:08:24 PM org.apache.pdfbox.pdmodel.font.PDType0Font
  toUnicode AVERTISSEMENT: No Unicode mapping for CID+111 (111) in font
  ArialMT nov. 16, 2017 8:08:24 PM
  org.apache.pdfbox.pdmodel.font.PDType0Font toUnicode AVERTISSEMENT: No
  Unicode mapping for CID+110 (110) in font ArialMT nov. 16, 2017
  8:08:24 PM org.apache.pdfbox.pdmodel.font.PDType0Font toUnicode
  AVERTISSEMENT: No Unicode mapping for CID+116 (116) in font ArialMT
  nov. 16, 2017 8:08:24 PM org.apache.pdfbox.pdmodel.font.PDType0Font
  toUnicode AVERTISSEMENT: No Unicode mapping for CID+97 (97) in font
  ArialMT nov. 16, 2017 8:08:24 PM
  org.apache.pdfbox.pdmodel.font.PDType0Font toUnicode AVERTISSEMENT: No
  Unicode mapping for CID+32 (32) in font ArialMT

I'tried also to exract text using iText :

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

import java.io.IOException;

public class App {
    private static final String FILE_NAME = "C:/my.pdf";

    public static void main(String[] args) {

        PdfReader reader;

        try {

            reader = new PdfReader(FILE_NAME);

            String textFromPage = PdfTextExtractor.getTextFromPage(reader, 1);

            System.out.println(textFromPage);

            reader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Here is the part of the PDF document :

When Tryin to extract text, or with Copy-paste, The output will be this :

CLIENT N° «VS35» « VS36 »
CONTRAT N° «VS28»

The link to the PDF File:
https://drive.google.com/file/d/1RNea028nCReIVS8nRWNlBwUwBsDOhDYg/view?usp=sharing

Body:
The variables are rendered white in the PDF, as can be seen with PDFDebugger (excerpt from the second content stream of page 1):

BT
  /F3 9 Tf
  1 0 0 1 70.944 30.6 Tm
  1 g
  1 G
  [ (\253) ] TJ
ET
BT
  1 0 0 1 75.984 30.6 Tm
  [ (VS1) -2 (1) -3 (3) ] TJ
ET

"1 g" is maximum from /DeviceGray so that is white. So that part puts out "«VS113".

The values come much later in the PDF... One of them appears at the end of the content stream of the XObject form (a sequence of PDF operations) "X2":

BT
  1.0 0.0 0.0 1.0 153.3 457.35144 Tm
  0.0 3.57696 Td
  0 Tr
  /DeviceRGB cs
  0.0 0.0 0.0 sc
  /TCCZPJ+ArialMT 11.04 Tf
  [ (\0003\0001\0008\000 \0009\0007\0008\000 \0000\0001\0002) ] TJ
  0.0 -3.57696 Td
ET

"0.0 0.0 0.0 sc" means black, and the next-to-next line has 318 978 012. This can't be extracted due to an error reading the /ToUnicode stream. That stream should map each code to a unicode but that is missing. (You may think that it is visually obvious here, but things are not always so).

The only thing that is weird is that Adobe Reader gets the values.

From looking at the components of the PDF, it seems that in the first step, a PDF is generated with these "variables" printed white on white. In a second step, a second software finds these variables and prints the actual text at their place.


问:
VB.NET Filling form with graphics conundrum
Afternoon, I have a maths-formula type query in VB.NET
I have a screen, it can be resized and the only input I get from the user, is the quantity of "balls" that go inside the screen.
I know I need to square root the width and height, to get my "quantity" of balls for a best-as equal rows and columns - but Im a bit stuffed on calculating:
The size of the balls.
The distance between the balls (if need-be, the balls need to be smaller)
and as per not-my example below, I need the ball start position to be at the top left corner of the form.

So, open up a copy of VS, add a new winforms project, paste the code below into the Paint event of the form and run it.

So what I need is: A indeterminate amount of balls to generate (fed by a user) to fill up the form, as equally best on the X and Y axis to fill up the form staying the same size and if possible, a little distance between them, say, a quarter of the size of the ball itself.

Feel free to resize the screen or change the _BallsInTotal variable for it to auto-generate the amount of balls.

```<code>Dim _BallsInTotal As Integer

    _BallsInTotal = 100

    Dim TotalColumns As Integer
    Dim TotalRows As Integer

    TotalColumns = Math.Sqrt(_BallsInTotal)
    TotalRows = Math.Sqrt(_BallsInTotal)

    Dim BallWidth As Single = 20
    Dim BallHeight As Single = 20

    Dim BallPositionX As Long = BallWidth * 2
    Dim BallPositionY As Long = BallHeight * 2

    Dim solidBrush As New SolidBrush(Color.FromArgb(255, 255, 0, 0))

    Dim rows As Single
    Dim columns As Single

    For columns = 1 To TotalColumns
        For rows = 1 To TotalRows
            e.Graphics.FillEllipse(solidBrush, BallPositionX * columns, BallPositionY * rows, BallWidth , BallHeight )
        Next
    Next
</code>```

Ive been scratching my head for the last two hour where Im at the point where its going to bleed! (seriously, its doing my head in).

答:
What I've added is an InputBox that allows the user to specify the total number of balls.  I placed the code in the OnPaint event for drawing the graphics.  I've calculated the width of the columns and rows based on the form width/height.  I'm using variables for the column/row in the For loops to track which column and row I'm drawing in, then using the column/row width/height to find my x and y (plus an additional .1 of the column/row width/height for spacing).  And finally using .8 of the column/row width/height for how much space I want the ball to take up in the column/row.</p>

```<code>Public Class Form1
Dim _total As Int32 = 120

Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
    Dim columns As Int32 = Math.Ceiling(Math.Sqrt(_total))
    Dim rows As Int32 = Math.Ceiling(Math.Sqrt(_total))

    Dim width As Int32 = Me.ClientSize.Width
    Dim height As Int32 = Me.ClientSize.Height

    Dim columnWidth As Int32 = width / columns
    Dim rowHeight As Int32 = height / rows

    Dim brush As Brush = New SolidBrush(Color.FromArgb(255, 255, 0, 0))

    Me.SuspendLayout()

    Dim painted As Int32 = 0

    For r As Int32 = 0 To rows - 1
        For c As Int32 = 0 To columns - 1
            Dim x As Int32 = (c * columnWidth) + (columnWidth * 0.1)
            Dim y As Int32 = (r * rowHeight) + (rowHeight * 0.1)
            e.Graphics.FillEllipse(brush, New Rectangle(x, y, columnWidth * 0.8, rowHeight * 0.8))
            painted += 1
            If painted = _total Then
                Me.ResumeLayout()
                Exit Sub
            End If
        Next
    Next

End Sub

Private Sub Form1_SizeChanged(sender As Object, e As EventArgs) Handles Me.SizeChanged
    Me.Invalidate()
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim input As String = InputBox("Enter a total.")
    Dim number As Int32 = 0
    If Int32.TryParse(input, number) Then
        _total = number
        Me.Invalidate()
    End If
End Sub
End Class
</code>```

Body:
Afternoon, I have a maths-formula type query in VB.NET
I have a screen, it can be resized and the only input I get from the user, is the quantity of "balls" that go inside the screen.
I know I need to square root the width and height, to get my "quantity" of balls for a best-as equal rows and columns - but Im a bit stuffed on calculating:
The size of the balls.
The distance between the balls (if need-be, the balls need to be smaller)
and as per not-my example below, I need the ball start position to be at the top left corner of the form.

So, open up a copy of VS, add a new winforms project, paste the code below into the Paint event of the form and run it.

So what I need is: A indeterminate amount of balls to generate (fed by a user) to fill up the form, as equally best on the X and Y axis to fill up the form staying the same size and if possible, a little distance between them, say, a quarter of the size of the ball itself.

Feel free to resize the screen or change the _BallsInTotal variable for it to auto-generate the amount of balls.

Dim _BallsInTotal As Integer

    _BallsInTotal = 100

    Dim TotalColumns As Integer
    Dim TotalRows As Integer

    TotalColumns = Math.Sqrt(_BallsInTotal)
    TotalRows = Math.Sqrt(_BallsInTotal)

    Dim BallWidth As Single = 20
    Dim BallHeight As Single = 20

    Dim BallPositionX As Long = BallWidth * 2
    Dim BallPositionY As Long = BallHeight * 2

    Dim solidBrush As New SolidBrush(Color.FromArgb(255, 255, 0, 0))

    Dim rows As Single
    Dim columns As Single

    For columns = 1 To TotalColumns
        For rows = 1 To TotalRows
            e.Graphics.FillEllipse(solidBrush, BallPositionX * columns, BallPositionY * rows, BallWidth , BallHeight )
        Next
    Next

Ive been scratching my head for the last two hour where Im at the point where its going to bleed! (seriously, its doing my head in).

Body:
What I've added is an InputBox that allows the user to specify the total number of balls.  I placed the code in the OnPaint event for drawing the graphics.  I've calculated the width of the columns and rows based on the form width/height.  I'm using variables for the column/row in the For loops to track which column and row I'm drawing in, then using the column/row width/height to find my x and y (plus an additional .1 of the column/row width/height for spacing).  And finally using .8 of the column/row width/height for how much space I want the ball to take up in the column/row.

Public Class Form1
Dim _total As Int32 = 120

Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
    Dim columns As Int32 = Math.Ceiling(Math.Sqrt(_total))
    Dim rows As Int32 = Math.Ceiling(Math.Sqrt(_total))

    Dim width As Int32 = Me.ClientSize.Width
    Dim height As Int32 = Me.ClientSize.Height

    Dim columnWidth As Int32 = width / columns
    Dim rowHeight As Int32 = height / rows

    Dim brush As Brush = New SolidBrush(Color.FromArgb(255, 255, 0, 0))

    Me.SuspendLayout()

    Dim painted As Int32 = 0

    For r As Int32 = 0 To rows - 1
        For c As Int32 = 0 To columns - 1
            Dim x As Int32 = (c * columnWidth) + (columnWidth * 0.1)
            Dim y As Int32 = (r * rowHeight) + (rowHeight * 0.1)
            e.Graphics.FillEllipse(brush, New Rectangle(x, y, columnWidth * 0.8, rowHeight * 0.8))
            painted += 1
            If painted = _total Then
                Me.ResumeLayout()
                Exit Sub
            End If
        Next
    Next

End Sub

Private Sub Form1_SizeChanged(sender As Object, e As EventArgs) Handles Me.SizeChanged
    Me.Invalidate()
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim input As String = InputBox("Enter a total.")
    Dim number As Int32 = 0
    If Int32.TryParse(input, number) Then
        _total = number
        Me.Invalidate()
    End If
End Sub
End Class


问:
How can I check/uncheck all checkboxes that are in a user control in a dropdownlist
I created a user control to host some checkboxes that are created dynamically based on a list from a SQL table. I need to provide an option to select/unselect all checkboxes. This is easy to do when not created dynamically. The problem I find is that once I click on (ALL), yes, it will check or uncheck all checkboxes, but will not allow individual selection.

The code that generates the checkboxes is this:

```<code>public void GenerateCheckboxesOnUserControl()
{
    // Create user control.
    UserControl2 flp = new UserControl2();

    UserControl2 userControl2 = new UserControl2();
    userControl2.BorderStyle = BorderStyle.None;

    this.customComboBox4.DropDownControl = userControl2.flpanel;

    //*****************************//

    List<string> ItemList = new List<string>();

    ItemList.Add("Pending");
    ItemList.Add("New");
    ItemList.Add("Started");
    ItemList.Add("Declined");
    ItemList.Add("Completed");
    ItemList.Add("Accepted");
    ItemList.Add("Close");
    ItemList.Add("(ALL)");

    int i = ItemList.Count;

    CheckBox[] box = new CheckBox[i];
    _cbStatus = box;

    for (i = 0; i < ItemList.Count; i++)
    {

        box[i] = new CheckBox();
        box[i].Name = "cb" + ItemList[i].ToString();
        box[i].Tag = ItemList[i];
        box[i].Text = ItemList[i].ToString();
        box[i].Focus();

        box[i].BringToFront();
        box[i].CheckedChanged += new System.EventHandler(this._cbStatus_CheckedChanged);

        this.customComboBox4.DropDownControl.Controls.Add(box[i]);
        count++;

    }

    //****************************//
}
</code>```

The code that is used to check/uncheck is this:

```<code>public void _cbStatus_CheckedChanged(object sender, EventArgs e)
{
    if (sender is CheckBox == false) return;

    UserControl2 userControl2 = new UserControl2();

    string message = string.Empty;
    string m = "";
    for (int i = 0; i < count; i++)
    {
        if (_cbStatus[i].Checked)
        {
            m += _cbStatus[i].Name + ", ";
            message += string.Format("boxes[{0}] is clicked\n ", i + " " + _cbStatus[i].Name);
        }

        foreach (Control cbStatus in customComboBox4.DropDownControl.Controls)
        {
            CheckBox cb = (CheckBox)cbStatus;
            if (cb.Name == "cb(ALL)" && cb.Checked)
            {
                _cbStatus[i].Checked = true;
            }
            else
                if (cb.Name == "cb(ALL)" && !cb.Checked)
                {
                    _cbStatus[i].Checked = false;
                }
        }
    }

    customComboBox4.Text = m;
    //MessageBox.Show(message);
}
</code>```

Obviously, if I remove the foreach loop, it will allow me to do individual selections. Any suggestion to make it work properly?

This is the codebehind for my user control:

```<code>private void InitializeComponent()
{
    this.flpanel = new System.Windows.Forms.FlowLayoutPanel();
    this.SuspendLayout();
    //
    // flpanel
    //
    this.flpanel.AutoScroll = true;
    this.flpanel.Location = new System.Drawing.Point(4, 13);
    this.flpanel.Name = "flpanel";
    this.flpanel.Size = new System.Drawing.Size(215, 135);
    this.flpanel.TabIndex = 0;
    //
    // UserControl2
    //
    this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.BackColor = System.Drawing.SystemColors.ActiveCaption;
    this.Controls.Add(this.flpanel);
    this.Name = "UserControl2";
    this.Size = new System.Drawing.Size(222, 151);
    this.ResumeLayout(false);
}

public System.Windows.Forms.FlowLayoutPanel flpanel;
</code>```

答:
You must only check/uncheck all other checkboxes, if the sender of the check was "cb(All)". And you must omit the "cb(All)" itself in this loop.

So your code should look something like this:

```<code>var eventSendingCheckbox = sender as CheckBox
if( eventSendingCheckbox.Name == "cb(ALL)" )
{
    foreach( Control cbStatus in customComboBox4.DropDownControl.Controls )
    {
         if( cbStatus != eventSendingCheckbox )
         {
             cbStatus.Checked = eventSendingCheckbox.Checked;
         }
    }
}
</code>```

The real fun begins, if you have the goal to also check/uncheck "cb(ALL)" automatically, if the user manually checked/unchecked all other boxes.

Body:
I created a user control to host some checkboxes that are created dynamically based on a list from a SQL table. I need to provide an option to select/unselect all checkboxes. This is easy to do when not created dynamically. The problem I find is that once I click on (ALL), yes, it will check or uncheck all checkboxes, but will not allow individual selection.

The code that generates the checkboxes is this:

public void GenerateCheckboxesOnUserControl()
{
    // Create user control.
    UserControl2 flp = new UserControl2();

    UserControl2 userControl2 = new UserControl2();
    userControl2.BorderStyle = BorderStyle.None;

    this.customComboBox4.DropDownControl = userControl2.flpanel;

    //*****************************//

    List<string> ItemList = new List<string>();

    ItemList.Add("Pending");
    ItemList.Add("New");
    ItemList.Add("Started");
    ItemList.Add("Declined");
    ItemList.Add("Completed");
    ItemList.Add("Accepted");
    ItemList.Add("Close");
    ItemList.Add("(ALL)");

    int i = ItemList.Count;

    CheckBox[] box = new CheckBox[i];
    _cbStatus = box;

    for (i = 0; i < ItemList.Count; i++)
    {

        box[i] = new CheckBox();
        box[i].Name = "cb" + ItemList[i].ToString();
        box[i].Tag = ItemList[i];
        box[i].Text = ItemList[i].ToString();
        box[i].Focus();

        box[i].BringToFront();
        box[i].CheckedChanged += new System.EventHandler(this._cbStatus_CheckedChanged);

        this.customComboBox4.DropDownControl.Controls.Add(box[i]);
        count++;

    }

    //****************************//
}

The code that is used to check/uncheck is this:

public void _cbStatus_CheckedChanged(object sender, EventArgs e)
{
    if (sender is CheckBox == false) return;

    UserControl2 userControl2 = new UserControl2();

    string message = string.Empty;
    string m = "";
    for (int i = 0; i < count; i++)
    {
        if (_cbStatus[i].Checked)
        {
            m += _cbStatus[i].Name + ", ";
            message += string.Format("boxes[{0}] is clicked\n ", i + " " + _cbStatus[i].Name);
        }

        foreach (Control cbStatus in customComboBox4.DropDownControl.Controls)
        {
            CheckBox cb = (CheckBox)cbStatus;
            if (cb.Name == "cb(ALL)" && cb.Checked)
            {
                _cbStatus[i].Checked = true;
            }
            else
                if (cb.Name == "cb(ALL)" && !cb.Checked)
                {
                    _cbStatus[i].Checked = false;
                }
        }
    }

    customComboBox4.Text = m;
    //MessageBox.Show(message);
}

Obviously, if I remove the foreach loop, it will allow me to do individual selections. Any suggestion to make it work properly?

This is the codebehind for my user control:

private void InitializeComponent()
{
    this.flpanel = new System.Windows.Forms.FlowLayoutPanel();
    this.SuspendLayout();
    //
    // flpanel
    //
    this.flpanel.AutoScroll = true;
    this.flpanel.Location = new System.Drawing.Point(4, 13);
    this.flpanel.Name = "flpanel";
    this.flpanel.Size = new System.Drawing.Size(215, 135);
    this.flpanel.TabIndex = 0;
    //
    // UserControl2
    //
    this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.BackColor = System.Drawing.SystemColors.ActiveCaption;
    this.Controls.Add(this.flpanel);
    this.Name = "UserControl2";
    this.Size = new System.Drawing.Size(222, 151);
    this.ResumeLayout(false);
}

public System.Windows.Forms.FlowLayoutPanel flpanel;

Body:
You must only check/uncheck all other checkboxes, if the sender of the check was "cb(All)". And you must omit the "cb(All)" itself in this loop.

So your code should look something like this:

var eventSendingCheckbox = sender as CheckBox
if( eventSendingCheckbox.Name == "cb(ALL)" )
{
    foreach( Control cbStatus in customComboBox4.DropDownControl.Controls )
    {
         if( cbStatus != eventSendingCheckbox )
         {
             cbStatus.Checked = eventSendingCheckbox.Checked;
         }
    }
}

The real fun begins, if you have the goal to also check/uncheck "cb(ALL)" automatically, if the user manually checked/unchecked all other boxes.


问:
System.Reflection multiple assemblies error after update
After updating .NET Framework NuGet packages that my solution references to last prerelease version. I've got a building error:

Multiple assemblies with equivalent identity have been imported:
  'C:\Projects\RP\packages\System.Reflection.4.1.0-beta-23516\lib\net46\System.Reflection.dll'
  and 'C:\Program Files (x86)\Reference
  Assemblies\Microsoft\Framework.NETFramework\v4.6\Facades\System.Reflection.dll'.
  Remove one of the duplicate references.

I can't figure out how resolve this issue. If I remove System.Reflection using NuGet it throws reference error exception, it wants System.Reflection v.4.1.0.0.

Could not load file or assembly 'System.Reflection, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

How can I remove a duplicate?

答:
You can also just grab the system.reflection 4.1.0.0 from Nuget rather than reverting back to 4.0.0.0.

Version 4.1.0.0 is in it's own Nuget Package, which is why it tends to be confusing.

I actually prefer this way, because if you run a nuget restore, any nuget packages that depend on System.Reflection 4.1.0.0, will revert any changes you made to your app.config.

Meaning, if you change your reference to 4.0.0.0, it'll revert back to 4.1.0.0 on a nuget restore.