问:
How to migrate an anciant form saved with new version in ORBEON?
How to keep an anciant form saved with new version.
I used the CRUD API and i followed steps using two methods:

Retrieve the XML of a form by imposing the most recent version number:

Create a form with an earlier version : test with docId=fd4f49aad1ac3eb5a8ac29b0fa15a8cc1ec6ee6e and  version=1

Run this command: curl -v -k -H
"Orbeon-Form-Definition-Version: 2"  http://127.0.0.1:8080/orbeon/fr/service/persistence/crud/newProject/test/data/fd4f49aad1ac3eb5a8ac29b0fa15a8cc1ec6ee6e/data.xml

This results in a "400 bad request". If I put the old version 1 instead of 2, there is no error.

Create an empty test form with the latest version and fill it with
the form created with the old version

Run this command curl -v -k -H
"Orbeon-Form-Definition-Version: 1"
http://127.0.0.1:8080/orbeon/fr/service/persistence/crud/newProject/test/data/fd4f49aad1ac3eb5a8ac29b0fa15a8cc1ec6ee6e/data.xml >>myData. ⇒ the XML file save to a directory.

Save an empty test form with the new version (documentId =
40239f94e49538db4e94e4f60ad7b4f312c23f3e)

Run this command curl -v -k -d @mydata.xml -H
"Content-Type: application/xml" -H "Orbeon-Form-Definition-Version:
2" -X PUT  http://127.0.0.1:8080/orbeon/fr/service/persistence/crud/newProject/test/data/40239f94e49538db4e94e4f60ad7b4f312c23f3e/data.xml ⇒ results 500 Internal server error.

This is a stacktrace when the error was occured:

```<code>> |An Error has Occurred                                                                                |
|----------------------------------------------------------------------------------------------------------------------|
|Fatal error: The markup in the document following the root element must be well-formed.                               |
|----------------------------------------------------------------------------------------------------------------------|
|Application Call Stack                                                                                |
|----------------------------------------------------------------------------------------------------------------------|
|oxf:/ops/pfc/xforms-xml-submission.xpl                                            |reading processor output      | 111|
|Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·|
|element=<p:output name="data" ref="instance"/>                                                                        |
|name   =data                                                                                |
|ref    =instance                                                                                |
|----------------------------------------------------------------------------------------------------------------------|
|oxf:/ops/pfc/xforms-xml-submission.xpl                                            |reading processor output      | 102|
|Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·|
|element=<p:output name="data" id="raw-instance"/>                                                                     |
|name   =data                                                                                |
|id     =raw-instance                                                                                |
|----------------------------------------------------------------------------------------------------------------------|
|:/Users/fkammoun/AppData/Local/Temp/upload__5a2c8fe_15fbb88e967__8000_00000000.tmp|                              |   1|
|----------------------------------------------------------------------------------------------------------------------|
|Exception: org.orbeon.oxf.common.ValidationException                                                                  |
|----------------------------------------------------------------------------------------------------------------------|
|org.orbeon.oxf.xml.XMLParsing$ErrorHandler         |fatalError                    |XMLParsing.java               | 221|
|orbeon.apache.xerces.util.ErrorHandlerWrapper      |fatalError                    |                              |    |
|orbeon.apache.xerces.impl.XMLErrorReporter         |reportError                   |                              |    |
|orbeon.apache.xerces.impl.XMLErrorReporter         |reportError                   |                              |    |
|orbeon.apache.xerces.impl.XMLErrorReporter         |reportError                   |                              |    |
|orbeon.apache.xerces.impl.XMLScanner               |reportFatalError              |                              |    |
|.impl.XMLDocumentScannerImpl$TrailingMiscDispatcher|dispatch                      |                              |    |
|n.apache.xerces.impl.XMLDocumentFragmentScannerImpl|scanDocument                  |                              |    |
|orbeon.apache.xerces.parsers.XML11Configuration    |parse                         |                              |    |
|orbeon.apache.xerces.parsers.XML11Configuration    |parse                         |                              |    |
|orbeon.apache.xerces.parsers.XMLParser             |parse                         |                              |    |
|orbeon.apache.xerces.parsers.AbstractSAXParser     |parse                         |                              |    |
|processor.generator.URLGenerator$URLResourceHandler|readXML                       |URLGenerator.java             |1042|
|org.orbeon.oxf.processor.generator.URLGenerator$1  |readImpl                      |URLGenerator.java             | 545|
|essor.impl.ProcessorOutputImpl$TopLevelOutputFilter|read                          |ProcessorOutputImpl.java      | 257|
|org.orbeon.oxf.processor.impl.ProcessorOutputImpl  |read                          |ProcessorOutputImpl.java      | 394|
|org.orbeon.oxf.processor.ProcessorImpl             |readInputAsSAX                |ProcessorImpl.java            | 262|
|ssor.pipeline.PipelineProcessor$InternalTopOutput$1|run                           |PipelineProcessor.java        | 535|
|org.orbeon.oxf.processor.pipeline.PipelineProcessor|executeParents                |PipelineProcessor.java        | 696|
|org.orbeon.oxf.processor.pipeline.PipelineProcessor|access$400                    |PipelineProcessor.java        |  60|
|cessor.pipeline.PipelineProcessor$InternalTopOutput|readImpl                      |PipelineProcessor.java        | 531|
|essor.impl.ProcessorOutputImpl$TopLevelOutputFilter|read                          |ProcessorOutputImpl.java      | 257|
|org.orbeon.oxf.processor.impl.ProcessorOutputImpl  |read                          |ProcessorOutputImpl.java      | 394|
|org.orbeon.oxf.processor.ProcessorImpl             |readInputAsSAX                |ProcessorImpl.java            | 262|
|org.orbeon.oxf.processor.ProcessorImpl             |readInputAsSAX                |ProcessorImpl.java            | 266|
|org.orbeon.oxf.processor.IdentityProcessor$1       |readImpl                      |IdentityProcessor.java        |  33|
|essor.impl.ProcessorOutputImpl$TopLevelOutputFilter|read                          |ProcessorOutputImpl.java      | 257|
|org.orbeon.oxf.processor.impl.ProcessorOutputImpl  |read                          |ProcessorOutputImpl.java      | 394|
|org.orbeon.oxf.processor.ProcessorImpl             |readInputAsSAX                |ProcessorImpl.java            | 262|
|orbeon.oxf.processor.pipeline.PipelineProcessor$1$1|run                           |PipelineProcessor.java        |  93|
|org.orbeon.oxf.processor.pipeline.PipelineProcessor|executeChildren               |PipelineProcessor.java        | 679|
|org.orbeon.oxf.processor.pipeline.PipelineProcessor|access$000                    |PipelineProcessor.java        |  60|
|g.orbeon.oxf.processor.pipeline.PipelineProcessor$1|readImpl                      |PipelineProcessor.java        |  91|
|essor.impl.ProcessorOutputImpl$TopLevelOutputFilter|read                          |ProcessorOutputImpl.java      | 257|
|org.orbeon.oxf.processor.impl.ProcessorOutputImpl  |read                          |ProcessorOutputImpl.java      | 394|
|processor.pipeline.choose.ConcreteChooseProcessor$1|readImpl                      |ConcreteChooseProcessor.java  | 126|
|essor.impl.ProcessorOutputImpl$TopLevelOutputFilter|read                          |ProcessorOutputImpl.java      | 257|
|org.orbeon.oxf.processor.impl.ProcessorOutputImpl  |read                          |ProcessorOutputImpl.java      | 394|
|org.orbeon.oxf.processor.ProcessorImpl             |readInputAsSAX                |ProcessorImpl.java            | 262|
|orbeon.oxf.processor.pipeline.PipelineProcessor$1$1|run                           |PipelineProcessor.java        |  93|
</code>```

答:
The following explains the errors you got in the 2 cases you mentioned:

When retrieving a document, you can't specify a form version. That information is attached to the document, identified by document id, and that version number is returned to you by the API when you're doing a GET.

The form definition version for a given document id isn't expected to change. This explains the error you're getting the second case, as you're trying to update a document, and provide a new form definition version, which isn't allowed. In fact, when you're updating a document, you're not expected to provide any form definition version, as that information can't change and is already stored in the database.

And to answer the question in the title, if you have a document created with version 1 of the form and you want to store a version of that document after you upgrade it to correspond to version 2 of the form, then you need to store it using a different document id.

Body:
How to keep an anciant form saved with new version.
I used the CRUD API and i followed steps using two methods:

Retrieve the XML of a form by imposing the most recent version number:

Create a form with an earlier version : test with docId=fd4f49aad1ac3eb5a8ac29b0fa15a8cc1ec6ee6e and  version=1

Run this command: curl -v -k -H
"Orbeon-Form-Definition-Version: 2"  http://127.0.0.1:8080/orbeon/fr/service/persistence/crud/newProject/test/data/fd4f49aad1ac3eb5a8ac29b0fa15a8cc1ec6ee6e/data.xml

This results in a "400 bad request". If I put the old version 1 instead of 2, there is no error.

Create an empty test form with the latest version and fill it with
the form created with the old version

Run this command curl -v -k -H
"Orbeon-Form-Definition-Version: 1"
http://127.0.0.1:8080/orbeon/fr/service/persistence/crud/newProject/test/data/fd4f49aad1ac3eb5a8ac29b0fa15a8cc1ec6ee6e/data.xml >>myData. ⇒ the XML file save to a directory.

Save an empty test form with the new version (documentId =
40239f94e49538db4e94e4f60ad7b4f312c23f3e)

Run this command curl -v -k -d @mydata.xml -H
"Content-Type: application/xml" -H "Orbeon-Form-Definition-Version:
2" -X PUT  http://127.0.0.1:8080/orbeon/fr/service/persistence/crud/newProject/test/data/40239f94e49538db4e94e4f60ad7b4f312c23f3e/data.xml ⇒ results 500 Internal server error.

This is a stacktrace when the error was occured:

> |An Error has Occurred                                                                                |
|----------------------------------------------------------------------------------------------------------------------|
|Fatal error: The markup in the document following the root element must be well-formed.                               |
|----------------------------------------------------------------------------------------------------------------------|
|Application Call Stack                                                                                |
|----------------------------------------------------------------------------------------------------------------------|
|oxf:/ops/pfc/xforms-xml-submission.xpl                                            |reading processor output      | 111|
|Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·|
|element=
                                                                        |
|name   =data                                                                                |
|ref    =instance                                                                                |
|----------------------------------------------------------------------------------------------------------------------|
|oxf:/ops/pfc/xforms-xml-submission.xpl                                            |reading processor output      | 102|
|Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·Â·|
|element=
                                                                     |
|name   =data                                                                                |
|id     =raw-instance                                                                                |
|----------------------------------------------------------------------------------------------------------------------|
|:/Users/fkammoun/AppData/Local/Temp/upload__5a2c8fe_15fbb88e967__8000_00000000.tmp|                              |   1|
|----------------------------------------------------------------------------------------------------------------------|
|Exception: org.orbeon.oxf.common.ValidationException                                                                  |
|----------------------------------------------------------------------------------------------------------------------|
|org.orbeon.oxf.xml.XMLParsing$ErrorHandler         |fatalError                    |XMLParsing.java               | 221|
|orbeon.apache.xerces.util.ErrorHandlerWrapper      |fatalError                    |                              |    |
|orbeon.apache.xerces.impl.XMLErrorReporter         |reportError                   |                              |    |
|orbeon.apache.xerces.impl.XMLErrorReporter         |reportError                   |                              |    |
|orbeon.apache.xerces.impl.XMLErrorReporter         |reportError                   |                              |    |
|orbeon.apache.xerces.impl.XMLScanner               |reportFatalError              |                              |    |
|.impl.XMLDocumentScannerImpl$TrailingMiscDispatcher|dispatch                      |                              |    |
|n.apache.xerces.impl.XMLDocumentFragmentScannerImpl|scanDocument                  |                              |    |
|orbeon.apache.xerces.parsers.XML11Configuration    |parse                         |                              |    |
|orbeon.apache.xerces.parsers.XML11Configuration    |parse                         |                              |    |
|orbeon.apache.xerces.parsers.XMLParser             |parse                         |                              |    |
|orbeon.apache.xerces.parsers.AbstractSAXParser     |parse                         |                              |    |
|processor.generator.URLGenerator$URLResourceHandler|readXML                       |URLGenerator.java             |1042|
|org.orbeon.oxf.processor.generator.URLGenerator$1  |readImpl                      |URLGenerator.java             | 545|
|essor.impl.ProcessorOutputImpl$TopLevelOutputFilter|read                          |ProcessorOutputImpl.java      | 257|
|org.orbeon.oxf.processor.impl.ProcessorOutputImpl  |read                          |ProcessorOutputImpl.java      | 394|
|org.orbeon.oxf.processor.ProcessorImpl             |readInputAsSAX                |ProcessorImpl.java            | 262|
|ssor.pipeline.PipelineProcessor$InternalTopOutput$1|run                           |PipelineProcessor.java        | 535|
|org.orbeon.oxf.processor.pipeline.PipelineProcessor|executeParents                |PipelineProcessor.java        | 696|
|org.orbeon.oxf.processor.pipeline.PipelineProcessor|access$400                    |PipelineProcessor.java        |  60|
|cessor.pipeline.PipelineProcessor$InternalTopOutput|readImpl                      |PipelineProcessor.java        | 531|
|essor.impl.ProcessorOutputImpl$TopLevelOutputFilter|read                          |ProcessorOutputImpl.java      | 257|
|org.orbeon.oxf.processor.impl.ProcessorOutputImpl  |read                          |ProcessorOutputImpl.java      | 394|
|org.orbeon.oxf.processor.ProcessorImpl             |readInputAsSAX                |ProcessorImpl.java            | 262|
|org.orbeon.oxf.processor.ProcessorImpl             |readInputAsSAX                |ProcessorImpl.java            | 266|
|org.orbeon.oxf.processor.IdentityProcessor$1       |readImpl                      |IdentityProcessor.java        |  33|
|essor.impl.ProcessorOutputImpl$TopLevelOutputFilter|read                          |ProcessorOutputImpl.java      | 257|
|org.orbeon.oxf.processor.impl.ProcessorOutputImpl  |read                          |ProcessorOutputImpl.java      | 394|
|org.orbeon.oxf.processor.ProcessorImpl             |readInputAsSAX                |ProcessorImpl.java            | 262|
|orbeon.oxf.processor.pipeline.PipelineProcessor$1$1|run                           |PipelineProcessor.java        |  93|
|org.orbeon.oxf.processor.pipeline.PipelineProcessor|executeChildren               |PipelineProcessor.java        | 679|
|org.orbeon.oxf.processor.pipeline.PipelineProcessor|access$000                    |PipelineProcessor.java        |  60|
|g.orbeon.oxf.processor.pipeline.PipelineProcessor$1|readImpl                      |PipelineProcessor.java        |  91|
|essor.impl.ProcessorOutputImpl$TopLevelOutputFilter|read                          |ProcessorOutputImpl.java      | 257|
|org.orbeon.oxf.processor.impl.ProcessorOutputImpl  |read                          |ProcessorOutputImpl.java      | 394|
|processor.pipeline.choose.ConcreteChooseProcessor$1|readImpl                      |ConcreteChooseProcessor.java  | 126|
|essor.impl.ProcessorOutputImpl$TopLevelOutputFilter|read                          |ProcessorOutputImpl.java      | 257|
|org.orbeon.oxf.processor.impl.ProcessorOutputImpl  |read                          |ProcessorOutputImpl.java      | 394|
|org.orbeon.oxf.processor.ProcessorImpl             |readInputAsSAX                |ProcessorImpl.java            | 262|
|orbeon.oxf.processor.pipeline.PipelineProcessor$1$1|run                           |PipelineProcessor.java        |  93|


来源: stackexchange

问:
Does String.to_atom("some-known-string") create a new atom in the atom-table each time?
Does String.to_atom("some-known-string") create a new atom in the atom-table each time?

If NO, then what is the point of String.to_existing_atom/1?

If YES, then why? since String.to_atom("some-known-string") will always give the same result ... and the atom-table is never garbage collected

答:
Assuming you are always using the same string, it may only create a new atom the first time it is run. After that, assuming continued use of the same string, it will not create new atoms.

The reason there is also to_existing_atom is to help prevent filling the atom table with unknown information.

```<code>iex(1)> String.to_existing_atom("foo")
** (ArgumentError) argument error
    :erlang.binary_to_existing_atom("foo", :utf8)
iex(1)> String.to_atom("foo")
:foo
iex(2)> String.to_existing_atom("foo")
:foo
</code>```

As you can see, when I first try to call to_existing_atom, the process actually crashes because that atom is not in the atom table. However, if I use to_atom to ensure it exists, I can now call to_existing_atom and I do not get a crash.

ContentLicense: CC BY-SA 3.0

Body:
Assuming you are always using the same string, it may only create a new atom the first time it is run. After that, assuming continued use of the same string, it will not create new atoms.

The reason there is also to_existing_atom is to help prevent filling the atom table with unknown information.

iex(1)> String.to_existing_atom("foo")
** (ArgumentError) argument error
    :erlang.binary_to_existing_atom("foo", :utf8)
iex(1)> String.to_atom("foo")
:foo
iex(2)> String.to_existing_atom("foo")
:foo

As you can see, when I first try to call to_existing_atom, the process actually crashes because that atom is not in the atom table. However, if I use to_atom to ensure it exists, I can now call to_existing_atom and I do not get a crash.

ContentLicense: CC BY-SA 4.0


问:
Excel VBA - VLookup not copying data
I have done my best to read every thread imaginable to rewrite my overall code to get this to work.

Situation: I have data in sheet2 (Scores) and data in sheet3 (Comments).  In each sheet, column A has a ticket number.  The Scores sheet includes every possible ticket number; the Comments sheets only includes a subset of that total (approx 50%).  The Scores sheet includes 4 populated columns while the Comments sheet has 2.  I need the lookup to match the common existing rows (ticket numbers), and then take the value in Comments column B (2) and paste it in Column E (5) of sheet1, which is the CSAT Summary sheet, and has the contents of Col A-D from the Scores sheet.

Below is the current code.  If I remove the VLookup and just put a variable (such as "A"), it does paste A in the correct column, albeit on every single line...

```<code>scores.UsedRange.Columns.Copy
csatSum.Range("A1").Insert
csatSum.Activate
Set rng = csatSum.Range("A2:A" & lastRow)
rngLastRow = Comments.Range("B2:B" & lastRow)
For i = 2 To lastRow
    On Error Resume Next
    csatSum.Cells(i, 5) = WorksheetFunction.VLookup(rng, Comments.Range(rngLastRow), 2, False)
    On Error GoTo 0
Next i
</code>```

Not sure what I am missing.  Obviously it is something in the VLookup itself.  But I am at a loss.

答:
I think it should be:</p>

```<code>scores.UsedRange.Columns.Copy
csatSum.Range("A1").Insert
'csatSum.Activate
'Set rng = csatSum.Range("A2:A" & lastRow)
Set rngLastRow = Comments.Range("A2:B" & lastRow)
For i = 2 To lastRow
    On Error Resume Next
    csatSum.Cells(i, 5) = WorksheetFunction.VLookup(csatSum.Cells(i, 1), rngLastRow, 2, False)
    On Error GoTo 0
Next i
</code>```

Title: Excel VBA - VLookup not copying data

Body:
I have done my best to read every thread imaginable to rewrite my overall code to get this to work.

Situation: I have data in sheet2 (Scores) and data in sheet3 (Comments).  In each sheet, column A has a ticket number.  The Scores sheet includes every possible ticket number; the Comments sheets only includes a subset of that total (approx 50%).  The Scores sheet includes 4 populated columns while the Comments sheet has 2.  I need the lookup to match the common existing rows (ticket numbers), and then take the value in Comments column B (2) and paste it in Column E (5) of sheet1, which is the CSAT Summary sheet, and has the contents of Col A-D from the Scores sheet.

Below is the current code.  If I remove the VLookup and just put a variable (such as "A"), it does paste A in the correct column, albeit on every single line...

scores.UsedRange.Columns.Copy
csatSum.Range("A1").Insert
csatSum.Activate
Set rng = csatSum.Range("A2:A" & lastRow)
rngLastRow = Comments.Range("B2:B" & lastRow)
For i = 2 To lastRow
    On Error Resume Next
    csatSum.Cells(i, 5) = WorksheetFunction.VLookup(rng, Comments.Range(rngLastRow), 2, False)
    On Error GoTo 0
Next i

Not sure what I am missing.  Obviously it is something in the VLookup itself.  But I am at a loss.

Body:
I think it should be:

scores.UsedRange.Columns.Copy
csatSum.Range("A1").Insert
'csatSum.Activate
'Set rng = csatSum.Range("A2:A" & lastRow)
Set rngLastRow = Comments.Range("A2:B" & lastRow)
For i = 2 To lastRow
    On Error Resume Next
    csatSum.Cells(i, 5) = WorksheetFunction.VLookup(csatSum.Cells(i, 1), rngLastRow, 2, False)
    On Error GoTo 0
Next i


问:
Unity Error "Visual Studio Tools: failed to convert debug symbols, no pdb2mdb"
TL; DR

Why would Unity think there is no pdb2mdb when using Visual Studio Tools for Unity (VSTU)?

Background

I import my Unity scripts as managed plugins (DLLS) from Visual Studio.  That is, when I build my code in VS, I export the generated .dll and .pdb file to Unity, and the Visual Studio Tools for Unity (VSTU) extension handles converting the .pdb's to .mdb's so I can debug.  Recently however, when I build my DLLs in VS and export them to Unity, the Unity console displays the following error:

Visual Studio Tools: failed to convert debug symbols, no pdb2mdb

pdb2mdb is the program within VSTU that converts .pdb to .mdb, and I have no idea why its supposedly missing all of a sudden.  I've tried cleaning/rebuilding my VS solution, restarting VS and Unity, and repairing my VS installation, all without success.  Even stranger, this behavior is happening on two different computers (albeit with all the same relevant software versions), which makes me nervous that the issue is somehow specific to my project.  All the information that I've been able to find so far is several years old and has not helped.

My development environment:

Windows 10

Unity 2017.2.0f3

Visual Studio 2017 15.5.0

VSTU 3.5.0.2

答:
Same thing happened to me after upgrading to Visual Studio 2017 15.5.0.
Unfortunately there is no easy way to downgrade Visual Studio, so the best thing would be to wait for a fix.

EDIT:

Solution: Downgrade your visual studio to 15.0.

Uninstall version 15.5.0 by running visual studio installer and uninstalling any Visual Studio product.

Using you Microsoft account, login to http://my.visualstudio.com.

Download the installation of Visual Studio 15.0 and install it. Don't forget to check Visual Studio Tools for Unity.

Test and verify the issue is solved.

EDIT 2:

Sorry that it comes in phases, it's because I kept investigating it.
Once you have Visual Studio 2017 15.0 installed (instructions above), you can now upgrade to 15.2 (which is much more stable), doing the following:

Download the manifest file for 15.2 (here) and put in C:\VS2017.

Download Visual Studio Community installer (here) and put in the same directory.

Open command line window (as Administrator), change directory to C:\VS2017, and type:

vs_community.exe --installChannelUri "file:///C:/VS2017/ChannelManifest.json" --channelUri "https://aka.ms/vs/15/release/channel"

You can now upgrade to 15.2!


问:
using a generic method when using interface
Im stuck on a generics issue.
I have a method that returns DbSet from a DbContext object based on the object type.

Now I want to write I method where I pass in a object that implements a interface called IBaseData (that all entities implements). I want to use the existing method to return the correct DbSet based on the type of the IBaseData object, but I can't get it to work.

I've tried various versions of , typeof and gettype.

Existing method:

```<code>public GenericRepository<T> GetRepo<T>() where T : class
{
    return new GenericRepository<T>(_context);
}
</code>```

New method (this is just what Im trying to do):

```<code>public async Task SetDateLastInvoked<T>(IBaseData data, int id)
{
    var tmp = GetRepo<typeof(data)>().Where(obj => obj.Id.Equals(id));
    tmp.DateLastInvoked = DateTime.Now;

    await SaveChangesAsync();
}
</code>```

答:
I assume you are doing something like:

```<code>public interface IBaseData
{
  int Id { get; set; }
}
</code>```

Then a method would looe like

```<code>public GenericRepository<T> GetRepo<T>()
  where T : class
{
  return new GenericRepository<T>(_context);
}

public async Task SetDateLastInvoked<T>(int id)
  where T : class, IBaseData
{
  var tmp = GetRepo<T>().FirstOrDefault(obj => obj.Id == id));
  tmp.DateLastInvoked = DateTime.Now;

  await SaveChangesAsync();
}
</code>```

Usage:

```<code>public MyClass : IBaseData
{
  public Id { get; set }
}

SetDateLastInvoked<MyClass>(1);
</code>```

Body:
Im stuck on a generics issue.
I have a method that returns DbSet from a DbContext object based on the object type.

Now I want to write I method where I pass in a object that implements a interface called IBaseData (that all entities implements). I want to use the existing method to return the correct DbSet based on the type of the IBaseData object, but I can't get it to work.

I've tried various versions of , typeof and gettype.

Existing method:

public GenericRepository<T> GetRepo<T>() where T : class
{
    return new GenericRepository<T>(_context);
}

New method (this is just what Im trying to do):

public async Task SetDateLastInvoked<T>(IBaseData data, int id)
{
    var tmp = GetRepo<typeof(data)>().Where(obj => obj.Id.Equals(id));
    tmp.DateLastInvoked = DateTime.Now;

    await SaveChangesAsync();
}

Body:
I assume you are doing something like:

public interface IBaseData
{
  int Id { get; set; }
}

Then a method would looe like

public GenericRepository<T> GetRepo<T>()
  where T : class
{
  return new GenericRepository<T>(_context);
}

public async Task SetDateLastInvoked<T>(int id)
  where T : class, IBaseData
{
  var tmp = GetRepo<T>().FirstOrDefault(obj => obj.Id == id));
  tmp.DateLastInvoked = DateTime.Now;

  await SaveChangesAsync();
}

Usage:

public MyClass : IBaseData
{
  public Id { get; set }
}

SetDateLastInvoked<MyClass>(1);


问:
Python: how to sort a list of strings by substring relevance?
I have some list of strings, for example:

```<code>["foo bar SOME baz TEXT bob",
"SOME foo bar baz bob TEXT",
"SOME foo TEXT",
"foo bar SOME TEXT baz",
"SOME TEXT"]
</code>```

I want it to be sorted by exactness to SOME TEXT substring (upper case doesn't matter). Something like this order:

```<code>["SOME TEXT",
"foo bar SOME TEXT baz",
"SOME foo TEXT",
"foo bar SOME baz TEXT bob",
"SOME foo bar baz bob TEXT"]
</code>```

The idea is - the best score gets the string with the best match to substring words position. And for bigger amount of "sloppy" words between substring's words - the lower ordering it gets.

I have found some libraries like fuzzyset, or Levenshtein distance but I'm not sure this is what I need. I know the exact substring by what I want to sort and those libs search the similar words, as I understood.

Actually I need to do this sort after some database query (Postgresql) in my Django project. I have already tried full-text search with its ORM, but didn't get this relevant sort order (it doesn't count the distance between substring words). Next I have tried Haystack+Whoosh, but also at this moment didn't find info how to do this sort there. So idea now is to get query set and next sort it out of the database (yep, I know that might be a bad decision, but for now I want it just work). But if anybody tells me how to do this within any of technologies, I have mentioned here - that will be also super cool. Thank you!

p.s. The length of substring supposed to be 2-10 words in max 20 word string.

答:
You can use difflib.SequenceMatcher, to achieve something very similar to your desired output:

```<code>>>> import difflib
>>> l = ["foo bar SOME baz TEXT bob", "SOME foo bar baz bob TEXT", "SOME foo TEXT", "foo bar SOME TEXT baz", "SOME TEXT"]
>>> sorted(l, key=lambda z: difflib.SequenceMatcher(None, z, "SOME TEXT").ratio(), reverse=True)
['SOME TEXT', 'SOME foo TEXT', 'foo bar SOME TEXT baz', 'foo bar SOME baz TEXT bob', 'SOME foo bar baz bob TEXT']
</code>```

If you can't tell the only difference is that the position of the two elements "foo bar SOME TEXT baz" and "SOME foo TEXT" are swapped compared to your desired output.

Body:
I have some list of strings, for example:

["foo bar SOME baz TEXT bob",
"SOME foo bar baz bob TEXT",
"SOME foo TEXT",
"foo bar SOME TEXT baz",
"SOME TEXT"]

I want it to be sorted by exactness to SOME TEXT substring (upper case doesn't matter). Something like this order:

["SOME TEXT",
"foo bar SOME TEXT baz",
"SOME foo TEXT",
"foo bar SOME baz TEXT bob",
"SOME foo bar baz bob TEXT"]

The idea is - the best score gets the string with the best match to substring words position. And for bigger amount of "sloppy" words between substring's words - the lower ordering it gets.

I have found some libraries like fuzzyset, or Levenshtein distance but I'm not sure this is what I need. I know the exact substring by what I want to sort and those libs search the similar words, as I understood.

Actually I need to do this sort after some database query (Postgresql) in my Django project. I have already tried full-text search with its ORM, but didn't get this relevant sort order (it doesn't count the distance between substring words). Next I have tried Haystack+Whoosh, but also at this moment didn't find info how to do this sort there. So idea now is to get query set and next sort it out of the database (yep, I know that might be a bad decision, but for now I want it just work). But if anybody tells me how to do this within any of technologies, I have mentioned here - that will be also super cool. Thank you!

p.s. The length of substring supposed to be 2-10 words in max 20 word string.

Body:
You can use difflib.SequenceMatcher, to achieve something very similar to your desired output:

>>> import difflib
>>> l = ["foo bar SOME baz TEXT bob", "SOME foo bar baz bob TEXT", "SOME foo TEXT", "foo bar SOME TEXT baz", "SOME TEXT"]
>>> sorted(l, key=lambda z: difflib.SequenceMatcher(None, z, "SOME TEXT").ratio(), reverse=True)
['SOME TEXT', 'SOME foo TEXT', 'foo bar SOME TEXT baz', 'foo bar SOME baz TEXT bob', 'SOME foo bar baz bob TEXT']

If you can't tell the only difference is that the position of the two elements "foo bar SOME TEXT baz" and "SOME foo TEXT" are swapped compared to your desired output.


问:
PowerBi Api: how to copy cell contents to clipboard using a context menu command
I am trying to just copy the cell contents of a report into the clipboard in my Microsoft PowerBI app.

in my configurations i have this:

```<code>    settings: {
        filterPaneEnabled: true,
        navContentPaneEnabled: true,
        extensions: [
            {
                command: {
                    name: "CopyToClipBoard",
                    title: "Copy to Clipboard",
                    extend:
                    {
                        visualContextMenu: {
                            title: "Copy"
                        }
                    }
                }
            }
        ]
    }
</code>```

this brings up a right click menu where i see Copy as my new option.

So then i create the method for gathering the data:

```<code>report.on("commandTriggered", function (command) {
    console.log(command);
    var details = command.detail;
    if (details.command === "CopyToClipBoard") {
 //I thought the selection was in the first DataPoint, first Identity. It's not.
        var dpoints = details.dataPoints[0].identity[0].equals;
        CopyData(dpoints);
    }
});

function CopyData(dpoints) {
    //Get the selected text and append the extra info
    var newdiv = document.createElement('div');
    var selection = window.getSelection();

    //hide the newly created container
    newdiv.style.position = 'absolute';
    newdiv.style.left = '-99999px';

    //insert the container, fill it with the extended text, and define the new selection
    document.body.appendChild(newdiv);
    newdiv.innerHTML = dpoints;
    selection.selectAllChildren(newdiv);
    document.execCommand("copy");

    window.setTimeout(function () {
        document.body.removeChild(newdiv);
    }, 100);
}
</code>```

the problem is that the command doesn't contain any element of whats in the cell. It contains only data point/Identity which contains the location or identity of the cell.

How can i just get the cell text??

答:
Looks like as of right now gathering the values are still in progress....
https://github.com/Microsoft/PowerBI-JavaScript/wiki/Handling-Events</p>

Body:
I am trying to just copy the cell contents of a report into the clipboard in my Microsoft PowerBI app.

in my configurations i have this:

    settings: {
        filterPaneEnabled: true,
        navContentPaneEnabled: true,
        extensions: [
            {
                command: {
                    name: "CopyToClipBoard",
                    title: "Copy to Clipboard",
                    extend:
                    {
                        visualContextMenu: {
                            title: "Copy"
                        }
                    }
                }
            }
        ]
    }

this brings up a right click menu where i see Copy as my new option.

So then i create the method for gathering the data:

report.on("commandTriggered", function (command) {
    console.log(command);
    var details = command.detail;
    if (details.command === "CopyToClipBoard") {
 //I thought the selection was in the first DataPoint, first Identity. It's not.
        var dpoints = details.dataPoints[0].identity[0].equals;
        CopyData(dpoints);
    }
});

function CopyData(dpoints) {
    //Get the selected text and append the extra info
    var newdiv = document.createElement('div');
    var selection = window.getSelection();

    //hide the newly created container
    newdiv.style.position = 'absolute';
    newdiv.style.left = '-99999px';

    //insert the container, fill it with the extended text, and define the new selection
    document.body.appendChild(newdiv);
    newdiv.innerHTML = dpoints;
    selection.selectAllChildren(newdiv);
    document.execCommand("copy");

    window.setTimeout(function () {
        document.body.removeChild(newdiv);
    }, 100);
}

the problem is that the command doesn't contain any element of whats in the cell. It contains only data point/Identity which contains the location or identity of the cell.

How can i just get the cell text??


问:
How to add the values from a foreach loop php
I have and foreach loop that outputs the totals I want to add when i echo the $val_tex it outputs in one number like "4911165" but if I echo it with a break tag it gives me the right values. It looks like

49

1

1

1

65

My question is how to get the sum of all the values which should equal "117"

```<code>$val_tex = array();

foreach ( $get_seller as $keys ) {

     $val_tex = $keys['total'];

}
</code>```

答:
You have to add them together in the foreach loop - there's a simple way to do that $total += $keys['total']; It's just a simpler way of saying $total = $total + $keys['total'];

There are also other ways - $total = array_sum(array(1,2,3,4)); // == 10 for example. To get the sum from a single column, you get an array that only contains the values from the specific column first:

```<code>// an array of the values from that column
$arrayTotall = array_column($keys, 'total');
$total = array_sum($arrayTotals);
</code>```

Body:
I have and foreach loop that outputs the totals I want to add when i echo the $val_tex it outputs in one number like "4911165" but if I echo it with a break tag it gives me the right values. It looks like

49

1

1

1

65

My question is how to get the sum of all the values which should equal "117"

$val_tex = array();

foreach ( $get_seller as $keys ) {

     $val_tex = $keys['total'];

}

Body:
You have to add them together in the foreach loop - there's a simple way to do that $total += $keys['total']; It's just a simpler way of saying $total = $total + $keys['total'];

There are also other ways - $total = array_sum(array(1,2,3,4)); // == 10 for example. To get the sum from a single column, you get an array that only contains the values from the specific column first:

// an array of the values from that column
$arrayTotall = array_column($keys, 'total');
$total = array_sum($arrayTotals);


问:
Python Flask Uploading FIles
I'm trying to upload user selected image into my firebase.

When I browse for the file

```<code>file = request.files['inputFile']
</code>```

and I try this

```<code>storage.child("images/examples.jpg").put(file)
</code>```

I get an error

```<code>io.UnsupportedOperation: fileno
</code>```

How do I go about fixing this? I just want user to select the file and I be able to make use of the .jpg file and upload it

答:
The put method takes a path to a local file (and an optional user token).

request.files[key] returns a custom object that represents the uploaded file. Flask documentation links: file uploads quickstart, incoming request data api, FileStorage class.

You need to store the uploaded file data to a local file, and the pass that file name to the put method:

```<code>request.files['inputFile'].save("some_filename.ext")
storage.child("images/examples.jpg").put("some_filename.ext")
</code>```

Look into the tempfile module to generate random temporary file names (instead of using the hard coded some_filename.ext, which obviously is not a very good idea with concurrent requests).

Title: Python Flask Uploading FIles

Body:
I'm trying to upload user selected image into my firebase.

When I browse for the file

file = request.files['inputFile']

and I try this

storage.child("images/examples.jpg").put(file)

I get an error

io.UnsupportedOperation: fileno

How do I go about fixing this? I just want user to select the file and I be able to make use of the .jpg file and upload it

Body:
The put method takes a path to a local file (and an optional user token).

request.files[key] returns a custom object that represents the uploaded file. Flask documentation links: file uploads quickstart, incoming request data api, FileStorage class.

You need to store the uploaded file data to a local file, and the pass that file name to the put method:

request.files['inputFile'].save("some_filename.ext")
storage.child("images/examples.jpg").put("some_filename.ext")

Look into the tempfile module to generate random temporary file names (instead of using the hard coded some_filename.ext, which obviously is not a very good idea with concurrent requests).


问:
Jenkins scripted pipeline or declarative pipeline
I'm trying to convert my old style project base workflow to a pipeline based on Jenkins. While going through docs I found there are two different syntaxes named scripted and declarative. Such as the Jenkins web declarative syntax release recently (end of 2016). Although there is a new syntax release Jenkins still supports scripted syntax as well.

Now, I'm not sure in which situation each of these two types would be a best match. So will declarative be the future of the Jenkins pipeline?

Anyone who can share some thoughts about these two syntax types.

答: Another thing to consider is declarative pipelines have a script() step. This can run any scripted pipeline. So my recommendation would be to use declarative pipelines, and if needed use script() for scripted pipelines. Therefore you get the best of both worlds.


问:
Android 5.0+ camera2 api real fullscreen
I'm trying to make fullscreen camera preview (like full HD) but I cannot set proper resolution on this example: https://github.com/googlesamples/android-Camera2Basic

Am I missing something in styles? Acutally I'm using "theme.appcompat.light.noactionbar" and hardcoded 1920x1080 camera resolution but still there are some bars on screen and I can't achieve fullscreen.

Also can I display some overlay on texture view after camera preview will be set?

答:
I just used immersive mode from android 4.4+ for fullscreen :)
Also for overlay i used texture view + open gl es 2.0 support.</p>


问:
Hide LabVIEW icon of executable from the taskbar
I am working on a project on which I call some LabVIEW programs which are executables. I don't want to see what happens on these one, so I set the transparency of the front panel at 100%. Like this, I don't see the labVIEW program. After the execution, LabVIEW is quitting automatically.

However, when LabVIEW is running, I have the icon of labVIEW in the taskbar of windows.

Do you know how to hide it? I already tried to add HideRootWindow=True on the .ini file but it is not working.

答:
According to this solution by Alexander Sobolev:

```<code>For application.exe in file application.ini add row HideRootWindow=True
When you activate VI, set VI-> Property node Front Panel window.Minimizable = True, show window (invoke node VI.Open, window state = standard).
When hiding, you need to track that, set Minimizable = False
Taskbar icon will appear and disappear with window
</code>```

He also provides the code (which should be "draggable" to labview to run):

Body:
According to this solution by Alexander Sobolev:

For application.exe in file application.ini add row HideRootWindow=True
When you activate VI, set VI-> Property node Front Panel window.Minimizable = True, show window (invoke node VI.Open, window state = standard).
When hiding, you need to track that, set Minimizable = False
Taskbar icon will appear and disappear with window

He also provides the code (which should be "draggable" to labview to run):


问:
iPhone - how may I catch a button click in a header view into a UITableView
I'm planning to build a customized view for the header line of a table view, with a button inside it. I think there will be no problem to do that, but I guess how I'll be able later to know from wich header line the button was clicked ? I guess that didSelectRowAtIndexPath will not be usefull here, and I don't see any didSelectHeaderAtSection method...

Can you tell me a good way to do that stuff ?

Thank you

答:
I did that once and used the indexPath.row integer, passed that to the (id) sender of the button. That should work just fine.

Edit:

In:

```<code>- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
</code>```

you create a button.
Then you can do this:

```<code>button.tag = section;
</code>```

You attach a method to the buttons

```<code>- (void) myMethod:(id) sender
</code>```

and inside there should be something like this:

```<code>[(UIButton *)sender tag]
</code>```

That should do the job.

ContentLicense: CC BY-SA 2.5

Body:
I did that once and used the indexPath.row integer, passed that to the (id) sender of the button. That should work just fine.

Edit:

In:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

you create a button.
Then you can do this:

button.tag = section;

You attach a method to the buttons

- (void) myMethod:(id) sender

and inside there should be something like this:

[(UIButton *)sender tag]

That should do the job.


问:
calculate the percentage of substring occurrence in string, python
I've written a function that works for strings of length 1, but I have no idea how to make it work for longer ones.

```<code>def function(text, n):
    dict={}
    char_count=0

    for c in text:
        keys=dict.keys()
        if c.isalpha()==True:
            char_count+=1
            if c in keys:
                dict[c] +=1
            else:
                dict[c]=1
    for key in dict:
        dict[key]=dict[key]/char_count

    return dict
</code>```

The use of import is not very welcome :/

答:
You can create a generator than iterates over each substring of length n.  Then use them as keys to a dictionary that tracks the counts.

```<code>def substring_percentage(text, n):
    out = {}
    n_substrings = len(text)-n+1
    subs = (text[i:i+n] for i in range(n_substrings))
    for s in subs:
        if s in out:
            out[s] += 100 / n_substrings
        else:
            out[s] = 100 / n_substrings
    return out
</code>```

Tests:

```<code>s = 'I have an assignment to write a function that will receive a sentence and a number ' \
  +'and will return the percentage of the occurrences of strings of length of the given ' \
  +'number in the given string.'

pcts = substring_percentage(s, 4)
sorted(pcts.items(), key=lambda x: x[::-1], reverse=True)
# returns:
[('the ', 2.094240837696335),
 (' the', 2.094240837696335),
 (' of ', 2.094240837696335),
 ('n th', 1.5706806282722514),
 ...
 (' an ', 0.5235602094240838),
 (' a s', 0.5235602094240838),
 (' a n', 0.5235602094240838),
 (' a f', 0.5235602094240838)]
</code>```

Body:
I've written a function that works for strings of length 1, but I have no idea how to make it work for longer ones.

def function(text, n):
    dict={}
    char_count=0

    for c in text:
        keys=dict.keys()
        if c.isalpha()==True:
            char_count+=1
            if c in keys:
                dict[c] +=1
            else:
                dict[c]=1
    for key in dict:
        dict[key]=dict[key]/char_count

    return dict

The use of import is not very welcome :/

Body:
You can create a generator than iterates over each substring of length n.  Then use them as keys to a dictionary that tracks the counts.

def substring_percentage(text, n):
    out = {}
    n_substrings = len(text)-n+1
    subs = (text[i:i+n] for i in range(n_substrings))
    for s in subs:
        if s in out:
            out[s] += 100 / n_substrings
        else:
            out[s] = 100 / n_substrings
    return out

Tests:

s = 'I have an assignment to write a function that will receive a sentence and a number ' \
  +'and will return the percentage of the occurrences of strings of length of the given ' \
  +'number in the given string.'

pcts = substring_percentage(s, 4)
sorted(pcts.items(), key=lambda x: x[::-1], reverse=True)
# returns:
[('the ', 2.094240837696335),
 (' the', 2.094240837696335),
 (' of ', 2.094240837696335),
 ('n th', 1.5706806282722514),
 ...
 (' an ', 0.5235602094240838),
 (' a s', 0.5235602094240838),
 (' a n', 0.5235602094240838),
 (' a f', 0.5235602094240838)]


问:
D3 Sankey diagram from CSV rendering incorrectly
I am trying to make a Sankey Diagram using d3js. I am using a csv data source and using code based on this block: http://bl.ocks.org/d3noob/c9b90689c1438f57d649

My dataset is quite large, but I think I should be under the threshold where I would be breaking the SVG renderer. I am unsure though. My code is functional when running with the 1082 line "SankeyDataSampleFunctional.csv". Here is what it looks like:

I have made some slight modifications to the original codebase to allow for my diagram to have substantially larger amounts nodes at some layers while others don't. This is my attempt at accommodating it in sankey.js:

```<code> function initializeNodeDepth() {
  var ky = d3.min(nodesByBreadth, function(nodes) {
    if (nodes.length > 200){
      return (size[1] - (nodes.length - 1) * 1) / d3.sum(nodes, value);
    }
    else if (nodes.length > 1000) {
      console.log((size[1] - (nodes.length - 1) * 1) / d3.sum(nodes, value))
      return (size[1] - (nodes.length - 1) * 1) / d3.sum(nodes, value);
    }
    return (size[1] - (nodes.length - 1) * nodePadding) / d3.sum(nodes,
    value);
  });
</code>```

I'm doing this to clamp down the space between nodes on layers with large numbers.
But when I try to add the last layer with 2102 more nodes I get all sorts of problems. This is what it looks like when I plug in "SankeyDataSample1.csv" into the same code in question:

I checked the console and its saying I'm trying to draw a bunch of stuff with negative height. My first recourse was to clip 2101 of those 2102 extra nodes off, to see if i could get just one node to render correctly on the following layer. of course not:

I tried adding some additional depth to that branch and it continues to render the branch in the wrong direction:

finally, i checked this post about someone else who was using large datasets in a d3 sankey: Large data set breaks d3 sankey diagram

I attempt the 'quick fix' of forcing my height to be nonzero seen in this post:

```<code>    .attr("height", function(d) { return d.dy < 0 ? 0 : d.y; })
</code>```

However this didnt do much for me. I also tried multiplying negative values of d.dy by -1 with a hope to invert them and this is all i got:

Here is my code: http://plnkr.co/edit/g2rE0z?p=info

Am I up at the limits of SVG with that last 2k nodes? Or am I just going about this wrong? Any assistance would be appreciated.

答: Have you tried to enlarge canvas size? Usually, in my case, if there's no space left for nodes, it renders like that. </p>

Body:
I am trying to make a Sankey Diagram using d3js. I am using a csv data source and using code based on this block: http://bl.ocks.org/d3noob/c9b90689c1438f57d649

My dataset is quite large, but I think I should be under the threshold where I would be breaking the SVG renderer. I am unsure though. My code is functional when running with the 1082 line "SankeyDataSampleFunctional.csv". Here is what it looks like:

I have made some slight modifications to the original codebase to allow for my diagram to have substantially larger amounts nodes at some layers while others don't. This is my attempt at accommodating it in sankey.js:

 function initializeNodeDepth() {
  var ky = d3.min(nodesByBreadth, function(nodes) {
    if (nodes.length > 200){
      return (size[1] - (nodes.length - 1) * 1) / d3.sum(nodes, value);
    }
    else if (nodes.length > 1000) {
      console.log((size[1] - (nodes.length - 1) * 1) / d3.sum(nodes, value))
      return (size[1] - (nodes.length - 1) * 1) / d3.sum(nodes, value);
    }
    return (size[1] - (nodes.length - 1) * nodePadding) / d3.sum(nodes,
    value);
  });

I'm doing this to clamp down the space between nodes on layers with large numbers.
But when I try to add the last layer with 2102 more nodes I get all sorts of problems. This is what it looks like when I plug in "SankeyDataSample1.csv" into the same code in question:

I checked the console and its saying I'm trying to draw a bunch of stuff with negative height. My first recourse was to clip 2101 of those 2102 extra nodes off, to see if i could get just one node to render correctly on the following layer. of course not:

I tried adding some additional depth to that branch and it continues to render the branch in the wrong direction:

finally, i checked this post about someone else who was using large datasets in a d3 sankey: Large data set breaks d3 sankey diagram

I attempt the 'quick fix' of forcing my height to be nonzero seen in this post:

    .attr("height", function(d) { return d.dy < 0 ? 0 : d.y; })

However this didnt do much for me. I also tried multiplying negative values of d.dy by -1 with a hope to invert them and this is all i got:

Here is my code: http://plnkr.co/edit/g2rE0z?p=info

Am I up at the limits of SVG with that last 2k nodes? Or am I just going about this wrong? Any assistance would be appreciated.


问:
Printing Excel Workbooks on Different Computers
I have an Excel workbook shared with other Excel users. When my co-workers and I use our different computers to print the same sheets to PDF, the page breaks differently in the resulting PDF, even though it displays the same in print preview.

We both run Windows 10, Excel 2016, using the same printer driver and printing preferences. I've confirmed the regional settings in our system are the same. No special fonts are included in the workbook. No difference in the AppData/Roaming/Microsoft/Excel/XLSTART/.

How can I avoid the layout changes? Is there anything that I might have missed checking? Any help would be appreciated!

答:
If you're both printing the same version of the same document on the same printer, driver, operating system, etc, then you are missing a setting.

Some printer settings are buried pretty deep.  Also, were you using the Print Preview or Page Preview when you both viewed it?

I suspect you missed a screen of settings somewhere from the image below, likely the Options... button in the bottom right, which take you into the Manufacturer's settings dialog(s).

Another place to check for settings you may have missed is the control pael.  Hit the Windows Key and type printers and hit Enter and make sure you double check every setting in that window and all of the sub-dialogs.  Some printers can have hundreds of settings.

If you still can't find a difference, get a third person on a different computer to try printing it.  The odd man out of the three of your print jobs, is likely the one with the different setting!

If still no go, please post screen shots.


问:
TableAdapter Fill doesn't update database
I want to insert data into MS Access using a DataSet and TableAdapters, but unfortunately it doesn't update the table in MS Access when I run this code:

```<code>DataSet2TableAdapters.Tabelle1TableAdapter tabelle1TableAdapter = new DataSet2TableAdapters.Tabelle1TableAdapter();

DataSet2 dataSet2 = new DataSet2();
dataSet2.Tabelle1.Insert("hallo", 1);
tabelle1TableAdapter.Update(dataSet2.Tabelle1);
</code>```

This is just a test file in my actual MS Access file the table has a lot of columns so I really like to use the "Insert" method or something similiar because it's easy to write.

Some suggestions how I can accomplish this?

答:
Don't fill your table instead just use the insert function from adapters.

Something like.

```<code>DataSet2TableAdapters.Tabelle1TableAdapter tabelle1TableAdapter = new DataSet2TableAdapters.Tabelle1TableAdapter();

Tabelle1TableAdapter.Insert(valueForID,ValueForWert,ValueForNummer);
Tabelle1TableAdapter.Update(dataSet2.mytable);
</code>```

You only use fill to read the data from the database

```<code>myadapter.fill(mydataset.mytable); // will read the data
</code>```

Read More

Body:
I want to insert data into MS Access using a DataSet and TableAdapters, but unfortunately it doesn't update the table in MS Access when I run this code:

DataSet2TableAdapters.Tabelle1TableAdapter tabelle1TableAdapter = new DataSet2TableAdapters.Tabelle1TableAdapter();

DataSet2 dataSet2 = new DataSet2();
dataSet2.Tabelle1.Insert("hallo", 1);
tabelle1TableAdapter.Update(dataSet2.Tabelle1);

This is just a test file in my actual MS Access file the table has a lot of columns so I really like to use the "Insert" method or something similiar because it's easy to write.

Some suggestions how I can accomplish this?

Body:
Don't fill your table instead just use the insert function from adapters.

Something like.

DataSet2TableAdapters.Tabelle1TableAdapter tabelle1TableAdapter = new DataSet2TableAdapters.Tabelle1TableAdapter();

Tabelle1TableAdapter.Insert(valueForID,ValueForWert,ValueForNummer);
Tabelle1TableAdapter.Update(dataSet2.mytable);

You only use fill to read the data from the database

myadapter.fill(mydataset.mytable); // will read the data

Read More


问:
GridView Scroll By one row
Hi i am implementing a gridView and i have trouble making it scroll down 1 row at a time with every scroll event.

my grid has a height of 1 row item (items height is 75dp). i don't want scrolling to be left in a middle of a row.

is there a way i can intercept and modify the scroll distance so that it only returns fixed value ex: +-75dp.

i would appreciate any help or suggestions you can give me. tnx

答:
APIv8 has new function, called smoothScrollBy(int distance, int duration)[1]

i think you should catch all scroll events & implement own method to scroll view.
if you want to scroll by 75dp, just convert it to pixels & use function above.

```<code>float density = getContext().getResources().getDisplayMetrics().density;
int scrollBy = (int)(density * 75);
smoothScrollBy(scrollBy, 0);
</code>```

But would be nice to calculate scrollBy from your GridView, instead of using some constant value (like 75dp)

[1]: http://developer.android.com/reference/android/widget/AbsListView.html#smoothScrollBy(int, int)

Title: GridView Scroll By one row

Body:
APIv8 has new function, called smoothScrollBy(int distance, int duration)[1]

i think you should catch all scroll events & implement own method to scroll view.
if you want to scroll by 75dp, just convert it to pixels & use function above.

float density = getContext().getResources().getDisplayMetrics().density;
int scrollBy = (int)(density * 75);
smoothScrollBy(scrollBy, 0);

But would be nice to calculate scrollBy from your GridView, instead of using some constant value (like 75dp)

[1]: http://developer.android.com/reference/android/widget/AbsListView.html#smoothScrollBy(int, int)


问:
Change email associated with past commits in git
So, our team has been working for several months on a project on Github. It turns out that one of our team members misconfigured his local git bash shell, and was commiting with an email address that had a typo in it.

The commits have already been pushed to the remote, and are fully ingrained into the history of the repository.

We tried the option of registering the misspelled email address and then associating it with his current GitHub account, but the email is part of a domain that no longer can be registered (an old Windows@live.com address), so this can't be done.

It's fairly important that we have access to the contribution stats of this team member, and we would also like to have the work publicly associated with his account for the purposes of building a portfolio.

Are there any options?

EDIT:

I ran the script mentioned at for this purpose in the questions linked in the comments of this post, but the author in questions commits have been replaced with soandsoemailname@10.100.220.47 rather than soandsoemailname@live.com. What gives? I want to know that this is correct before I force push and mess up everything.

答:
This should have a similar effect to the script mentioned in Yu-Lin Chen's comment but makes it explicit on the command line. You might find it easier to avoid escaping/resolution problems with it:

```<code>git filter-branch -f --env-filter "if [[ \$GIT_AUTHOR_EMAIL = 'bademail@live.com' ]]; then GIT_AUTHOR_EMAIL=goodemail@live.com; fi" HEAD
</code>```

You'll probably also want to rewrite the committer:

```<code>git filter-branch -f --env-filter "if [[ \$GIT_COMMITTER_EMAIL = 'bademail@live.com' ]]; then GIT_COMMITTER_EMAIL=goodemail@live.com; fi" HEAD
</code>```

Body:
This should have a similar effect to the script mentioned in Yu-Lin Chen's comment but makes it explicit on the command line. You might find it easier to avoid escaping/resolution problems with it:

git filter-branch -f --env-filter "if [[ \$GIT_AUTHOR_EMAIL = 'bademail@live.com' ]]; then GIT_AUTHOR_EMAIL=goodemail@live.com; fi" HEAD

You'll probably also want to rewrite the committer:

git filter-branch -f --env-filter "if [[ \$GIT_COMMITTER_EMAIL = 'bademail@live.com' ]]; then GIT_COMMITTER_EMAIL=goodemail@live.com; fi" HEAD


问:
Java netty client cannot send message to server, but telnet to sever ok
I'm just learning Java Netty to make very simple client-server via socket 7000. Server is running and it will echo the message received from client. It works if I use telnet localhost 7000 and send message to server and receive the echo message.

However, with a Java Netty client, it doesn't work. Server receives nothing, client sends nothing? as I tried to add some writing to console.

Here is the classes of this example:

Client

```<code>public final class EchoClient {

    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    new LoggingHandler(LogLevel.TRACE),
                                    new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()),
                                    new StringEncoder(),
                                    new StringDecoder(),
                                    new EchoClientHandler());
                        }
                    });

            // Start the connection attempt.
            bootstrap.connect("localhost", 7000).sync().channel().closeFuture().sync();
            System.out.println("Message sent successfully.");
        } finally {
            group.shutdownGracefully();
        }
    }
}

public class EchoClientHandler extends SimpleChannelInboundHandler<String> {

    /**
     * Constructor for the class
     *
     * @param message the message you want to transmit
     */
    public EchoClientHandler() {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String message = "message from client.";
        System.out.println("Sending message: " + message);
        ctx.write(message);
        ctx.flush();
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("Error caught in the communication service: " + cause);
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("Received message: " + msg);
    }
}
</code>```

Server

```<code>    public final class EchoServer {

    static final boolean SSL = System.getProperty("ssl") != null;
    static final int PORT = Integer.parseInt(System.getProperty("port", "7000"));

    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.TRACE))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    new LoggingHandler(LogLevel.TRACE),
                                    new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()),
                                    new StringEncoder(),
                                    new StringDecoder(),
                                    new EchoServerHandler());
                        }
                    });

            System.out.println("Server is listening on port 7000.");

            // Start the server.
            ChannelFuture channelFuture = serverBootstrap.bind("localhost", 7000).sync();

            // Wait until the server socket is closed.
            channelFuture.channel().closeFuture().sync();

        } finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

public class EchoServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String message = "message from server.";
        System.out.println("Sending message: " + message);
        ctx.write(message);
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        System.out.println("Error in receiving message.");
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
        System.out.println("Received message: " + message);
        ctx.write(message);
        ctx.flush();
        //ctx.close();
    }
}
</code>```

So when I run EchoServer, then I run EchoClient, the output from EchoClient is

```<code>Sending message: message from client.
Message sent successfully.
Then application stopped.
</code>```

And the output from EchoServer is

```<code>Sending message: message from server.
</code>```

答:
Compare your protocol between your client and telnet (using LoggingHandler or Wireshark), if you do this, you will notice that there is 1 major difference between those 2 protocols.

The difference is the fact that you send your messages without a new newline at the end, while telnet does.

Solving this is really easy by appending a new newline at the end of your message, or writing a new handler that does this automatically for you.

```<code>ctx.write(message + "\n");
</code>```

One other improvement you could make is calling writeAndFlush instead of first write, and then flush, this also prevents you from missing the call to the other method when you get interrupted while coding.

Body:
I'm just learning Java Netty to make very simple client-server via socket 7000. Server is running and it will echo the message received from client. It works if I use telnet localhost 7000 and send message to server and receive the echo message.

However, with a Java Netty client, it doesn't work. Server receives nothing, client sends nothing? as I tried to add some writing to console.

Here is the classes of this example:

Client

public final class EchoClient {

    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    new LoggingHandler(LogLevel.TRACE),
                                    new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()),
                                    new StringEncoder(),
                                    new StringDecoder(),
                                    new EchoClientHandler());
                        }
                    });

            // Start the connection attempt.
            bootstrap.connect("localhost", 7000).sync().channel().closeFuture().sync();
            System.out.println("Message sent successfully.");
        } finally {
            group.shutdownGracefully();
        }
    }
}

public class EchoClientHandler extends SimpleChannelInboundHandler<String> {

    /**
     * Constructor for the class
     *
     * @param message the message you want to transmit
     */
    public EchoClientHandler() {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String message = "message from client.";
        System.out.println("Sending message: " + message);
        ctx.write(message);
        ctx.flush();
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("Error caught in the communication service: " + cause);
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("Received message: " + msg);
    }
}

Server

    public final class EchoServer {

    static final boolean SSL = System.getProperty("ssl") != null;
    static final int PORT = Integer.parseInt(System.getProperty("port", "7000"));

    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.TRACE))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    new LoggingHandler(LogLevel.TRACE),
                                    new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()),
                                    new StringEncoder(),
                                    new StringDecoder(),
                                    new EchoServerHandler());
                        }
                    });

            System.out.println("Server is listening on port 7000.");

            // Start the server.
            ChannelFuture channelFuture = serverBootstrap.bind("localhost", 7000).sync();

            // Wait until the server socket is closed.
            channelFuture.channel().closeFuture().sync();

        } finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

public class EchoServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String message = "message from server.";
        System.out.println("Sending message: " + message);
        ctx.write(message);
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        System.out.println("Error in receiving message.");
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
        System.out.println("Received message: " + message);
        ctx.write(message);
        ctx.flush();
        //ctx.close();
    }
}

So when I run EchoServer, then I run EchoClient, the output from EchoClient is

Sending message: message from client.
Message sent successfully.
Then application stopped.

And the output from EchoServer is

Sending message: message from server.

Body:
Compare your protocol between your client and telnet (using LoggingHandler or Wireshark), if you do this, you will notice that there is 1 major difference between those 2 protocols.

The difference is the fact that you send your messages without a new newline at the end, while telnet does.

Solving this is really easy by appending a new newline at the end of your message, or writing a new handler that does this automatically for you.

ctx.write(message + "\n");

One other improvement you could make is calling writeAndFlush instead of first write, and then flush, this also prevents you from missing the call to the other method when you get interrupted while coding.


问:
What does yarn --prefer-offline do?
I assume when I install npm package say react for the first time with

```<code>yarn add react
</code>```

this will save react file in local cache. I found .yarn-cache to contain many files. I assume it is yarn local cache folder so that when I install react again in the future, it will be installed from local cache, no??

If I need to install react again in the future, should I simply write this:

```<code>yarn add react
</code>```

or this:

```<code>yarn add react --prefer-offline
</code>```

答:
In order to use --prefer-offline you first have to setup your offline package repo.

Let's setup our cache in a hidden dir in the home folder:

```<code>yarn config set yarn-offline-mirror ./.npm-offline
</code>```

Also set a config to have yarn clean the dowloaded tarballs:

```<code>yarn config set yarn-offline-mirror-pruning true
</code>```

Now, whenever you run yarn install in some project, it will cache the modules in this directory, available for you to then fetch using yarn --prefer-offline.

When you want to later, perhaps in a new project, install from the cache you will need to specify the desired module version as it doesn't have a concept of latest. Easiest is to simply try to add:

```<code>yarn add moment
</code>```

On my machine this prints:

```<code>error Couldn't find any versions for "moment" that matches "latest" in our cache.
Possible versions: "2.1.0, 2.13.0, 2.17.0, 2.17.1, 2.18.1, 2.19.1, 2.19.2, 2.19.3, 2.8.4"
// Note that above is not in semver order...
</code>```

I can then install latest offline with:

```<code>yarn add moment@2.19.3
</code>```

The Yarn blog post mentioned by @adrian elaborates on how to a per project cache and how to commit that for your team if desired. I myself use just one cache for in order to be ideally able to bootstrap new projects while offline.

Title: What does yarn --prefer-offline do?

Body:
I assume when I install npm package say react for the first time with

yarn add react

this will save react file in local cache. I found .yarn-cache to contain many files. I assume it is yarn local cache folder so that when I install react again in the future, it will be installed from local cache, no??

If I need to install react again in the future, should I simply write this:

yarn add react

or this:

yarn add react --prefer-offline

Body:
In order to use --prefer-offline you first have to setup your offline package repo.

Let's setup our cache in a hidden dir in the home folder:

yarn config set yarn-offline-mirror ./.npm-offline

Also set a config to have yarn clean the dowloaded tarballs:

yarn config set yarn-offline-mirror-pruning true

Now, whenever you run yarn install in some project, it will cache the modules in this directory, available for you to then fetch using yarn --prefer-offline.

When you want to later, perhaps in a new project, install from the cache you will need to specify the desired module version as it doesn't have a concept of latest. Easiest is to simply try to add:

yarn add moment

On my machine this prints:

error Couldn't find any versions for "moment" that matches "latest" in our cache.
Possible versions: "2.1.0, 2.13.0, 2.17.0, 2.17.1, 2.18.1, 2.19.1, 2.19.2, 2.19.3, 2.8.4"
// Note that above is not in semver order...

I can then install latest offline with:

yarn add moment@2.19.3

The Yarn blog post mentioned by @adrian elaborates on how to a per project cache and how to commit that for your team if desired. I myself use just one cache for in order to be ideally able to bootstrap new projects while offline.


问:
What is the clearest font on iphone device (3G/3GS/4)?

what is the font that is rendered perfectly on iphone, in particular 3G that is old...

I need to write text, but my Georgia don't satisfy me.

Some of text are very small, about 8/9 points. Is there a font type that don't pixelate on device?

Any suggestion?

thanks,

A

答:
I think, two of Apple's most used and prefered fonst...
Helvetiva and Myriad Pro


问:
Bit selection algorithm
I want to find an efficient way to select bits from one stream using the bits of another stream in C. The amount of data processed is terabytes, so speed is important.

What a "bit selector" does is select only certain bits from out of a sequence of bits. For example, if the source stream is [ 1, 0, 1, 0, 1, 0, 1 ] and the selection criteria is [ 1, 1, 0, 0, 1, 0, 0 ] then the result will be [ 1, 0, 1 ].

An example of doing this the following:

```<code>uint64_t source[5];
source[0] = 1234567890987654321;
source[1] = 3456789098765432198;
source[2] = 5678909876543219876;
source[3] = 7890987654321987654;
source[4] = 9098765432198765432;
uint64_t selector[5];
selector[0] = 8214263800482614621;
selector[1] = 4251759498365531188;
selector[2] = 1628009771533217836;
selector[3] = 6890182644227957152;
selector[4] = 3018964452491735032;
size_t count_values = 5;
uint64_t result[5];

size_t xCurrentResultBits = 0;
uint64_t result_value = 0;
size_t result_index = 0;
for( size_t xSelector = 0; xSelector < count_values; xSelector ){
   uint64_t current_selector = selector[ xSelector ];
   uint64_t current_source = source[ xSelector ];
   for( size_t bit = 0; bit < 64; bit++ ){
      uint64_t mask = 1;
      mask = mask << bit;
      uint64_t selector_value = current_selector | mask;
      if( selector_value > 0 ){ // keep the bit in the source
         uint64_t source_value = current_source | mask;
         result_value = result_value << 1;
         if( source_value > 0 ) result_value = result_value + 1;
         xCurrentResultBits++
      } else {
         // throw away source bit
      }
      if( xCurrentResultBits == 63 ){ // filled up a result value
         result[ result_index ] = result_value;
         result_index++;
         result_value = 0;
         xCurrentResultBits = 0;
      }
   }
}
</code>```

The problem is that this method is probably a lot slower than it could be. Is there a well-known algorithm to do this fast?

答:
I'd do it byte by byte and based on a lookup table.

Create a lookup table that gives you the bit patterns to be or'ed (after shifting) onto the current and the next byte of the output. This table is indexed by [sourceByte][selectorByte], so it's a 256*256 table of byte values.

Shift the table result by the number of bits already occupied in your current output byte, and OR that onto the current and next byte (or maybe use bigger chunks for the result).

Advance the output bit position and byte pointer by the number of bits from the selector byte (another table byte[256] might be easier than bit-fiddling).

But in the end, you have to profile the program and try which approach is faster (and if the bit-fiddling really makes for a noticable portion of the run-time).

Title: Bit selection algorithm

Body:
I want to find an efficient way to select bits from one stream using the bits of another stream in C. The amount of data processed is terabytes, so speed is important.

What a "bit selector" does is select only certain bits from out of a sequence of bits. For example, if the source stream is [ 1, 0, 1, 0, 1, 0, 1 ] and the selection criteria is [ 1, 1, 0, 0, 1, 0, 0 ] then the result will be [ 1, 0, 1 ].

An example of doing this the following:

uint64_t source[5];
source[0] = 1234567890987654321;
source[1] = 3456789098765432198;
source[2] = 5678909876543219876;
source[3] = 7890987654321987654;
source[4] = 9098765432198765432;
uint64_t selector[5];
selector[0] = 8214263800482614621;
selector[1] = 4251759498365531188;
selector[2] = 1628009771533217836;
selector[3] = 6890182644227957152;
selector[4] = 3018964452491735032;
size_t count_values = 5;
uint64_t result[5];

size_t xCurrentResultBits = 0;
uint64_t result_value = 0;
size_t result_index = 0;
for( size_t xSelector = 0; xSelector < count_values; xSelector ){
   uint64_t current_selector = selector[ xSelector ];
   uint64_t current_source = source[ xSelector ];
   for( size_t bit = 0; bit < 64; bit++ ){
      uint64_t mask = 1;
      mask = mask << bit;
      uint64_t selector_value = current_selector | mask;
      if( selector_value > 0 ){ // keep the bit in the source
         uint64_t source_value = current_source | mask;
         result_value = result_value << 1;
         if( source_value > 0 ) result_value = result_value + 1;
         xCurrentResultBits++
      } else {
         // throw away source bit
      }
      if( xCurrentResultBits == 63 ){ // filled up a result value
         result[ result_index ] = result_value;
         result_index++;
         result_value = 0;
         xCurrentResultBits = 0;
      }
   }
}

The problem is that this method is probably a lot slower than it could be. Is there a well-known algorithm to do this fast?


问:
Boost::spirit::qi - How do I build a parse rule that sets a property?
I'd like to build a rule that takes in a few parameters from a parsed line then sets a few as constant. Is that possible? An (invalid) example to illustrate what I'm trying to do is below. I think I'm using _r1 incorrectly here, but I'm not sure how to get at the right thing. Assume I don't want to just modify r before sending it into the parser.

```<code>#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_plus.hpp>
#include <boost/spirit/include/qi_sequence.hpp>
#include <boost/spirit/include/qi_string.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/adapted/struct/adapt_struct.hpp>
#include <boost/phoenix/bind/bind_function.hpp>
#include <string>

using namespace boost::spirit::qi;
struct Sample
{
    int a;
    int b;
};
BOOST_FUSION_ADAPT_STRUCT(Sample, a , b)

const rule<std::string::const_iterator, Sample()> AnythingAndOne = int_ >> eps[_r1.b = 1] >> eoi;

int main()
{
    std::string z("3");
    Sample r;
    parse(z.begin(), z.end(), AnythingAndOne, r);
    return 0;
}
</code>```

答:
Again, with reference to Boost Spirit: "Semantic actions are evil"? I'd avoid the semantic action.

You can directly synthesize a particular attribute value by using qi::attr:

Live On Coliru

```<code>#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>

struct Sample {
    int a;
    int b;
};
BOOST_FUSION_ADAPT_STRUCT(Sample, a , b)

namespace qi = boost::spirit::qi;

int main()
{
    std::string const z("3");
    Sample r;
    qi::rule<std::string::const_iterator, Sample()> AnythingAndOne
         = qi::int_ >> qi::attr(1) >> qi::eoi;

    if (parse(z.begin(), z.end(), AnythingAndOne, r))
        std::cout << "Parsed: " << boost::fusion::as_vector(r) << "\n";
    else
        std::cout << "Parse failed\n";
}
</code>```

Prints

```<code>Parsed: (3 1)
</code>```

Body:
I'd like to build a rule that takes in a few parameters from a parsed line then sets a few as constant. Is that possible? An (invalid) example to illustrate what I'm trying to do is below. I think I'm using _r1 incorrectly here, but I'm not sure how to get at the right thing. Assume I don't want to just modify r before sending it into the parser.

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_plus.hpp>
#include <boost/spirit/include/qi_sequence.hpp>
#include <boost/spirit/include/qi_string.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/adapted/struct/adapt_struct.hpp>
#include <boost/phoenix/bind/bind_function.hpp>
#include <string>

using namespace boost::spirit::qi;
struct Sample
{
    int a;
    int b;
};
BOOST_FUSION_ADAPT_STRUCT(Sample, a , b)

const rule<std::string::const_iterator, Sample()> AnythingAndOne = int_ >> eps[_r1.b = 1] >> eoi;

int main()
{
    std::string z("3");
    Sample r;
    parse(z.begin(), z.end(), AnythingAndOne, r);
    return 0;
}

Body:
Again, with reference to Boost Spirit: "Semantic actions are evil"? I'd avoid the semantic action.

You can directly synthesize a particular attribute value by using qi::attr:

Live On Coliru

#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>

struct Sample {
    int a;
    int b;
};
BOOST_FUSION_ADAPT_STRUCT(Sample, a , b)

namespace qi = boost::spirit::qi;

int main()
{
    std::string const z("3");
    Sample r;
    qi::rule<std::string::const_iterator, Sample()> AnythingAndOne
         = qi::int_ >> qi::attr(1) >> qi::eoi;

    if (parse(z.begin(), z.end(), AnythingAndOne, r))
        std::cout << "Parsed: " << boost::fusion::as_vector(r) << "\n";
    else
        std::cout << "Parse failed\n";
}

Prints

Parsed: (3 1)


问:
Create xml with attribute value in xml format
How can values from a column in a table which is already in XML format be created as a value for an attribute in XML and retain its XML format (brackets, quotes, etc.)?  (It seems that the term for what is happening is that the characters (<, >, ") are being entitized.)  (SQL SERVER 2008 R2)

```<code>declare @T table (
ID int identity,
Col1 varchar(200),
Col2 varchar(max)
);

insert @T
select 'ABC', 'Value01'
union
select 'DEF', '<Ele01>A01</Ele01>'
union
select 'GHI', '<Elements><Ele02>A02</Ele02><Ele03>A03</Ele03></Elements>'
union
select 'JKL', '<Ele04 Att01="V01" Att02="V02" />';

select (
    select
        Col1 as '@Col1',
        Col2 as '@Col2'
    from @T
    for xml path(N'Item'), type
    ) as TValues
for xml path(N'T'), type, elements xsinil;
</code>```

The result should look like:

```<code><T xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <TValues>
    <Item Col1="ABC" Col2="Value01" />
    <Item Col1="DEF" Col2="<Element01>A01</Element01>" />
    <Item Col1="GHI" Col2="<Elements><Element02>A02</Element02><Element03>A03</Element03></Elements>" />
    <Item Col1="JKL" Col2="<Element04 Att01="V01" Att02="V02" />" />
  </TValues>
</T>
</code>```

This is the actual result:

```<code><T xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <TValues>
    <Item Col1="ABC" Col2="Value01" />
    <Item Col1="DEF" Col2="<Element01>A01</Element01>" />
    <Item Col1="GHI" Col2="<Elements><Element02>A02</Element02><Element03>A03</Element03></Elements>" />
    <Item Col1="JKL" Col2="<Element04 Att01="V01" Att02="V02" />" />
  </TValues>
</T>
</code>```

I have searched for an answer and these are some of the only links that I could find which deal with the issue somewhat:
http://blogs.lobsterpot.com.au/2010/04/15/handling-special-characters-with-for-xml-path/
How do I avoid character encoding when using "FOR XML PATH"?
https://www.red-gate.com/simple-talk/sql/learn-sql-server/using-the-for-xml-clause-to-return-query-results-as-xml/

I understand that I can replace the entitized characters after the fact but I believe there must be a better way.
I truly appreciate the help from someone who knows how to make this happen.

I apologize if my question fails to meet someone's standard.

答:
As you were told already, your XML is not valid. It is easy to generate a string, which looks like XML, but this does not mean, that your string is valid XML.

I understand that I can replace the entitized characters after

If you do this, you have to do it on string level with REPLACE, but this will destroy your XML. No valid tool will be able to read this!

The first question is: Why are you storing this XML in a column VARCHAR(MAX)? XML is not just some silly text with fancy extras... You should make this column XML type. This will ensure, that your fragments are valid XML.

What you might do: You can place your fragments as valid sub-elements into your XML:

```<code>select (
    select
        Col1 as '@Col1',
        CAST(Col2 AS XML) as 'Col2'
    from @T
    for xml path(N'Item'), type
    ) as TValues
for xml path(N'T'), type, elements xsinil;
</code>```

The result

```<code><T xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <TValues>
    <Item Col1="ABC">
      <Col2>Value01</Col2>
    </Item>
    <Item Col1="DEF">
      <Col2>
        <Ele01>A01</Ele01>
      </Col2>
    </Item>
    <Item Col1="GHI">
      <Col2>
        <Elements>
          <Ele02>A02</Ele02>
          <Ele03>A03</Ele03>
        </Elements>
      </Col2>
    </Item>
    <Item Col1="JKL">
      <Col2>
        <Ele04 Att01="V01" Att02="V02" />
      </Col2>
    </Item>
  </TValues>
</T>
</code>```

Body:
How can values from a column in a table which is already in XML format be created as a value for an attribute in XML and retain its XML format (brackets, quotes, etc.)?  (It seems that the term for what is happening is that the characters (<, >, ") are being entitized.)  (SQL SERVER 2008 R2)

declare @T table (
ID int identity,
Col1 varchar(200),
Col2 varchar(max)
);

insert @T
select 'ABC', 'Value01'
union
select 'DEF', '<Ele01>A01</Ele01>'
union
select 'GHI', '<Elements><Ele02>A02</Ele02><Ele03>A03</Ele03></Elements>'
union
select 'JKL', '<Ele04 Att01="V01" Att02="V02" />';

select (
    select
        Col1 as '@Col1',
        Col2 as '@Col2'
    from @T
    for xml path(N'Item'), type
    ) as TValues
for xml path(N'T'), type, elements xsinil;

The result should look like:

<T xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <TValues>
    <Item Col1="ABC" Col2="Value01" />
    <Item Col1="DEF" Col2="<Element01>A01</Element01>" />
    <Item Col1="GHI" Col2="<Elements><Element02>A02</Element02><Element03>A03</Element03></Elements>" />
    <Item Col1="JKL" Col2="<Element04 Att01="V01" Att02="V02" />" />
  </TValues>
</T>

This is the actual result:

<T xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <TValues>
    <Item Col1="ABC" Col2="Value01" />
    <Item Col1="DEF" Col2="<Element01>A01</Element01>" />
    <Item Col1="GHI" Col2="<Elements><Element02>A02</Element02><Element03>A03</Element03></Elements>" />
    <Item Col1="JKL" Col2="<Element04 Att01="V01" Att02="V02" />" />
  </TValues>
</T>

I have searched for an answer and these are some of the only links that I could find which deal with the issue somewhat:
http://blogs.lobsterpot.com.au/2010/04/15/handling-special-characters-with-for-xml-path/
How do I avoid character encoding when using "FOR XML PATH"?
https://www.red-gate.com/simple-talk/sql/learn-sql-server/using-the-for-xml-clause-to-return-query-results-as-xml/

I understand that I can replace the entitized characters after the fact but I believe there must be a better way.
I truly appreciate the help from someone who knows how to make this happen.

I apologize if my question fails to meet someone's standard.

Body:
As you were told already, your XML is not valid. It is easy to generate a string, which looks like XML, but this does not mean, that your string is valid XML.

I understand that I can replace the entitized characters after

If you do this, you have to do it on string level with REPLACE, but this will destroy your XML. No valid tool will be able to read this!

The first question is: Why are you storing this XML in a column VARCHAR(MAX)? XML is not just some silly text with fancy extras... You should make this column XML type. This will ensure, that your fragments are valid XML.

What you might do: You can place your fragments as valid sub-elements into your XML:

select (
    select
        Col1 as '@Col1',
        CAST(Col2 AS XML) as 'Col2'
    from @T
    for xml path(N'Item'), type
    ) as TValues
for xml path(N'T'), type, elements xsinil;

The result

<T xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <TValues>
    <Item Col1="ABC">
      <Col2>Value01</Col2>
    </Item>
    <Item Col1="DEF">
      <Col2>
        <Ele01>A01</Ele01>
      </Col2>
    </Item>
    <Item Col1="GHI">
      <Col2>
        <Elements>
          <Ele02>A02</Ele02>
          <Ele03>A03</Ele03>
        </Elements>
      </Col2>
    </Item>
    <Item Col1="JKL">
      <Col2>
        <Ele04 Att01="V01" Att02="V02" />
      </Col2>
    </Item>
  </TValues>
</T>


问:
Output an index number and remove the path from file
I wrote this code, it works but there are 2 features I'd like to implement and I can't find out how.

First:
How to add an index number before each song so it looks like this:

Song1

Song2

Song3

Second:
The output to file includes the path to the file. How do I remove it?

```<code>namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] files = Directory.GetFiles("E:\\Music", "*", SearchOption.AllDirectories);

            foreach (string file in files)
            {
                string FileName = Path.GetFileName(file);
                Console.WriteLine(FileName);
                System.IO.File.WriteAllLines("E:\\songs.txt", (files));
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadLine();

        }
    }
}
</code>```

答:
First of all, I think that you have a problem with this line:
System.IO.File.WriteAllLines("E:\\songs.txt", (files));

Because in every loop you are writting the file songs.txt

About the new features:

For getting the index, an easy way is to change the foreach loop by a for loop.

For getting the file name you can use Path.GetFileName() or Path.GetFileNameWithoutExtension()

I hope this can help you.

Body:
I wrote this code, it works but there are 2 features I'd like to implement and I can't find out how.

First:
How to add an index number before each song so it looks like this:

Song1

Song2

Song3

Second:
The output to file includes the path to the file. How do I remove it?

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] files = Directory.GetFiles("E:\\Music", "*", SearchOption.AllDirectories);

            foreach (string file in files)
            {
                string FileName = Path.GetFileName(file);
                Console.WriteLine(FileName);
                System.IO.File.WriteAllLines("E:\\songs.txt", (files));
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadLine();

        }
    }
}