问:
Check if a Word Document is password protected without opening it
I'm using the Microsoft Office Interop namespace in order to password protect Word documents.
I first create an instance of Word as a background process and gather the list of Word documents I want to protect. The issue I have is that when the application gets to an already secure document it opens with a prompt for the set password. After dismissing this it runs through the rest of the documents with the instance of Word now in the foreground.

I would like to skip past the previously protected documents. My code is currently as follows:

```<code>    private void Protect_Word(FileInfo file)
    {
            Word.Document doc = wrd.Documents.Open(file.FullName);
            if (!doc.HasPassword)
            {
                doc.Password = this.passwordBox.Text;
                doc.Save();

            }
            ((Microsoft.Office.Interop.Word._Document)doc).Close(0);
    }
</code>```

The problem with this setup is that the password for a document is being asked for before I can call HasPassword. Is there a way I can programatically check the document for a password prior to actually opening it?

答:
I was looking for similar information and couldn't found a straight answer.
I managed to find a good solution for two problems using vb .net:

Detect if a docx is password protected to open file:
msgbox(documentName.haspassword.tostring)
This will give you true or false for the password protection

SaveAs a password protected document to a document without password:
documentName.password("known password") = ""
This will save a copy of the open document without the password

Body:
I'm using the Microsoft Office Interop namespace in order to password protect Word documents.
I first create an instance of Word as a background process and gather the list of Word documents I want to protect. The issue I have is that when the application gets to an already secure document it opens with a prompt for the set password. After dismissing this it runs through the rest of the documents with the instance of Word now in the foreground.

I would like to skip past the previously protected documents. My code is currently as follows:

    private void Protect_Word(FileInfo file)
    {
            Word.Document doc = wrd.Documents.Open(file.FullName);
            if (!doc.HasPassword)
            {
                doc.Password = this.passwordBox.Text;
                doc.Save();

            }
            ((Microsoft.Office.Interop.Word._Document)doc).Close(0);
    }

The problem with this setup is that the password for a document is being asked for before I can call HasPassword. Is there a way I can programatically check the document for a password prior to actually opening it?


来源: stackexchange

问:
Why open source code at Github isn't matching with the ones provided in package?
Screenshot:

As you can the code on the left (inside IDE) isn't matching with the one provided on Github, and I am using latest version of the package. I have highlighted the piece of code I'm referring to.

pubspec.yaml

```<code>in_app_purchase: 0.3.1
</code>```

Here is code link

Here is the package link

答:
As mentioned in the comments, this is because the author didn't push those changes to pub.dev , if you want you can use the package from the github directly by modifying your pubspec.yaml file accordingly, like the following example

```<code>dependencies:
  plugin1:
    git:
      url: git://github.com/flutter/plugin1.git
</code>```

The above example is taken from Flutter Docs. In your case, it could be something like

```<code>dependencies:
  flutter_plugins:
    git:
      url: git://github.com/flutter/plugins.git
</code>```

Or if you only need in_app_purchase and not the entire plugin library then you can do the following

```<code>dependencies:
  in_app_purchase:
    git:
      url: git://github.com/flutter/plugins.git
      path: packages/in_app_purchase
</code>```

IDE code matches the right-hand side code of OP

ContentLicense: CC BY-SA 4.0

Body:
Screenshot:

As you can the code on the left (inside IDE) isn't matching with the one provided on Github, and I am using latest version of the package. I have highlighted the piece of code I'm referring to.

pubspec.yaml

in_app_purchase: 0.3.1

Here is code link

Here is the package link

Body:
As mentioned in the comments, this is because the author didn't push those changes to pub.dev , if you want you can use the package from the github directly by modifying your pubspec.yaml file accordingly, like the following example

dependencies:
  plugin1:
    git:
      url: git://github.com/flutter/plugin1.git

The above example is taken from Flutter Docs. In your case, it could be something like

dependencies:
  flutter_plugins:
    git:
      url: git://github.com/flutter/plugins.git

Or if you only need in_app_purchase and not the entire plugin library then you can do the following

dependencies:
  in_app_purchase:
    git:
      url: git://github.com/flutter/plugins.git
      path: packages/in_app_purchase

IDE code matches the right-hand side code of OP


问:
Tool is delaying output in eclipse plugin developemnt
I am developing plugin for eclipse. It will run my clang tool. In clang tool i am writing simple pass to check that every case and default statement must have the break statement.

I am running my clang tool using process builder.
I am using job API to run my tool and Display class to print the error.

when i run my plugin i am facing some issue.
Let say i commented my break statement of one of the case or default statement , it should print error in console that every case and default statement must have the break statement.
it is printing error  after i type something else or some space or trying to uncomment after my comment .
similarly when i do uncomment , it should not print the error , but it is printing , but again when i type something or some space or trying to comment , error disappear.

following is the link of my code

https://github.com/sunilsarode/eclipse_plugin/blob/master/ccchecker/src/ccchecker/handlers/SampleHandler.java

following image show the first case not printing error on my eclipse console on which i am developing a plugin .

and this shows that second case printing error on my eclipse console on which i am developing a plugin .

any help in this ?

EDIT:
I want my plugin-in to output something on console view (not on development console ) or some dot kind of thing on the gutter of the text editor and when i click or hover on that dot , i want to show some popup with error message.

I tried to print message on console view by crating console using this link https://wiki.eclipse.org/FAQ_How_do_I_write_to_the_console_from_a_plug-in%3F
 it works , but new problem is , i lost focus from text editor to console that i have created and because of this i am unable to test the problem i mentioned in question.

sorry too much i am expecting.

Following image show that  text editor lost its focus to console view and the button you have mentioned is not there at console view but it is there at console of eclipse on which i am writing a code.

答:
Following keypress method and addKeyListener is not working when i press the Ctrl+s. In order to get the save event we have to use the ICommandService with save command.

```<code>((StyledText) editor.getAdapter(Control.class)).addKeyListener(new KeyListener() {

            @Override
            public void keyPressed(KeyEvent keyEvent) {

                if (((keyEvent.stateMask & SWT.CTRL) == SWT.CTRL) && (keyEvent.keyCode == 's')) {
                    // System.out.println("From Display I am the Key down !!" + keyEvent.keyCode);
                    Job job = new Job("My job") {

                        @Override
                        protected IStatus run(IProgressMonitor arg0) {
                            // TODO Auto-generated method stub
                            StringBuilder builder = runCCChecker(path);

                            syncWithUi(builder);
                            return Status.OK_STATUS;
                        }

                    };

                    job.setUser(true);
                    job.schedule();

                }

            }

            @Override
            public void keyReleased(KeyEvent arg0) {

            }
        });
</code>```

In order to show the warning at each line I am using IMarker interface.
In order to run my tool only on current active file of eclipse editor on which I am firing save command , I am using IPartService service.

following is the link of my code

https://github.com/sunilsarode/eclipse_plugin/blob/master/ccchecker/src/ccchecker/handlers/SampleHandler.java

It is working fine. If anybody find any issue please let me know.

Body:
Following keypress method and addKeyListener is not working when i press the Ctrl+s. In order to get the save event we have to use the ICommandService with save command.

((StyledText) editor.getAdapter(Control.class)).addKeyListener(new KeyListener() {

            @Override
            public void keyPressed(KeyEvent keyEvent) {

                if (((keyEvent.stateMask & SWT.CTRL) == SWT.CTRL) && (keyEvent.keyCode == 's')) {
                    // System.out.println("From Display I am the Key down !!" + keyEvent.keyCode);
                    Job job = new Job("My job") {

                        @Override
                        protected IStatus run(IProgressMonitor arg0) {
                            // TODO Auto-generated method stub
                            StringBuilder builder = runCCChecker(path);

                            syncWithUi(builder);
                            return Status.OK_STATUS;
                        }

                    };

                    job.setUser(true);
                    job.schedule();

                }

            }

            @Override
            public void keyReleased(KeyEvent arg0) {

            }
        });

In order to show the warning at each line I am using IMarker interface.
In order to run my tool only on current active file of eclipse editor on which I am firing save command , I am using IPartService service.

following is the link of my code

https://github.com/sunilsarode/eclipse_plugin/blob/master/ccchecker/src/ccchecker/handlers/SampleHandler.java

It is working fine. If anybody find any issue please let me know.


问:
Using the JQuery Autotab plugin, is it possible to create a field that accepts exactly 6 digits?
I'm working with the Autotab JQuery plugin

Here's an example they give in the Autotab documentation...

Regular Expression (Allows numbers and periods)

```<code>$('#regex').autotab({ format: 'custom', pattern: '[^0-9\.]' });
</code>```

The weird thing is that the pattern is a set of characters negated by the caret (^).  So I assume the way this works is that the pattern specifies characters that the user isn't allowed to enter.

I was trying to create a field that could be left blank by the user, or would accept six and only six (no more, no less) digits.  Is this more complex than Autotab allows?

答:
if what you need is to limit to only 6 characters you can create a range, this way you should solve the problem ...</p>

```<code>$('#regex').autotab({ format: 'custom', pattern: '[^0-9+$]', maxlength: 6, minlength: 6});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working with the Autotab JQuery plugin

Here's an example they give in the Autotab documentation...

Regular Expression (Allows numbers and periods)

$('#regex').autotab({ format: 'custom', pattern: '[^0-9\.]' });

The weird thing is that the pattern is a set of characters negated by the caret (^).  So I assume the way this works is that the pattern specifies characters that the user isn't allowed to enter.

I was trying to create a field that could be left blank by the user, or would accept six and only six (no more, no less) digits.  Is this more complex than Autotab allows?

Body:
if what you need is to limit to only 6 characters you can create a range, this way you should solve the problem ...

$('#regex').autotab({ format: 'custom', pattern: '[^0-9+$]', maxlength: 6, minlength: 6});


问:
Understanding the inner workings of a programming language
Where would be a good place to start learning the inner workings of a programming language like C?

Would it be learning how a parser/lexer works?

答:
No, not really. Parsing is only a small part of the complexity of a language, and not the most interesting part. Typing (for C, not such a big part either), optimization, code generation: those are the bulk of the compiler.

The first step is to know the language well. Get a book such as The C Programming Language by Brian Kernighan and Dennis Ritchie (“K&R”). Do the exercises.

Then you may find it interesting to learn how a compiler works.

A good way of measuring your understanding of C is to read the
standard. (This is not a tutorial!) See how much you understand. See if you understand why the standard does things the way it does.


问:
Electron for MAS (Mac app store)
After doing a lot of research I've found that in order to build an electron app for the Mac App Store, it requires a special build of Electron. Previously though I've only used electron-prebuilt installed via npm.

Is there a way to install the mac app store version via npm or is there a pre-built version? I can't seem to find any such packages. I do notice the full code is here https://github.com/atom/electron/releases but, it would be nicer to have the dependencies remain in my package.json if possible.  Is there a recommended way to set this up?

答:
If you use electron-forge for packaging, you can run package command with parameter --platform=mas which will package your app with the right version of electron for Mac App store. I have done it successfully with my electron application.

```<code>electron-forge package --platform=mas
</code>```

Title: Electron for MAS (Mac app store)

Body:
If you use electron-forge for packaging, you can run package command with parameter --platform=mas which will package your app with the right version of electron for Mac App store. I have done it successfully with my electron application.

electron-forge package --platform=mas


问:
Dynamically render information from two arrays
I have this data:

```<code>"PensionPlanSummary": [
        {
            "Type": "DefinedContributionPension",
            "Participants": [
                {
                    "Year": 2018,
                    "Value": 425.0
                }
            ],
            "TotalAssets": [
                {
                    "Year": 2018,
                    "Value": 629282.0
                }
            ],
            "NetAssets": [
                {
                    "Year": 2018,
                    "Value": 629282.0
                }
            ],

        },
        {
            "Type": "Welfare",
            "Participants": [
                {
                    "Year": 2018,
                    "Value": 252.0
                },
                {
                    "Year": 2017,
                    "Value": 389.0
                }
            ],
            "TotalAssets": [
                {
                    "Year": 2018,
                    "Value": 0.0
                },
                {
                    "Year": 2017,
                    "Value": 0.0
                }
            ],
            "NetAssets": [
                {
                    "Year": 2018,
                    "Value": 0.0
                },
                {
                    "Year": 2017,
                    "Value": 0.0
                }
            ]

        }
    ]
</code>```

I want to render data in this table:

Focus only on Participants. As you can see the data is not populated correct because it is populating by row and for example it should skip 2016 and 2017 for DefinedContributionPension and to fill 2018.
This table is result of this code:

```<code>{element.Participants.reverse().map((el, ind) => {
                              return uniqueYears.map((e, i) => {
                                // console.log(el.Year);
                                if (el.Year == e) {
                                  console.log(el.Year);
                                  return (
                                    <td key={ind}>
                                      ${numeral(el.Value).format("0,0")}
                                    </td>
                                  );
                                } else {
                                  return <td key={ind}> - </td>;
                                }
                              });
                            })}
</code>```

uniqueYears =[2016,2017,2018]
element is the single object (I have another map above). So as you can see I am mapping 1 time the participants and 1 time unique years and finding the 1 record that is true for the condition of equality of the element year. As you can see it is not putting the dash - and it is not populating table correct. I tried looping in other way - first to loop over the uniqueYears array and then to element.Participants but again it not worked as expected. Any ideas how to make it?
P.S.: Table should look like this way:

But lets focus only on participants as in example.

答:
Okay, I made a solution for your problem!

So, to get the years from your table, I made a simple function, which just returns the years from your statistics table header, instead of using the pre-defined uniqueYears = [2016, 2017, 2018], but feel free to use it if you need.

Obs.: The advantage of using this function is that you don't need to update your year heading and you uniqueYears array, update only your html table headings and you get the new data for all.

```<code>function getYears() {
  let years = [];
  for(const cell of document.querySelectorAll("[data-statistics='year'] th")) {
    if(cell.innerText.trim() !== "") years.push(parseInt(cell.innerText));
  }
  return years;
}
</code>```

So if you choose to use the function above make sure you have in yout html table this, the data-statistics="year" is required by the function.

        2016
        2017
        2018

```

<p>Right after, to get the entries of each one of your data, you can use the Object.entries(), which gives you the <code>key</code> and the <code>entry</code> of each property of your object.
The Array.prototype.splice() is to remove the <code>type</code> property, focusing only on the statistics data.</p>

<pre class="lang-js prettyprint-override"><code>for(const Plan of PensionPlanSummary) {
  let PlanEntries = Object.entries(Plan);

  PlanEntries = PlanEntries.splice(1, PlanEntries.length - 1);
  for(const pe of PlanEntries) {
    // pe[0] -> Title
    // pe[1] -> Data
    getRow(pe[0], pe[1]);
  }
}
</code>```

Then with your entries with a simple for loops you can achieve your data appending everything into Data	 and return a html row;

function getRow(index = "", data = null) {
  let years = getYears(); // Use your uniqueYears array here.
  let html = "
"

  // Sort by year
  data = data.slice(0);
  data.sort((a, b) => {
    return a.Year - b.Year;
  })

  html += `<td>${index}</td>`;

  for (const d of data) {
    while (years.length !== 0) {
      if (d.Year === years[0]) {
        html += `<td>${d.Value}</td>`;
        years.shift();
        break;
      } else {
        html += `<td>-</td>`;
      }
      years.shift();
    }
  }

  html += "
";

    // console.log(html);
  return html;
}
```

<p>The final result will be this html:</p>

<pre class="lang-html prettyprint-override"><code><tr>
    <td>Participants</td>
    <td>-</td>
    <td>-</td>
    <td>425</td>
</tr>
</code>```

Or for your 2 year data participants:

    Participants
    -
    389
    252

```

Now you only need to append in your html, as you want, take a look at JsFiddle if you need.

It is a little bit dirty code, but hope it helps!

Body:
I have this data:

"PensionPlanSummary": [
        {
            "Type": "DefinedContributionPension",
            "Participants": [
                {
                    "Year": 2018,
                    "Value": 425.0
                }
            ],
            "TotalAssets": [
                {
                    "Year": 2018,
                    "Value": 629282.0
                }
            ],
            "NetAssets": [
                {
                    "Year": 2018,
                    "Value": 629282.0
                }
            ],

        },
        {
            "Type": "Welfare",
            "Participants": [
                {
                    "Year": 2018,
                    "Value": 252.0
                },
                {
                    "Year": 2017,
                    "Value": 389.0
                }
            ],
            "TotalAssets": [
                {
                    "Year": 2018,
                    "Value": 0.0
                },
                {
                    "Year": 2017,
                    "Value": 0.0
                }
            ],
            "NetAssets": [
                {
                    "Year": 2018,
                    "Value": 0.0
                },
                {
                    "Year": 2017,
                    "Value": 0.0
                }
            ]

        }
    ]

I want to render data in this table:

Focus only on Participants. As you can see the data is not populated correct because it is populating by row and for example it should skip 2016 and 2017 for DefinedContributionPension and to fill 2018.
This table is result of this code:

{element.Participants.reverse().map((el, ind) => {
                              return uniqueYears.map((e, i) => {
                                // console.log(el.Year);
                                if (el.Year == e) {
                                  console.log(el.Year);
                                  return (

                                      ${numeral(el.Value).format("0,0")}

                                  );
                                } else {
                                  return  - 	;
                                }
                              });
                            })}

uniqueYears =[2016,2017,2018]
element is the single object (I have another map above). So as you can see I am mapping 1 time the participants and 1 time unique years and finding the 1 record that is true for the condition of equality of the element year. As you can see it is not putting the dash - and it is not populating table correct. I tried looping in other way - first to loop over the uniqueYears array and then to element.Participants but again it not worked as expected. Any ideas how to make it?
P.S.: Table should look like this way:

But lets focus only on participants as in example.

Body:
Okay, I made a solution for your problem!

So, to get the years from your table, I made a simple function, which just returns the years from your statistics table header, instead of using the pre-defined uniqueYears = [2016, 2017, 2018], but feel free to use it if you need.

Obs.: The advantage of using this function is that you don't need to update your year heading and you uniqueYears array, update only your html table headings and you get the new data for all.

function getYears() {
  let years = [];
  for(const cell of document.querySelectorAll("[data-statistics='year'] th")) {
    if(cell.innerText.trim() !== "") years.push(parseInt(cell.innerText));
  }
  return years;
}

So if you choose to use the function above make sure you have in yout html table this, the data-statistics="year" is required by the function.

<thead>
    <tr data-statistics="year">
        <th></th>
        <th>2016</th>
        <th>2017</th>
        <th>2018</th>
    </tr>
</thead>

Right after, to get the entries of each one of your data, you can use the Object.entries(), which gives you the key and the entry of each property of your object.
The Array.prototype.splice() is to remove the type property, focusing only on the statistics data.

for(const Plan of PensionPlanSummary) {
  let PlanEntries = Object.entries(Plan);

  PlanEntries = PlanEntries.splice(1, PlanEntries.length - 1);
  for(const pe of PlanEntries) {
    // pe[0] -> Title
    // pe[1] -> Data
    getRow(pe[0], pe[1]);
  }
}

Then with your entries with a simple for loops you can achieve your data appending everything into <td>Data</td> and return a html row;

function getRow(index = "", data = null) {
  let years = getYears(); // Use your uniqueYears array here.
  let html = "<tr>"

  // Sort by year
  data = data.slice(0);
  data.sort((a, b) => {
    return a.Year - b.Year;
  })

  html += `<td>${index}</td>`;

  for (const d of data) {
    while (years.length !== 0) {
      if (d.Year === years[0]) {
        html += `<td>${d.Value}</td>`;
        years.shift();
        break;
      } else {
        html += `<td>-</td>`;
      }
      years.shift();
    }
  }

  html += "</tr>";

    // console.log(html);
  return html;
}

The final result will be this html:

<tr>
    <td>Participants</td>
    <td>-</td>
    <td>-</td>
    <td>425</td>
</tr>

Or for your 2 year data participants:

<tr>
    <td>Participants</td>
    <td>-</td>
    <td>389</td>
    <td>252</td>
</tr>

Now you only need to append in your html, as you want, take a look at JsFiddle if you need.

It is a little bit dirty code, but hope it helps!


问:
How to register generated resources in Android Gradle task?
I am trying to generate some Android resources in a Gradle task.

I've written a task which parses an input file, and writes out an XML file to a location under the app's build directory.

app/build.gradle

import groovy.xml.MarkupBuilder

task generateSomeAppResources {
    ext.outputDir = new File(projectDir, "build/generated/res/values")
    doFirst {
        mkdir outputDir

        new File(outputDir, "generated.xml").withWriter { writer ->
            def destXml = new MarkupBuilder(new IndentPrinter(writer, "    ", true, true))
            destXml.setDoubleQuotes(true)
            def destXmlMkp = destXml.getMkp()
            destXmlMkp.xmlDeclaration(version: "1.0", encoding: "utf-8")
            destXmlMkp.comment("Generated at ${new Date()}")
            destXmlMkp.yield "\r\n"

            destXml.resources() {
                "string"("name": "generated_app_resource") {
                    destXmlMkp.yield("Some generated value for the app")
                }
            }
        }
    }
}
```

<p>This works fine, and the generated output looks like I expect.</p>

<p><strong>generated.xml</strong></p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<!-- Generated at Wed Feb 12 12:46:12 GMT 2020 -->
<resources>
    <string name="generated_app_resource">Some generated value for the app</string>
</resources>

</code>```

I am struggling to get the Android build system to detect the generated file, though. Google's advice is

to write a task that outputs a generated resource directory structure with whatever you need, use BaseVariant.registerGeneratedResFolders()

But documentation on registerGeneratedResFolders() is non-existent. After much tedious searching I found some example usages in the Play Services Plugin source, for example, so I tried to add something along those lines.

app/build.gradle

android.applicationVariants.all { variant ->
    def files = project.files(generateSomeAppResources.outputDir)
    files.builtBy(generateSomeAppResources)
    variant.preBuildProvider.configure { dependsOn(generateSomeAppResources) }
    variant.mergeResourcesProvider.configure { dependsOn(generateSomeAppResources) }
    variant.registerGeneratedResFolders(files)
}
```

But I'm missing something. The generated resource shows up purple in Android Studio, meaning that the IDE thinks it exists...

...but the code fails to compile with an Unresolved reference: generated_app_resource error.

I don't know what magic incantations are needed to make the Android build system pick up these resources. How do I get this to build?

答:
To create resources, android requires

1) A resource directory above values folder then you can add desired resources as per your requirement

2) Instruct the build process to add the generated resources while building R.java

So first configure your build resource task like:

```<code>task generateSomeAppResources {
    ext.outputDir = new File(projectDir, "build/generated/res/custom/values")
    print("path is "+projectDir)
    doFirst {
        mkdir outputDir

        new File(outputDir, "strings.xml").withWriter { writer ->
            def destXml = new MarkupBuilder(new IndentPrinter(writer, "    ", true, true))
            destXml.setDoubleQuotes(true)
            def destXmlMkp = destXml.getMkp()
            destXmlMkp.xmlDeclaration(version: "1.0", encoding: "utf-8")
            destXmlMkp.comment("Generated at ${new Date()}")
            destXmlMkp.yield "\r\n"

            destXml.resources() {
                "string"("name": "generated_app_resource") {
                    destXmlMkp.yield("Some generated value for the app")
                }
            }
        }
    }
}
</code>```

now add the path in the build process using sourceSets in build.gradle(app) like

```<code>android {
    //....
    sourceSets {
        main {
            res.srcDirs += [
                    'build/generated/res/custom',
            ]
        }
    }
}
</code>```

Additionally, add the task in the current build process as

```<code>gradle.projectsEvaluated {
    preBuild.dependsOn('generateSomeAppResources')
} // no need of `android.applicationVariants.all...`
</code>```

Now sync the project and it will work as expected.

Result:

Body:
I am trying to generate some Android resources in a Gradle task.

I've written a task which parses an input file, and writes out an XML file to a location under the app's build directory.

app/build.gradle

import groovy.xml.MarkupBuilder

task generateSomeAppResources {
    ext.outputDir = new File(projectDir, "build/generated/res/values")
    doFirst {
        mkdir outputDir

        new File(outputDir, "generated.xml").withWriter { writer ->
            def destXml = new MarkupBuilder(new IndentPrinter(writer, "    ", true, true))
            destXml.setDoubleQuotes(true)
            def destXmlMkp = destXml.getMkp()
            destXmlMkp.xmlDeclaration(version: "1.0", encoding: "utf-8")
            destXmlMkp.comment("Generated at ${new Date()}")
            destXmlMkp.yield "\r\n"

            destXml.resources() {
                "string"("name": "generated_app_resource") {
                    destXmlMkp.yield("Some generated value for the app")
                }
            }
        }
    }
}

This works fine, and the generated output looks like I expect.

generated.xml

<?xml version="1.0" encoding="utf-8"?>

<resources>
    <string name="generated_app_resource">Some generated value for the app</string>
</resources>

I am struggling to get the Android build system to detect the generated file, though. Google's advice is

to write a task that outputs a generated resource directory structure with whatever you need, use BaseVariant.registerGeneratedResFolders()

But documentation on registerGeneratedResFolders() is non-existent. After much tedious searching I found some example usages in the Play Services Plugin source, for example, so I tried to add something along those lines.

app/build.gradle

android.applicationVariants.all { variant ->
    def files = project.files(generateSomeAppResources.outputDir)
    files.builtBy(generateSomeAppResources)
    variant.preBuildProvider.configure { dependsOn(generateSomeAppResources) }
    variant.mergeResourcesProvider.configure { dependsOn(generateSomeAppResources) }
    variant.registerGeneratedResFolders(files)
}

But I'm missing something. The generated resource shows up purple in Android Studio, meaning that the IDE thinks it exists...

...but the code fails to compile with an Unresolved reference: generated_app_resource error.

I don't know what magic incantations are needed to make the Android build system pick up these resources. How do I get this to build?

Body:
To create resources, android requires

1) A resource directory above values folder then you can add desired resources as per your requirement

2) Instruct the build process to add the generated resources while building R.java

So first configure your build resource task like:

task generateSomeAppResources {
    ext.outputDir = new File(projectDir, "build/generated/res/custom/values")
    print("path is "+projectDir)
    doFirst {
        mkdir outputDir

        new File(outputDir, "strings.xml").withWriter { writer ->
            def destXml = new MarkupBuilder(new IndentPrinter(writer, "    ", true, true))
            destXml.setDoubleQuotes(true)
            def destXmlMkp = destXml.getMkp()
            destXmlMkp.xmlDeclaration(version: "1.0", encoding: "utf-8")
            destXmlMkp.comment("Generated at ${new Date()}")
            destXmlMkp.yield "\r\n"

            destXml.resources() {
                "string"("name": "generated_app_resource") {
                    destXmlMkp.yield("Some generated value for the app")
                }
            }
        }
    }
}

now add the path in the build process using sourceSets in build.gradle(app) like

android {
    //....
    sourceSets {
        main {
            res.srcDirs += [
                    'build/generated/res/custom',
            ]
        }
    }
}

Additionally, add the task in the current build process as

gradle.projectsEvaluated {
    preBuild.dependsOn('generateSomeAppResources')
} // no need of `android.applicationVariants.all...`

Now sync the project and it will work as expected.

Result:


问:
git rewrite history on remote
Disclaimer: I'm sure the title of this questions has already thrown up all your red flags and has made you want to either flame me or give me some explanations about why rewriting history is a grave sin. That's fine, you can do that, but please also address the question that I have.

I made some very, very bad mistakes in my git repo which blew it up to several gigabytes, yikes! Luckily, this is my own private repo, so I went through and rewrote history to remove all the mistakes. I followed these instructions, basically:

Find all the files I want to remove.

Use git-filter-branch to remove them.

Remove the records from the logs and refs

Re-garbage collect.

Doing this, I got the repo down from several gigabytes to a single megayte, yay! I followed up with a git push origin --force --all, and everything updated successfully.

Now, I want to clone my repo into a new system to test that my rewrite worked. When I clone, I get this:

```<code>remote: Enumerating objects: 6359, done.
remote: Counting objects: 100% (6359/6359), done.
remote: Compressing objects: 100% (4857/4857), done.
fatal: The remote end hung up unexpectedly 1.70 GiB | 3.05 MiB/s
</code>```

This seems strange to me. First of all, my repo is no longer several gigabytes, it is only 1 megabyte. Additionally, I do not have 6539 objects. After the rewrite, I only have 2128 objects. It seems like it is downloading the repo before I pushed the rewrite.

So my question is: How can I get the remote repo to see that I've rewritten history to make the repo much, much smaller?

Thanks!

P.S. The repo is on bitbucket.

答:
Double check there are no old branches on bitbucket that point to the un-filtered version of the project. It's possible that, for example, bitbucket protects the master branch from being force pushed, so it is still pointing to the old code. Running a git fetch then gitk --all --remotes on your old repo should be a good way to show you the state of the upstream repo.

The remote end should not have hung up unexpectedly either way, even if there was a lot of data to download. That sounds like a problem with your internet connection or with bitbucket.

Note: Rewriting history is a totally reasonable thing to do in cases like this, or if e.g. you have committed secret or GDPR protected information to your repository.

Title: git rewrite history on remote

Body:
Disclaimer: I'm sure the title of this questions has already thrown up all your red flags and has made you want to either flame me or give me some explanations about why rewriting history is a grave sin. That's fine, you can do that, but please also address the question that I have.

I made some very, very bad mistakes in my git repo which blew it up to several gigabytes, yikes! Luckily, this is my own private repo, so I went through and rewrote history to remove all the mistakes. I followed these instructions, basically:

Find all the files I want to remove.

Use git-filter-branch to remove them.

Remove the records from the logs and refs

Re-garbage collect.

Doing this, I got the repo down from several gigabytes to a single megayte, yay! I followed up with a git push origin --force --all, and everything updated successfully.

Now, I want to clone my repo into a new system to test that my rewrite worked. When I clone, I get this:

remote: Enumerating objects: 6359, done.
remote: Counting objects: 100% (6359/6359), done.
remote: Compressing objects: 100% (4857/4857), done.
fatal: The remote end hung up unexpectedly 1.70 GiB | 3.05 MiB/s

This seems strange to me. First of all, my repo is no longer several gigabytes, it is only 1 megabyte. Additionally, I do not have 6539 objects. After the rewrite, I only have 2128 objects. It seems like it is downloading the repo before I pushed the rewrite.

So my question is: How can I get the remote repo to see that I've rewritten history to make the repo much, much smaller?

Thanks!

P.S. The repo is on bitbucket.


问:
LPC1549 USB ISP fails on Linux
I'm struggling with programming NXP LPC1549 microcontroller using the built-in USB ISP bootloader. According to the user manual Chapter 34.5, the device shows up as a USB mass storage device. The old firmware can be deleted and new one should be downloaded just by dragging and dropping it to the USB device.

All of this works indeed, but my 64-bit Ubuntu 16.04 shows an error message when ejecting the USB drive saying

Error ejecting /dev/sdb: Command-line 'eject "/dev/sdb"' exited with non-zero exit status 1: eject: unable to eject, last error: Invalid argument

After reset the microcontroller doesn't wake up and when looking with a debugger it's clear that the firmware flashing didn't go as expected. This is output of hexdump of the actual binary file and this is a hexdump of first 0x2000 bytes of the microcontroller's memory read with the debugger.

The funny thing is that with Windows everything works without problems and the application runs as it should. This also verifies that my firmware is ok and working.

I'm right now a bit helpless since I don't have a clue what could be the problem and how to start solving it.

答:
I have met the same kind of issue on a Raspberry Pi (Raspbian). Finally the following command did the job:

```<code>dd bs=1024 conv=nocreat,notrunc if=/home/pi/new_version.bin of=/media/pi/CRP DISABLD/firmware.bin
</code>```

new_version.bin is the new firmware to flash on the device.

I hope this helps.

Michel

Title: LPC1549 USB ISP fails on Linux

Body:
I have met the same kind of issue on a Raspberry Pi (Raspbian). Finally the following command did the job:

dd bs=1024 conv=nocreat,notrunc if=/home/pi/new_version.bin of=/media/pi/CRP DISABLD/firmware.bin

new_version.bin is the new firmware to flash on the device.

I hope this helps.

Michel


问:
Find all lines where a value exists in one line
Here is my query

```<code>        select order_no, pkg_no, zone_no
        from T_DETAIL_ITEM a
        where order_no = 495
        order by order_no, pkg_no
</code>```

For a given package I have zone number = 0

What I need to do is return all the lines with the pkg_no = 1597. Because one where exists with a zero zone.

I tried a few different 'where exists' lines and it isn't working.

答:
The accepted answer is good, but I had saw that you noted you tried EXISTS, so I wrote this example up using that method. </p>

```<code>SELECT *
FROM T_Detail_Item  d
WHERE exists (SELECT * FROM T_Detail_Item  dx WHERE dx.pkg_no = d.pkg_no AND dx.zone_no = 0)
</code>```

Body:
Here is my query

        select order_no, pkg_no, zone_no
        from T_DETAIL_ITEM a
        where order_no = 495
        order by order_no, pkg_no

For a given package I have zone number = 0

What I need to do is return all the lines with the pkg_no = 1597. Because one where exists with a zero zone.

I tried a few different 'where exists' lines and it isn't working.

Body:
The accepted answer is good, but I had saw that you noted you tried EXISTS, so I wrote this example up using that method.

SELECT *
FROM T_Detail_Item  d
WHERE exists (SELECT * FROM T_Detail_Item  dx WHERE dx.pkg_no = d.pkg_no AND dx.zone_no = 0)


问:
VBA Excel sort the data from A to Z in one column with all data table changes
It might be such a duplicate question with:

VBA Sort A-Z on One Column

However I want to have the stuff clarified.

I tried to use this code for my purpose:

```<code>Sub SortAsc2()

    Dim LastRow As Long
    LastRow = Cells(Rows.Count, "M").End(xlUp).Row

    'Columns("D:D").Select
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("D"), _
    SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet1").Sort
        .SetRange Range("D2:D" & LastRow)
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

End Sub
</code>```

where I got an error:

1004 Method 'Range' of object_Global failed

I tried another code then

```<code>Sub SortDataWithoutHeader()
    Range("D1:D12").Sort Key1:=Range("D1"), Order1:=xlAscending, Header:=xlNo
End Sub
</code>```

But the sort happens only within the column, whereas the other data is unaffected.
I want to have values from other cells corresponding to the data sort.

Is anyone able to help?

答:
Give this a try.

Read code's comments and adjust it to fit your needs

Code:

```<code>Public Sub SortAsc2()

    Dim targetSheet As Worksheet
    Dim targetRange As Range

    Dim lastRow As Long

    ' Set a reference to the sheet
    Set targetSheet = ThisWorkbook.Worksheets("Sheet1")

    ' Find the last non empty row (based on column A)
    lastRow = targetSheet.Cells(targetSheet.Rows.Count, "A").End(xlUp).Row

    ' Set the range to be sorted (A2= begins in row 2 and ends in column K?)
    Set targetRange = targetSheet.Range("A2:K" & lastRow)

    ' Clear current sorting fields
    targetSheet.Sort.SortFields.Clear

    ' You are missing a 1 after "D" in Range in your code
    targetSheet.Sort.SortFields.Add Key:=Range("D1"), _
                                         SortOn:=xlSortOnValues, _
                                         Order:=xlAscending, _
                                         DataOption:=xlSortNormal

    With targetSheet.Sort
        .SetRange targetRange
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

End Sub
</code>```

Let me know if it works

Body:
It might be such a duplicate question with:

VBA Sort A-Z on One Column

However I want to have the stuff clarified.

I tried to use this code for my purpose:

Sub SortAsc2()

    Dim LastRow As Long
    LastRow = Cells(Rows.Count, "M").End(xlUp).Row

    'Columns("D:D").Select
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("D"), _
    SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet1").Sort
        .SetRange Range("D2:D" & LastRow)
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

End Sub

where I got an error:

1004 Method 'Range' of object_Global failed

I tried another code then

Sub SortDataWithoutHeader()
    Range("D1:D12").Sort Key1:=Range("D1"), Order1:=xlAscending, Header:=xlNo
End Sub

But the sort happens only within the column, whereas the other data is unaffected.
I want to have values from other cells corresponding to the data sort.

Is anyone able to help?

Body:
Give this a try.

Read code's comments and adjust it to fit your needs

Code:

Public Sub SortAsc2()

    Dim targetSheet As Worksheet
    Dim targetRange As Range

    Dim lastRow As Long

    ' Set a reference to the sheet
    Set targetSheet = ThisWorkbook.Worksheets("Sheet1")

    ' Find the last non empty row (based on column A)
    lastRow = targetSheet.Cells(targetSheet.Rows.Count, "A").End(xlUp).Row

    ' Set the range to be sorted (A2= begins in row 2 and ends in column K?)
    Set targetRange = targetSheet.Range("A2:K" & lastRow)

    ' Clear current sorting fields
    targetSheet.Sort.SortFields.Clear

    ' You are missing a 1 after "D" in Range in your code
    targetSheet.Sort.SortFields.Add Key:=Range("D1"), _
                                         SortOn:=xlSortOnValues, _
                                         Order:=xlAscending, _
                                         DataOption:=xlSortNormal

    With targetSheet.Sort
        .SetRange targetRange
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

End Sub

Let me know if it works


问:
How to display ID of each category in Woocommerce shop page with "Show Categories" selected
So I have my shop page set to list all categories (not products). I've been using hooks to alter the display, hide/show elements, etc.

How can I get the ID of each category in the list within that category's display? WC is obviously pulling data through the WC loop, as it displays the thumbnail and title of each category, gets the url for the category, etc. How can I grab the ID and display it, say, next to the title for example?

I need to know how to get the ID so that I can use that to display the value of an ACF field for each category in the list display. I assume the id will look something like product_cat_<id-num> or something.

Please help. Deadline is drawing near. When I Google anything related to displaying the categories on the shop page, it just gives me a bunch of links like the linked article above, which have nothing about how to extract category info from this loop...

答:
The issue was that I was not passing $category to my function.

This is how you would show a custom field below a title on shop page where categories are shown:

```<code>add_action( 'woocommerce_shop_loop_subcategory_title', 'end_shop_loop_title_wrap', 15 );

// pass $category to function - this is what i was missing
function end_shop_loop_title_wrap($category) {

    if( is_shop() ) {

        if ( $category ) {

            $term_id = 'product_cat_' . $category->term_id;

            echo the_field( 'custom_field_name', $term_id );

        }

    }

}
</code>```

I found the answer to my issue buried in Google on a Stack Exchange question that I couldn't find again if i tried (which is why i bookmarked it).

Thanks to Alex Uleberg for the answer that I found.

Why is there not more robust documentation/info/explanations for Woocommerce?

Body:
The issue was that I was not passing $category to my function.

This is how you would show a custom field below a title on shop page where categories are shown:

add_action( 'woocommerce_shop_loop_subcategory_title', 'end_shop_loop_title_wrap', 15 );

// pass $category to function - this is what i was missing
function end_shop_loop_title_wrap($category) {

    if( is_shop() ) {

        if ( $category ) {

            $term_id = 'product_cat_' . $category->term_id;

            echo the_field( 'custom_field_name', $term_id );

        }

    }

}

I found the answer to my issue buried in Google on a Stack Exchange question that I couldn't find again if i tried (which is why i bookmarked it).

Thanks to Alex Uleberg for the answer that I found.

Why is there not more robust documentation/info/explanations for Woocommerce?


问:
View source of file that is redirecting
When I click a URL a redirect is taking place using window.location

I'm trying to see the code behind this html file but since it is redirecting I am unable to view it. How can I view the source code the redirecting file ? Can I force the browser to not execute the javascript code and instead view it ?

答:
Try this:

Open a new tab on the browser

Open the inspector (F12) > Network tab

Check "Preserve log"

Paste the url you want to inspect in the address bar and press Enter

In the Network tab you can see all the resource called and also the "original" page (you can filter by string in order to find it easly)

Click the original page; on the right you can see the preview of that page

Title: View source of file that is redirecting


问:
Is there any Plugins SDK for Liferay 7.2 GA1 CE edition in eclipse
Please let me know if there is any Plugins SDK for liferay 7.2 GA1 in eclipse. I am trying to migrate from liferay 6.2 to Liferay 7.2.</p>

答:
It doesn't matter if there is one or not. (But as Ant isn't that fancy any more to manage today's dependencies, you shouldn't stay on the Plugins SDK anyway)

When you upgrade your code using Liferay's assistant, it will take care of migrating your Plugins-SDK code to Liferay workspace and you should take that opportunity. In the process it will also help changing all the modified packages to their new names.

In related news: You should always use the latest GA release of your target major release. As 7.2 GA2 is out: Definitely use that. It might contain updated upgrade routines, and there's no need to suffer from known and fixed bugs.


问:
How can I avoid duplicated functions using MVC?
I'm building an application using ASP.NET Core, and I would like to avoid duplicated code, in the following situation. I'm using usermanager to get all users with a specific role, but I'm using the exact same function for three diferent controllers because I don't know how to reuse the function.

I've read about action filters, but I don't know how to adapt my code in this situation.

Example first controller:

```<code>public class FirstController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}
</code>```

Second controller

```<code>public class SecondController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}
</code>```

Third controller

```<code>public class ThirdController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}
</code>```

答:
This is a good time to create a UserService class and add it to your services for it to be used in the controller through dependency Injection.

class UserService : IUserService
{
    Task<Dictionary<string, string>> GetAdminEmails()
    {
        ...
    }
}

```

<p>Add it to the service provider in startup.cs</p>

<p><code>services.AddScoped<IUserService, UserService>()</code></p>

<p>then use it in any controllers</p>

<pre class="lang-cs prettyprint-override"><code>public class FirstController : Controller
{
    private readonly IUserService _userService;
    public FirstController(IUserService userService)
    {
        _userService = userService;
    }
}
</code>```

if you need access to User in UserService, just inject IHttpContextAccessor into your UserService through DI.

Body:
I'm building an application using ASP.NET Core, and I would like to avoid duplicated code, in the following situation. I'm using usermanager to get all users with a specific role, but I'm using the exact same function for three diferent controllers because I don't know how to reuse the function.

I've read about action filters, but I don't know how to adapt my code in this situation.

Example first controller:

public class FirstController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}

Second controller

public class SecondController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}

Third controller

public class ThirdController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}

Body:
This is a good time to create a UserService class and add it to your services for it to be used in the controller through dependency Injection.

class UserService : IUserService
{
    Task<Dictionary<string, string>> GetAdminEmails()
    {
        ...
    }
}

Add it to the service provider in startup.cs

services.AddScoped<IUserService, UserService>()

then use it in any controllers

public class FirstController : Controller
{
    private readonly IUserService _userService;
    public FirstController(IUserService userService)
    {
        _userService = userService;
    }
}

if you need access to User in UserService, just inject IHttpContextAccessor into your UserService through DI.


问:
How do I pass a filename parameter to MediaPlayer in android kotlin?
How do I pass a filename parameter to MediaPlayer in android kotlin?

I have a sound file called "hello.wav" which is in the res/raw directory.  I have tried the following code and it will not accept the parameter sndfil as there is no file called sndfil.wav in the res/raw directory...

```<code>    private var sndfil = "xxxxxxxxxx"

    fun playnow (sndfil: String) {
        mp = MediaPlayer.create(this, R.raw.sndfil)
        mp.start()
        return
    }

    playnow("hello")
</code>```

How can a filename be passed as a parameter to android MediaPlayer ?

答:
take a look at the getIdentifier method it returns a resource identifier for the given resource name.

```<code>fun playnow (sndfil: String) {
    val resourceIdentifier = resources.getIdentifier(sndfil, "raw", packageName)
    mp = MediaPlayer.create(this,resourceIdentifier)
    mp.start()
    return
}

playnow("hello")
</code>```

Body:
How do I pass a filename parameter to MediaPlayer in android kotlin?

I have a sound file called "hello.wav" which is in the res/raw directory.  I have tried the following code and it will not accept the parameter sndfil as there is no file called sndfil.wav in the res/raw directory...

    private var sndfil = "xxxxxxxxxx"

    fun playnow (sndfil: String) {
        mp = MediaPlayer.create(this, R.raw.sndfil)
        mp.start()
        return
    }

    playnow("hello")

How can a filename be passed as a parameter to android MediaPlayer ?

Body:
take a look at the getIdentifier method it returns a resource identifier for the given resource name.

fun playnow (sndfil: String) {
    val resourceIdentifier = resources.getIdentifier(sndfil, "raw", packageName)
    mp = MediaPlayer.create(this,resourceIdentifier)
    mp.start()
    return
}

playnow("hello")


问:
Java: NullPointerException from class.getResource( ... )
I was writing a small application and when I tried to create an ImageIcon I always got an exception. The exception was caused by this line of code:

```<code>prayerLevel.setIcon(new ImageIcon(getClass().getResource("/icons/icon_prayer.png")));
</code>```

Now within my program, the folder /icons/ does exist. I don't know if it makes the difference but the class file is within a package, where as the icons folder is within the project folder (when you would see the bin and src folder).

I have looked around for a bit and I couldn't find a solution that could help me solve the problem. Perhaps any of you guys could help?

Edit: someone asked for my folder hierarchy:

I know the class file is not in the same folder as the icons are, but I've made applications where I had to load files from a different folder and doing /folder/ always used to work.

Edit 2:

```<code>System.out.println(getClass().getResource("/icons/icon_prayer.png") == null);
</code>```

Prints true.

答:
I believe the NPE is being thrown from the ImageIcon constructor as getResource is returning null.

Try the following:

```<code>getClass().getClassLoader().getResource("/icons/icon_prayer.png")
</code>```

Or:

```<code>ClassLoader.getSystemResource("/icons/icon_prayer.png")
</code>```

Body:
I was writing a small application and when I tried to create an ImageIcon I always got an exception. The exception was caused by this line of code:

prayerLevel.setIcon(new ImageIcon(getClass().getResource("/icons/icon_prayer.png")));

Now within my program, the folder /icons/ does exist. I don't know if it makes the difference but the class file is within a package, where as the icons folder is within the project folder (when you would see the bin and src folder).

I have looked around for a bit and I couldn't find a solution that could help me solve the problem. Perhaps any of you guys could help?

Edit: someone asked for my folder hierarchy:

I know the class file is not in the same folder as the icons are, but I've made applications where I had to load files from a different folder and doing /folder/ always used to work.

Edit 2:

System.out.println(getClass().getResource("/icons/icon_prayer.png") == null);

Prints true.

Body:
I believe the NPE is being thrown from the ImageIcon constructor as getResource is returning null.

Try the following:

getClass().getClassLoader().getResource("/icons/icon_prayer.png")

Or:

ClassLoader.getSystemResource("/icons/icon_prayer.png")


问:
How can I update this state without mutating the array?
I want to know how to not mutate state in the following scenario:

I'm using React Hooks. I have a TodoList that lists TodoItems. TodoItems can be clicked to run a function called toggle which toggles their completed property.

```<code>import React, { useState } from "react";
import TodoItem from "./TodoItem";

export default function TodoList() {
  const [todos, setTodos] = useState([
    { text: "Example", completed: false }
  ]);

  const toggle = index => {
    const newTodos = [...todos];
    newTodos[index].completed = !newTodos[index].completed; // Mutating state?
    setTodos(newTodos);
  };

  return (
    <>
      {todos.map((item, index) => (
        <TodoItem key={index} index={index} todo={item} toggle={toggle} />
      ))}
    </>
  );
}
</code>```

I was told that this was mutating state:

You create a copy of the todos array, but you still mutate an item inside the array:

newTodos[index].completed = !newTodos[index].completed;
```

  <p>Spreading the array only creates a shallow copy of the array, but the original todo object is not copied and thus mutated.</p>
</blockquote>

<p>So, what is the correct way to handle this without mutating state? I've tried passing in a <code>prevTodos</code> param, but then the state doesn't update:</p>

```const toggle = index => {
  setTodos(prevTodos => {
    prevTodos[index].completed = !prevTodos[index].completed;
    return prevTodos;
  });
};
```

<p><strong>Update:</strong> I've taken a look at the posts you've all recommended. This is a solution, although I'm wondering if there's a cleaner way to express it:</p>

```const toggle = index => {
  setTodos(
    todos.map((todo, i) =>
      i === index ? { ...todo, completed: !todo.completed } : todo
    )
  );
};
```

Update 2: Thanks everyone. I posted the solution below. StackOverflow won't let me accept it for 2 days, but I'll do it then. The accepted answer on the suggested post suggests the use of a third-party library, and it doesn't use React Hooks, so I don't consider this question a duplicate.

答:
Found a solution. map will return a different array, and you can listen to the index parameter (in my snippet below, this is i) to listen to the current index and change the object you're targeting.

```<code>const toggle = index => {
  setTodos(
    todos.map((todo, i) =>
      i === index ? { ...todo, completed: !todo.completed } : todo
    )
  );
};
</code>```

These threads helped me piece this together:

Why is the state mutating if I am using spread operator?

Whats the best way to update an object in an array in ReactJS?

Thanks to everyone that helped.

Body:
I want to know how to not mutate state in the following scenario:

I'm using React Hooks. I have a TodoList that lists TodoItems. TodoItems can be clicked to run a function called toggle which toggles their completed property.

import React, { useState } from "react";
import TodoItem from "./TodoItem";

export default function TodoList() {
  const [todos, setTodos] = useState([
    { text: "Example", completed: false }
  ]);

  const toggle = index => {
    const newTodos = [...todos];
    newTodos[index].completed = !newTodos[index].completed; // Mutating state?
    setTodos(newTodos);
  };

  return (
    <>
      {todos.map((item, index) => (
        <TodoItem key={index} index={index} todo={item} toggle={toggle} />
      ))}
    </>
  );
}

I was told that this was mutating state:

You create a copy of the todos array, but you still mutate an item inside the array:

newTodos[index].completed = !newTodos[index].completed;

Spreading the array only creates a shallow copy of the array, but the original todo object is not copied and thus mutated.

So, what is the correct way to handle this without mutating state? I've tried passing in a prevTodos param, but then the state doesn't update:

const toggle = index => {
  setTodos(prevTodos => {
    prevTodos[index].completed = !prevTodos[index].completed;
    return prevTodos;
  });
};

Update: I've taken a look at the posts you've all recommended. This is a solution, although I'm wondering if there's a cleaner way to express it:

const toggle = index => {
  setTodos(
    todos.map((todo, i) =>
      i === index ? { ...todo, completed: !todo.completed } : todo
    )
  );
};

Update 2: Thanks everyone. I posted the solution below. StackOverflow won't let me accept it for 2 days, but I'll do it then. The accepted answer on the suggested post suggests the use of a third-party library, and it doesn't use React Hooks, so I don't consider this question a duplicate.

Body:
Found a solution. map will return a different array, and you can listen to the index parameter (in my snippet below, this is i) to listen to the current index and change the object you're targeting.

const toggle = index => {
  setTodos(
    todos.map((todo, i) =>
      i === index ? { ...todo, completed: !todo.completed } : todo
    )
  );
};

These threads helped me piece this together:

Why is the state mutating if I am using spread operator?

Whats the best way to update an object in an array in ReactJS?

Thanks to everyone that helped.


问:
How to draw vertical lines as a music track progressbar using Canvas in Javascript
I am trying to build a custom audio player. I am using HtmlAudioElement for that. I have managed to do play, pause, display duration and all but i have stuck where i need to show a progress bar when playing a track. I have percentage value( How much song already played ) which is updating every millisecond. I was wondering using that percentages value can i use canvas and draw vertical lines as percentage increases?

So this is how progress bar should change color as percentage increases.  I have no idea where to start. I am very new to Canvas. Any Help ?

I have tried this so far. ( This is not what i want) .

```<code>const canvas = document.getElementById('progress');
canvas.width = 1920;
canvas.height = 100;
const ctx = canvas.getContext('2d');

ctx.fillStyle = 'grey';

for(let i = 0; i < 1000; i+=10){
    console.log(i);
    ctx.fillRect(i,0,5,100);
}

let count = 0;
let percent = 0;
ctx.fillStyle = 'orange';

function draw(){
    console.log('Hello')
    ctx.fillRect(count,0,5,100);
    count+=10;
    if(count > 100/1){
        return;
    }
    window.requestAnimationFrame(draw);
}

draw();
</code>```

So this what it looks right now.

I want as playing percentage changes i need to hook that value somewhere in Canvas so i can draw those lines.

Thanks in advance :)

答:
You can read the value (% done) directly from the media object that holds it.

I can not workout what it is you are having trouble with. you mention color the following is a simple color changing bar.

Basic progress bar

Some constants to define the progress bar

```<code>const width = 500;
const height = 20;
const startColor = {r: 255, g: 128, b: 0}; // unsigned byte values 0 - 255
const endColor = {r: 255, g: 128, b: 0};
</code>```

To interpolate the color

```<code>function progressColor(start, end, progress) {
    const r = (end.r - start.r) * progress + start.r;
    const g = (end.g - start.g) * progress + start.g;
    const b = (end.b - start.b) * progress + start.b;
    return `rgb(${r | 0},${g |0 }, ${b | 0})`;
}
</code>```

To draw the bar

```<code>function progressBar(progress) {
    ctx.fillStyle =  progressColor(startColor, endColor, progress);
    // whatever design you want the example is just a simple bar

    ctx.fillRect(0,0, width * progress, height);
}
</code>```

The main loop

The main loop every 60th second.

If the audio is paused it stops.

Care must be taken when starting the animation loop not to start it more than once

Note that the audio will have stopped up to ~1/60th second before the last animation frame is rendered.

The main animation loop...

```<code>var progressAnimating = false;  // this is to avoid more that one mainLoop playing
function mainLoop() {
    ctx.clearRect(0,0,width,height);

    // draw backing bar here

    const fractionDone = audio.time / audio.duration;
    progressBar(fractionDone);

    // only while not paused
    if (!audio.paused) {
        requestAnimationFrame(mainLoop);
    } else {
        progressAnimating = false;  // flag that the animation has stopped
    }
}
</code>```

Use Audio events to start animation

Use the audio play event to start the animation.

Check to make sure that the animation is not playing before you request the first frame.

If the animation is still active then it will continue by its self

.

```<code>audio.addEventListener("play",() => {
    if (!progressAnimating) {
        requestAnimationFrame(mainLoop);
        progressAnimating = true;
    }
});
</code>```

Styling the progress bar

The next function replaces the solid bar from above.
It uses the clip area to limit the width so you dont need to fiddle with fractional bars.

```<code>const barWidth = 4; // in px
const barSpacing = 8; // distance from left edge to next left edge in px

function progressBar(progress) {
    ctx.save(); // save the unclipped state

    ctx.beginPath(); // create the clip path
    ctx.rect(0,0, width * progress, height);
    ctx.clip();

    ctx.fillStyle =  progressColor(startColor, endColor, progress);

    ctx.beginPath(); // draw all bars as one
    var x = 0;
    while (x < width * progress) {
        ctx.rect(x, 0, barWidth, height);
        x += barSpacing;
    }
    ctx.fill(); // draw that bars

    ctx.restore(); // restore unclipped state
}
</code>```

Body:
I am trying to build a custom audio player. I am using HtmlAudioElement for that. I have managed to do play, pause, display duration and all but i have stuck where i need to show a progress bar when playing a track. I have percentage value( How much song already played ) which is updating every millisecond. I was wondering using that percentages value can i use canvas and draw vertical lines as percentage increases?

So this is how progress bar should change color as percentage increases.  I have no idea where to start. I am very new to Canvas. Any Help ?

I have tried this so far. ( This is not what i want) .

const canvas = document.getElementById('progress');
canvas.width = 1920;
canvas.height = 100;
const ctx = canvas.getContext('2d');

ctx.fillStyle = 'grey';

for(let i = 0; i < 1000; i+=10){
    console.log(i);
    ctx.fillRect(i,0,5,100);
}

let count = 0;
let percent = 0;
ctx.fillStyle = 'orange';

function draw(){
    console.log('Hello')
    ctx.fillRect(count,0,5,100);
    count+=10;
    if(count > 100/1){
        return;
    }
    window.requestAnimationFrame(draw);
}

draw();

So this what it looks right now.

I want as playing percentage changes i need to hook that value somewhere in Canvas so i can draw those lines.

Thanks in advance :)

Body:
You can read the value (% done) directly from the media object that holds it.

I can not workout what it is you are having trouble with. you mention color the following is a simple color changing bar.

Basic progress bar

Some constants to define the progress bar

const width = 500;
const height = 20;
const startColor = {r: 255, g: 128, b: 0}; // unsigned byte values 0 - 255
const endColor = {r: 255, g: 128, b: 0};

To interpolate the color

function progressColor(start, end, progress) {
    const r = (end.r - start.r) * progress + start.r;
    const g = (end.g - start.g) * progress + start.g;
    const b = (end.b - start.b) * progress + start.b;
    return `rgb(${r | 0},${g |0 }, ${b | 0})`;
}

To draw the bar

function progressBar(progress) {
    ctx.fillStyle =  progressColor(startColor, endColor, progress);
    // whatever design you want the example is just a simple bar

    ctx.fillRect(0,0, width * progress, height);
}

The main loop

The main loop every 60th second.

If the audio is paused it stops.

Care must be taken when starting the animation loop not to start it more than once

Note that the audio will have stopped up to ~1/60th second before the last animation frame is rendered.

The main animation loop...

var progressAnimating = false;  // this is to avoid more that one mainLoop playing
function mainLoop() {
    ctx.clearRect(0,0,width,height);

    // draw backing bar here

    const fractionDone = audio.time / audio.duration;
    progressBar(fractionDone);

    // only while not paused
    if (!audio.paused) {
        requestAnimationFrame(mainLoop);
    } else {
        progressAnimating = false;  // flag that the animation has stopped
    }
}

Use Audio events to start animation

Use the audio play event to start the animation.

Check to make sure that the animation is not playing before you request the first frame.

If the animation is still active then it will continue by its self

.

audio.addEventListener("play",() => {
    if (!progressAnimating) {
        requestAnimationFrame(mainLoop);
        progressAnimating = true;
    }
});

Styling the progress bar

The next function replaces the solid bar from above.
It uses the clip area to limit the width so you dont need to fiddle with fractional bars.

const barWidth = 4; // in px
const barSpacing = 8; // distance from left edge to next left edge in px

function progressBar(progress) {
    ctx.save(); // save the unclipped state

    ctx.beginPath(); // create the clip path
    ctx.rect(0,0, width * progress, height);
    ctx.clip();

    ctx.fillStyle =  progressColor(startColor, endColor, progress);

    ctx.beginPath(); // draw all bars as one
    var x = 0;
    while (x < width * progress) {
        ctx.rect(x, 0, barWidth, height);
        x += barSpacing;
    }
    ctx.fill(); // draw that bars

    ctx.restore(); // restore unclipped state
}


问:
What does double colon in laravel means
Example :

```<code>Auth::guard($guard)->guest()
</code>```

I dont get what double colon (::) notation means in laravel framework. from http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php I learn that it stand for scope resolution operator to access static, constant and overridden properties or methods of a class. but from laravel I learn that Auth means the alias for class facade so I need an explanation of the example above especially guard(parameter)->guest() means.

I'm still new to php and now learning laravel framework for my back-end.

答:
Basically its know as

```<code>Scope resolution operator (::)
</code>```

Simply it is token which allow access to static, constant and overridden properties of method of a class

Example- in laravel we call model like this

User::select('name')->get()->toArray();

Title: What does double colon in laravel means

Body:
Example :

Auth::guard($guard)->guest()

I dont get what double colon (::) notation means in laravel framework. from http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php I learn that it stand for scope resolution operator to access static, constant and overridden properties or methods of a class. but from laravel I learn that Auth means the alias for class facade so I need an explanation of the example above especially guard(parameter)->guest() means.

I'm still new to php and now learning laravel framework for my back-end.

Body:
Basically its know as

Scope resolution operator (::)

Simply it is token which allow access to static, constant and overridden properties of method of a class

Example- in laravel we call model like this

User::select('name')->get()->toArray();


问:
ArrayList IndexOfBound exceptions when to get data from firestore database, why?
i have a Recycler View which is filled with 2 arraylist, the first is the card view title, and the second its content, the problem happens in the second arraylist, which receives data from the firestore, for example.

Below is the code for how I fill the arraylist of data I receive from the local cloud and strings.

        valorCard.add(0, "R$: 16.402,98"); // must be added on first position

        DocumentReference dbRef = db.collection("Usuarios").document(firebaseAuth.getCurrentUser().getUid().toString());
        dbRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>(){
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                valorCard.add(1, documentSnapshot.get("quantBois").toString()); // must be added on second position
            }
        });
        valorCard.add(2,"25.000,00$"); // must be added on thrid position
        valorCard.add(3,"25/05/2020"); // must be added on fourth position

```

<p>When the code is runned, this is returned:</p>

```E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.agrolucros2019, PID: 29318
    java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
        at java.util.ArrayList.add(ArrayList.java:483)
        at com.example.agrolucros2019.fragmentos.home.HomeFragment.onCreateView(HomeFragment.java:65)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
        at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManagerImpl.java:2100)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1874)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1830)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
        at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)
        at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
        at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2624)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:904)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
        at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2659)
        at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1395)
        at android.app.Activity.performStart(Activity.java:7361)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3150)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1960)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7094)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
```

I believe this is due to the fact that a request for data in the cloud takes some time to receive the data, and as I need to insert the data exactly in the second (1) position, this causes a delay that causes the 0 jump for 2 (since 1 has not yet been filled in) go wrong.

答: This cause of my problem is a method "add" from ArrayList, this method overwrite the oldest value of position and "put" to the next address, the solution was to use the Set method, so, then were "valorCard.add" i'm overwrite to valorCard.set.

Body:
i have a Recycler View which is filled with 2 arraylist, the first is the card view title, and the second its content, the problem happens in the second arraylist, which receives data from the firestore, for example.

Below is the code for how I fill the arraylist of data I receive from the local cloud and strings.

        valorCard.add(0, "R$: 16.402,98"); // must be added on first position

        DocumentReference dbRef = db.collection("Usuarios").document(firebaseAuth.getCurrentUser().getUid().toString());
        dbRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>(){
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                valorCard.add(1, documentSnapshot.get("quantBois").toString()); // must be added on second position
            }
        });
        valorCard.add(2,"25.000,00$"); // must be added on thrid position
        valorCard.add(3,"25/05/2020"); // must be added on fourth position

When the code is runned, this is returned:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.agrolucros2019, PID: 29318
    java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
        at java.util.ArrayList.add(ArrayList.java:483)
        at com.example.agrolucros2019.fragmentos.home.HomeFragment.onCreateView(HomeFragment.java:65)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
        at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManagerImpl.java:2100)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1874)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1830)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
        at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)
        at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
        at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2624)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:904)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
        at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2659)
        at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1395)
        at android.app.Activity.performStart(Activity.java:7361)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3150)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1960)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7094)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)

I believe this is due to the fact that a request for data in the cloud takes some time to receive the data, and as I need to insert the data exactly in the second (1) position, this causes a delay that causes the 0 jump for 2 (since 1 has not yet been filled in) go wrong.


问:
Why doesn't my root view's height take account of its navigation bar?
I was under the impression that a UINavigationController's navigation bar would always push down the child view's height, such that the child view's origin was at the bottom of the title bar.

But when I present a view controller like this ...

```<code>MyViewController *viewController = [[MyViewController alloc] init];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
viewController.title = @"My View Controller";
viewController.navigationItem.prompt = @"My Prompt";
viewController.delegate = self;

[self presentModalViewController:navigationController animated:YES];
[navigationController release]; [viewController release];
</code>```

... and then check self.view.frame.size.height with an NSLog in viewDidLoad, it reports that my view is 460px high. Shouldn't it subtracting the height of my title & prompt?

答:
So, as requested:

When you call viewDidLoad the view controller hasn't been pushed onto the screen yet. So when you get the frame size from within that method it will report its' default (typically, 320x480 for an iPhone app).

The view then autoresizes to take into account the navigation bar. So when you check the frame size in viewWillAppear it will now be correct. Typically this isn't a problem for iPhone apps. For iPad apps, where you have multiple orientations, it can be a bit of a pain!

There are a few exceptions to this - for example, when using NIBs.

Body:
I was under the impression that a UINavigationController's navigation bar would always push down the child view's height, such that the child view's origin was at the bottom of the title bar.

But when I present a view controller like this ...

MyViewController *viewController = [[MyViewController alloc] init];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
viewController.title = @"My View Controller";
viewController.navigationItem.prompt = @"My Prompt";
viewController.delegate = self;

[self presentModalViewController:navigationController animated:YES];
[navigationController release]; [viewController release];

... and then check self.view.frame.size.height with an NSLog in viewDidLoad, it reports that my view is 460px high. Shouldn't it subtracting the height of my title & prompt?


问:
Laravel Rule Validation Check Databse Not Working
this is my code:

```<code>  $id_project = $request->id;
  $rfid       = $request->rfid;

  $validateData = $request->validate([
                    'name'      => 'required|string|max:255',
                    'rfid'      => 'required|min:40',[
                                    Rule::exists('usersdata')->where(function($query) use ($id_project,$rfid){
                                       $query->where('id_project', $id_project)->where('rfid', $rfid);
                                    }),
                    ],
                    'description'   => 'string|max:255|nullable',
                ]);

   $user = UserModel::create($validateData);
   return Response()->json(['success' => 'success insert data'], 200);
</code>```

Validation for RFID (required or Min 40 char) its working.

but if i'm insert with same id_project and same RFID data that's not working.
whereas in my database have already have id_project and rfid.

keep successful inserting data.

答:
You have syntax fault on your code, compare your code with this corrected one:

$validateData = $request->validate([
    'name'      => 'required|string|max:255',
    'rfid'      => [
                       'required',
                       'min:40',
                       Rule::unique('usersdata', 'rfid')
                           ->where('id_project', $id_project)
                   ],
    'description'   => 'string|max:255|nullable',
]);
```

Body:
this is my code:

  $id_project = $request->id;
  $rfid       = $request->rfid;

  $validateData = $request->validate([
                    'name'      => 'required|string|max:255',
                    'rfid'      => 'required|min:40',[
                                    Rule::exists('usersdata')->where(function($query) use ($id_project,$rfid){
                                       $query->where('id_project', $id_project)->where('rfid', $rfid);
                                    }),
                    ],
                    'description'   => 'string|max:255|nullable',
                ]);

   $user = UserModel::create($validateData);
   return Response()->json(['success' => 'success insert data'], 200);

Validation for RFID (required or Min 40 char) its working.

but if i'm insert with same id_project and same RFID data that's not working.
whereas in my database have already have id_project and rfid.

keep successful inserting data.


问:
How to improve BSIS reading inside dynamic itab loop?
I have a code as below, which takes more than 200 minutes to execute, could you help me to improve the performance.

This code is triggered at User Command. Say users select all records (about 300K records) at first level output for next level drill down report:

The dynamic internal table <OI_TABLE> has around 300K records with a field component called BOX marked as 'X' for those selected lines by the user.

The program reads the selected lines from the dynamic internal table (<OI_TABLE>), compare them to another standard internal table (GT_BSIS) which has around 300K records, whose clearing key value should be the same for both internal tables (1:N cardinality).

It then inserts those common records to the third standard internal table (GT_L2_DISP) for further processing/display.

Code:

```<code>LOOP AT <oi_table> ASSIGNING <oi_line>.
  ASSIGN COMPONENT 'BOX' OF STRUCTURE <oi_line> TO <oi_field>.
  IF <oi_field> = 'X'.
    ASSIGN COMPONENT 'CLEARING_KEY' OF STRUCTURE <oi_line> TO <oi_field>.
    LOOP AT gt_bsis WHERE clearing_key = <oi_field>.
      MOVE-CORRESPONDING gt_bsis TO gt_l2_disp.
      APPEND gt_l2_disp.
    ENDLOOP.
  ENDIF.
ENDLOOP.
</code>```

Here, <oi_table> contains data for first level ALV output and GT_BSIS would contain data for 2nd level ALV output.

My understanding :

If we can fill up standard internal table GT_BSIS and marking/passing 'X' to a column (say FLAG) in GT_BSIS, while user is selecting rows from ALV first level output, it would help in performance as ONE LOOP .. ENDLOOP could be avoided.

An indexed internal table may also be an option. Please suggest a way to improve the performance.

NB: our SAP System is ECC, ABAP 7.31, so please do not propose inline code/declaration.

答:
@Zero, Thank you so much Zero for your Response and Valued Feedback, Appreciate, I have done it and here is the Code Below, which I have used. Performance/Runtime is Reduced Drastically from 210 Minutes to well Below 5 Minutes for about 340K Records for Both those Internal Tables,

```<code>DATA: git_ibsis TYPE HASHED TABLE OF modbsis_layout1
                     WITH UNIQUE KEY clearing_key belnr buzei,
      gwa_ibsis LIKE LINE OF git_ibsis.

FIELD-SYMBOLS : <gfs_ibsis>     LIKE LINE OF git_ibsis.

DATA : lv_clkey(12)   TYPE c,
       lv_box(3)      TYPE c.

       lv_clkey = 'CLEARING_KEY'.
       lv_box   = 'BOX'.

         SORT : ibsis BY clearing_key belnr buzei,
                <oi_table> BY ('BOX') ('CLEARING_KEY').

         LOOP AT ibsis.
           MOVE-CORRESPONDING ibsis TO gwa_ibsis.
           INSERT gwa_ibsis INTO TABLE git_ibsis.
           CLEAR : gwa_ibsis, ibsis.
         ENDLOOP.

         SORT : git_ibsis BY clearing_key belnr buzei.

         LOOP AT git_ibsis ASSIGNING <gfs_ibsis>.
           READ TABLE <oi_table> ASSIGNING <oi_line> WITH KEY
                      (lv_box)   = gc_x
                      (lv_clkey) = <gfs_ibsis>-clearing_key BINARY SEARCH.
           IF sy-subrc = 0.
             MOVE-CORRESPONDING <gfs_ibsis> TO zvxl100.
             APPEND zvxl100.
           ENDIF.
         ENDLOOP.
</code>```

Note : Used Hashed Internal Table,

Performance / Runtime is Reduced from 210 Minutes to Well Below 5 Minutes,

Body:
I have a code as below, which takes more than 200 minutes to execute, could you help me to improve the performance.

This code is triggered at User Command. Say users select all records (about 300K records) at first level output for next level drill down report:

The dynamic internal table <OI_TABLE> has around 300K records with a field component called BOX marked as 'X' for those selected lines by the user.

The program reads the selected lines from the dynamic internal table (<OI_TABLE>), compare them to another standard internal table (GT_BSIS) which has around 300K records, whose clearing key value should be the same for both internal tables (1:N cardinality).

It then inserts those common records to the third standard internal table (GT_L2_DISP) for further processing/display.

Code:

LOOP AT <oi_table> ASSIGNING <oi_line>.
  ASSIGN COMPONENT 'BOX' OF STRUCTURE <oi_line> TO <oi_field>.
  IF <oi_field> = 'X'.
    ASSIGN COMPONENT 'CLEARING_KEY' OF STRUCTURE <oi_line> TO <oi_field>.
    LOOP AT gt_bsis WHERE clearing_key = <oi_field>.
      MOVE-CORRESPONDING gt_bsis TO gt_l2_disp.
      APPEND gt_l2_disp.
    ENDLOOP.
  ENDIF.
ENDLOOP.

Here, <oi_table> contains data for first level ALV output and GT_BSIS would contain data for 2nd level ALV output.

My understanding :

If we can fill up standard internal table GT_BSIS and marking/passing 'X' to a column (say FLAG) in GT_BSIS, while user is selecting rows from ALV first level output, it would help in performance as ONE LOOP .. ENDLOOP could be avoided.

An indexed internal table may also be an option. Please suggest a way to improve the performance.

NB: our SAP System is ECC, ABAP 7.31, so please do not propose inline code/declaration.

Body:
@Zero, Thank you so much Zero for your Response and Valued Feedback, Appreciate, I have done it and here is the Code Below, which I have used. Performance/Runtime is Reduced Drastically from 210 Minutes to well Below 5 Minutes for about 340K Records for Both those Internal Tables,

DATA: git_ibsis TYPE HASHED TABLE OF modbsis_layout1
                     WITH UNIQUE KEY clearing_key belnr buzei,
      gwa_ibsis LIKE LINE OF git_ibsis.

FIELD-SYMBOLS : <gfs_ibsis>     LIKE LINE OF git_ibsis.

DATA : lv_clkey(12)   TYPE c,
       lv_box(3)      TYPE c.

       lv_clkey = 'CLEARING_KEY'.
       lv_box   = 'BOX'.

         SORT : ibsis BY clearing_key belnr buzei,
                <oi_table> BY ('BOX') ('CLEARING_KEY').

         LOOP AT ibsis.
           MOVE-CORRESPONDING ibsis TO gwa_ibsis.
           INSERT gwa_ibsis INTO TABLE git_ibsis.
           CLEAR : gwa_ibsis, ibsis.
         ENDLOOP.

         SORT : git_ibsis BY clearing_key belnr buzei.

         LOOP AT git_ibsis ASSIGNING <gfs_ibsis>.
           READ TABLE <oi_table> ASSIGNING <oi_line> WITH KEY
                      (lv_box)   = gc_x
                      (lv_clkey) = <gfs_ibsis>-clearing_key BINARY SEARCH.
           IF sy-subrc = 0.
             MOVE-CORRESPONDING <gfs_ibsis> TO zvxl100.
             APPEND zvxl100.
           ENDIF.
         ENDLOOP.

Note : Used Hashed Internal Table,

Performance / Runtime is Reduced from 210 Minutes to Well Below 5 Minutes,