问:
DB2 service does not start
I have installed DB2 Developer Edition on a Windows 10 machine. The DB2 instance is set to start as a service. When I attempt to start the service, I get the following error:

When I open db2diag.log, I can see these "Severe" errors:

```<code>2020-02-19-09.02.15.388000+060 I4802F420            LEVEL: Severe
PID     : 13992                TID : 6588           PROC : db2syscs.exe
INSTANCE: DB2                  NODE : 000
HOSTNAME: Honza
EDUID   : 6588                 EDUNAME: db2sysc
FUNCTION: DB2 UDB, base sys utilities, sqlePreInitSysCtlr, probe:4491
MESSAGE : ZRC=0x870F00C8=-2029059896=SQLO_UNKCPCC
          "unknown code page, or country code."

2020-02-19-09.02.15.389000+060 I5224F569            LEVEL: Severe
PID     : 13992                TID : 6588           PROC : db2syscs.exe
INSTANCE: DB2                  NODE : 000
HOSTNAME: Honza
EDUID   : 6588                 EDUNAME: db2sysc
FUNCTION: DB2 UDB, base sys utilities, sqlePreInitSysCtlr, probe:4675
MESSAGE : ZRC=0x870F00C8=-2029059896=SQLO_UNKCPCC
          "unknown code page, or country code."
DATA #1 : String, 17 bytes
syscState.preInit
DATA #2 : Hexdump, 8 bytes
0x0000004C0BDFF828 : 8100 0038 0800 0000                        ...8....

2020-02-19-09.02.15.390000+060 I5795F413            LEVEL: Severe
PID     : 13992                TID : 6588           PROC : db2syscs.exe
INSTANCE: DB2                  NODE : 000
HOSTNAME: Honza
EDUID   : 6588                 EDUNAME: db2sysc
FUNCTION: DB2 UDB, base sys utilities, sqleSysCtlr, probe:3496
MESSAGE : ZRC=0x870F00C8=-2029059896=SQLO_UNKCPCC
          "unknown code page, or country code."

2020-02-19-09.02.15.491000+060 I6210F499            LEVEL: Severe
PID     : 13992                TID : 6588           PROC : db2syscs.exe
INSTANCE: DB2                  NODE : 000
HOSTNAME: Honza
EDUID   : 6588                 EDUNAME: db2sysc
FUNCTION: DB2 UDB, base sys utilities, sqleSysCtlr, probe:3948
MESSAGE : ZRC=0x870F00C8=-2029059896=SQLO_UNKCPCC
          "unknown code page, or country code."
DATA #1 : <preformatted>
System Controller is exiting with RC =-2029059896, Erorr=0
</code>```

Apparently, there is some problem with the DB2 code page / country code settings. Windows Event Viewer does not shed light on this - there are only errors indicating Windows could not start the DB2 service because the service terminated unexpectedly.

I tried to install DB2 Express edition and it exhibits the same problem.

答:
Answering my own question. The problem was in checked "Beta: Use Unicode UTF-8 for worldwide language support" checkbox in Windows Administrative language settings (Control Panel > Region > Administrative > Change System Locale > Beta: Use Unicode UTF-8 for worldwide language support.).

If you experience "unknown code page, or country code." issue with DB2, make sure the checkbox is unchecked.

Windows 10 Administrative Language Settings:

Title: DB2 service does not start

Body:
I have installed DB2 Developer Edition on a Windows 10 machine. The DB2 instance is set to start as a service. When I attempt to start the service, I get the following error:

When I open db2diag.log, I can see these "Severe" errors:

2020-02-19-09.02.15.388000+060 I4802F420            LEVEL: Severe
PID     : 13992                TID : 6588           PROC : db2syscs.exe
INSTANCE: DB2                  NODE : 000
HOSTNAME: Honza
EDUID   : 6588                 EDUNAME: db2sysc
FUNCTION: DB2 UDB, base sys utilities, sqlePreInitSysCtlr, probe:4491
MESSAGE : ZRC=0x870F00C8=-2029059896=SQLO_UNKCPCC
          "unknown code page, or country code."

2020-02-19-09.02.15.389000+060 I5224F569            LEVEL: Severe
PID     : 13992                TID : 6588           PROC : db2syscs.exe
INSTANCE: DB2                  NODE : 000
HOSTNAME: Honza
EDUID   : 6588                 EDUNAME: db2sysc
FUNCTION: DB2 UDB, base sys utilities, sqlePreInitSysCtlr, probe:4675
MESSAGE : ZRC=0x870F00C8=-2029059896=SQLO_UNKCPCC
          "unknown code page, or country code."
DATA #1 : String, 17 bytes
syscState.preInit
DATA #2 : Hexdump, 8 bytes
0x0000004C0BDFF828 : 8100 0038 0800 0000                        ...8....

2020-02-19-09.02.15.390000+060 I5795F413            LEVEL: Severe
PID     : 13992                TID : 6588           PROC : db2syscs.exe
INSTANCE: DB2                  NODE : 000
HOSTNAME: Honza
EDUID   : 6588                 EDUNAME: db2sysc
FUNCTION: DB2 UDB, base sys utilities, sqleSysCtlr, probe:3496
MESSAGE : ZRC=0x870F00C8=-2029059896=SQLO_UNKCPCC
          "unknown code page, or country code."

2020-02-19-09.02.15.491000+060 I6210F499            LEVEL: Severe
PID     : 13992                TID : 6588           PROC : db2syscs.exe
INSTANCE: DB2                  NODE : 000
HOSTNAME: Honza
EDUID   : 6588                 EDUNAME: db2sysc
FUNCTION: DB2 UDB, base sys utilities, sqleSysCtlr, probe:3948
MESSAGE : ZRC=0x870F00C8=-2029059896=SQLO_UNKCPCC
          "unknown code page, or country code."
DATA #1 : <preformatted>
System Controller is exiting with RC =-2029059896, Erorr=0

Apparently, there is some problem with the DB2 code page / country code settings. Windows Event Viewer does not shed light on this - there are only errors indicating Windows could not start the DB2 service because the service terminated unexpectedly.

I tried to install DB2 Express edition and it exhibits the same problem.


来源: stackexchange

问:
How to make the if statement without repetition of code?
Following is the if statement that execute some part of the code before it checks some condition, it is working fine but it looks very basic and repeated lines.</p>

```<code>    if(allTasks[t].status === "Completed"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","completed");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Past Due"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","pastdue");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Duetoday"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","duetoday");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Onhold"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","onhold");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Canceled"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","canceled");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }
</code>```

答:
```<code>var statusList={
    'Completed':{
        'arrowClass':'arrow2',
        'tagClass':'completed'
    },
    'Past Due':{
        'arrowClass':'arrow2',
        'tagClass':'pastdue'
    }
}
</code>```

With this structure You can do something like this:

```<code>arrow.setAttribute("class",statusList[allTasks[t].status]["arrowClass"]);
tag.setAttribute("class",statusList[allTasks[t].status]["tagClass"]);
tag.innerHTML = allTasks[t].status;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Following is the if statement that execute some part of the code before it checks some condition, it is working fine but it looks very basic and repeated lines.

    if(allTasks[t].status === "Completed"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","completed");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Past Due"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","pastdue");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Duetoday"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","duetoday");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Onhold"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","onhold");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Canceled"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","canceled");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }

Body:
var statusList={
    'Completed':{
        'arrowClass':'arrow2',
        'tagClass':'completed'
    },
    'Past Due':{
        'arrowClass':'arrow2',
        'tagClass':'pastdue'
    }
}

With this structure You can do something like this:

arrow.setAttribute("class",statusList[allTasks[t].status]["arrowClass"]);
tag.setAttribute("class",statusList[allTasks[t].status]["tagClass"]);
tag.innerHTML = allTasks[t].status;


答:
```<code>updateTask(status, arrow, tag, taskCont) {
  arrow.setAttribute("class","arrow2");
  tag.setAttribute("class",status.toLowerCase());
  tag.innerHTML = allTasks[t].status;
  taskCont.appendChild(tag);
}

updateTask(allTasks[t].status, arrow, tag, taskCont)
</code>```

Notice the status.toLowerCase() bit.

If you want to tone down the fragility of this you can use an Enum to map the status to the correct corresponding tag attribute.

Hope this helps.

Title: How to make the if statement without repetition of code?

Body:
updateTask(status, arrow, tag, taskCont) {
  arrow.setAttribute("class","arrow2");
  tag.setAttribute("class",status.toLowerCase());
  tag.innerHTML = allTasks[t].status;
  taskCont.appendChild(tag);
}

updateTask(allTasks[t].status, arrow, tag, taskCont)

Notice the status.toLowerCase() bit.

If you want to tone down the fragility of this you can use an Enum to map the status to the correct corresponding tag attribute.

Hope this helps.


问:
Check a condition in the background every ten seconds and send notification
I'm working on an app for Mac OS X. My app checks something every ten seconds, and if the condition is true, the app sends a Growl notification.

I've already coded the Growl notifications and the checking. I just need to know how to make this checking repeat itself every ten seconds, and each time send a notification if true, all in the background.

Please write the exact code, as I am very new to Objective-C. Thank you :D

-------------------------------EDIT------------------------------------

Currently i'm using this:

```<code>//  MyApp_AppDelegate.m

#import "MyApp_AppDelegate.h"

@implementation MyApp_AppDelegate

- (void)awakeFromNib {
    return;
}

-(void)applicationDidFinishLaunching:(NSNotification*)aNotification {

    // grwol:
    NSBundle *myBundle = [NSBundle bundleForClass:[MyApp_AppDelegate class]];
    NSString *growlPath = [[myBundle privateFrameworksPath] stringByAppendingPathComponent:@"Growl-WithInstaller.framework"];
    NSBundle *growlBundle = [NSBundle bundleWithPath:growlPath];

    #include <unistd.h>

    int x = 0;
    int l = 10; // time/repeats
    int t = 10; //seconds
    while ( x <= l ) {

        // more code here only to determine sendgrowl value...

        if(sendgrowl) {
            if (growlBundle && [growlBundle load]) {
                // more code to sends growl
            } else {
                NSLog(@"ERROR: Could not load Growl.framework");
            }
        }

        // do other stuff that doesn't matter...

        // wait:
        sleep(t);

        x++;
    }
}

/* Dealloc method */
- (void) dealloc {
    [super dealloc];
}

@end
</code>```

答:
The exact code that you are looking for can be found here:
Time Programming Topics</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm working on an app for Mac OS X. My app checks something every ten seconds, and if the condition is true, the app sends a Growl notification.

I've already coded the Growl notifications and the checking. I just need to know how to make this checking repeat itself every ten seconds, and each time send a notification if true, all in the background.

Please write the exact code, as I am very new to Objective-C. Thank you :D

-------------------------------EDIT------------------------------------

Currently i'm using this:

//  MyApp_AppDelegate.m

#import "MyApp_AppDelegate.h"

@implementation MyApp_AppDelegate

- (void)awakeFromNib {
    return;
}

-(void)applicationDidFinishLaunching:(NSNotification*)aNotification {

    // grwol:
    NSBundle *myBundle = [NSBundle bundleForClass:[MyApp_AppDelegate class]];
    NSString *growlPath = [[myBundle privateFrameworksPath] stringByAppendingPathComponent:@"Growl-WithInstaller.framework"];
    NSBundle *growlBundle = [NSBundle bundleWithPath:growlPath];

    #include <unistd.h>

    int x = 0;
    int l = 10; // time/repeats
    int t = 10; //seconds
    while ( x <= l ) {

        // more code here only to determine sendgrowl value...

        if(sendgrowl) {
            if (growlBundle && [growlBundle load]) {
                // more code to sends growl
            } else {
                NSLog(@"ERROR: Could not load Growl.framework");
            }
        }

        // do other stuff that doesn't matter...

        // wait:
        sleep(t);

        x++;
    }
}

/* Dealloc method */
- (void) dealloc {
    [super dealloc];
}

@end


问:
Two date range return
How to return the two date combine string like below.

```<code>Start Date : 11/2/2020
End Date : 26/2/2020
</code>```

Then Output should be like this : 11 to 26 feb 2020

```<code>Start Date : 26/2/2020
End Date : 5/3/2020
</code>```

Then Output should be like this : 26 feb to 5 march 2020

```<code>Start Date : 29/12/2020
End Date : 2/1/2021
</code>```

Then Output should be like this : 29 Dec 2020 to 2 Jan 2021

Please Help me to solve this issue.

答:
One way to do this:

put your date parts into arrays - ['11', 'Feb', '2020']

loop over them in reverse order, from year to day

unset each entry in your start date array, that has the same value as the corresponding entry in your end date array - for as long as the current part matches; break out of the loop once the first mismatch occurs

join the parts that are left back together

```<code>function time_range_format($start, $end) {
  for($i=2; $i>=0; --$i) {
    if($end[$i] == $start[$i]) {
      unset($start[$i]);
    }
    else {
      break; // important to leave the loop, once the first non-matching part is encountered
    }
  }
  return ($start ? implode(' ', $start) . ' to ' : '') . implode(' ', $end);
}

var_dump(
  time_range_format(['11', 'Feb', '2020'], ['26', 'Feb', '2020']),
  time_range_format(['26', 'Feb', '2020'], ['5', 'Mar', '2020']),
  time_range_format(['29', 'Dec', '2020'], ['2', 'Jan', '2021']),
  time_range_format(['29', 'Dec', '2020'], ['29', 'Dec', '2020'])
);
</code>```

Results for above examples:

```<code>11 to 26 Feb 2020
26 Feb to 5 Mar 2020
29 Dec 2020 to 2 Jan 2021
29 Dec 2020
</code>```

By checking if $start still contains anything at the end, and only putting out the to if it does, you can even handle the “edge case” that start and end date are the same, as in the very last row of this example.

Title: Two date range return

Body:
How to return the two date combine string like below.

Start Date : 11/2/2020
End Date : 26/2/2020

Then Output should be like this : 11 to 26 feb 2020

Start Date : 26/2/2020
End Date : 5/3/2020

Then Output should be like this : 26 feb to 5 march 2020

Start Date : 29/12/2020
End Date : 2/1/2021

Then Output should be like this : 29 Dec 2020 to 2 Jan 2021

Please Help me to solve this issue.

Body:
One way to do this:

put your date parts into arrays - ['11', 'Feb', '2020']

loop over them in reverse order, from year to day

unset each entry in your start date array, that has the same value as the corresponding entry in your end date array - for as long as the current part matches; break out of the loop once the first mismatch occurs

join the parts that are left back together

function time_range_format($start, $end) {
  for($i=2; $i>=0; --$i) {
    if($end[$i] == $start[$i]) {
      unset($start[$i]);
    }
    else {
      break; // important to leave the loop, once the first non-matching part is encountered
    }
  }
  return ($start ? implode(' ', $start) . ' to ' : '') . implode(' ', $end);
}

var_dump(
  time_range_format(['11', 'Feb', '2020'], ['26', 'Feb', '2020']),
  time_range_format(['26', 'Feb', '2020'], ['5', 'Mar', '2020']),
  time_range_format(['29', 'Dec', '2020'], ['2', 'Jan', '2021']),
  time_range_format(['29', 'Dec', '2020'], ['29', 'Dec', '2020'])
);

Results for above examples:

11 to 26 Feb 2020
26 Feb to 5 Mar 2020
29 Dec 2020 to 2 Jan 2021
29 Dec 2020

By checking if $start still contains anything at the end, and only putting out the to if it does, you can even handle the “edge case” that start and end date are the same, as in the very last row of this example.


问:
What is the recommended way to log regularization losses for TensorBoard 2.1
I want to be able to monitor the evolution of the regularization losses of my model with TensorBoard (I'm using TensorFlow 2.1).

Until now, I've set up a tf.keras.callbacks.TensorBoard callback passed to tf.keras.Model.fit. It allows me to monitor the total loss and the learning rate:

The callback logs them by default.

However the total loss is composed of multiple terms (e.g. regularization losses). How can I easily monitor them?

The tf.keras.callbacks.TensorBoard doesn't seem to support this. Right?

I found this doc section: Logging custom scalars. However the example shows how to monitor a scalar at each epoch end while I'm looking for something which collect scalars at each batch end and log the mean at each epoch end.

I guess I can write a custom callback but can I avoid spending time on this?

Is there another solution?

Hence my question, what is the recommended way to log regularization losses for TensorBoard 2.1?

答:
You can create your own callback by inheriting from the TensorBoard callback and manually adding the desired quantities.

Here is the code I am using for that purpose. In this case, you would get a separate graph for the regularization losses of each layer.

class CustomTBCallback(keras.callbacks.TensorBoard):
    def _log_metrics(self, logs, prefix, step):
        for layer in self.model.layers:
            if layer.losses:
                logs["reg_%s" % layer.name] = tf.reduce_sum(layer.losses)
        super()._log_metrics(logs, prefix, step)
```

Unfortunately, this is somewhat hacky as it relies on the private _log_metrics function which may change between different versions of tensorflow. I have used this with tf 2.0.

Body:
You can create your own callback by inheriting from the TensorBoard callback and manually adding the desired quantities.

Here is the code I am using for that purpose. In this case, you would get a separate graph for the regularization losses of each layer.

class CustomTBCallback(keras.callbacks.TensorBoard):
    def _log_metrics(self, logs, prefix, step):
        for layer in self.model.layers:
            if layer.losses:
                logs["reg_%s" % layer.name] = tf.reduce_sum(layer.losses)
        super()._log_metrics(logs, prefix, step)

Unfortunately, this is somewhat hacky as it relies on the private _log_metrics function which may change between different versions of tensorflow. I have used this with tf 2.0.


问:
Why is my repositoryPath ignored in Azure DevOps / TFS?
First of all, I have a NuGet.Config:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <config>
    <add key="repositoryPath" value=".\ExternalReferences\Packages" />
      <solution>
        <add key="disableSourceControlIntegration" value="true" />
      </solution>
  </config>
</configuration>
</code>```

In the root of my dev branch. It's job is, that every project in my dev branch restores the packages into \dev\ExternalReferences\Packages, which works fine localy.

Im trying to introduce Azure Pipelines via TFS (VisualStudio Team Services/DevOps) for my CI-Build.

However, TFS is restoring the packages into the wrong folder \dev\packages (where \dev is D:\a\9\s\) instead of \dev\ExternalReferences\Packages.

```<code>Acquired lock for the installation of Newtonsoft.Json 12.0.3
Installing Newtonsoft.Json 12.0.3.
Adding package 'Microsoft.Extensions.Logging.Abstractions.2.2.0' to folder 'D:\a\9\s\packages'
</code>```

This breaks the build later (Which expects the ExternalReferences\Packages):

```<code>PrepareForBuild:
  Creating directory "bin\Release\".
  Creating directory "obj\Release\".
ResolveAssemblyReferences:
  Primary reference "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL".
##[warning]C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(2110,5): Warning MSB3245: Could not resolve this reference. Could not locate the assembly "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(2110,5): warning MSB3245: Could not resolve this reference. Could not locate the assembly "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors. [D:\a\9\s\Conwell.WebServices.Google\Conwell.WebServices.Google.csproj]
</code>```

Any Idea how to make NuGet to restore to the correct directory?

I just created a standard Pipeline for the project type Asp.NET

答:
Why is my repositoryPath ignored in Azure DevOps / TFS?

Since the nuget restore task restoring the packages into the wrong folder \dev\packages, it seems the settings repositoryPath in the NuGet.Config is ignored.

To resolve this issue, you could try to specify the nuget.config when you set the nuget restore task to make sure you have use the NuGet.Config:

Then my nuget.config looks like:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="AzureDevOpsFeed" value="https://pkgs.dev.azure.com/xxxn/_packaging/xxx/nuget/v3/index.json" />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
  </packageSources>

  <config>
    <add key="repositoryPath" value=".\ExternalReferences\Packages" />
  </config>

</configuration>
</code>```

Then, as test result, I could get the package in the folder ExternalReferences\Packages:

Hope this helps.

Body:
First of all, I have a NuGet.Config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <config>
    <add key="repositoryPath" value=".\ExternalReferences\Packages" />
      <solution>
        <add key="disableSourceControlIntegration" value="true" />
      </solution>
  </config>
</configuration>

In the root of my dev branch. It's job is, that every project in my dev branch restores the packages into \dev\ExternalReferences\Packages, which works fine localy.

Im trying to introduce Azure Pipelines via TFS (VisualStudio Team Services/DevOps) for my CI-Build.

However, TFS is restoring the packages into the wrong folder \dev\packages (where \dev is D:\a\9\s\) instead of \dev\ExternalReferences\Packages.

Acquired lock for the installation of Newtonsoft.Json 12.0.3
Installing Newtonsoft.Json 12.0.3.
Adding package 'Microsoft.Extensions.Logging.Abstractions.2.2.0' to folder 'D:\a\9\s\packages'

This breaks the build later (Which expects the ExternalReferences\Packages):

PrepareForBuild:
  Creating directory "bin\Release\".
  Creating directory "obj\Release\".
ResolveAssemblyReferences:
  Primary reference "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL".
##[warning]C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(2110,5): Warning MSB3245: Could not resolve this reference. Could not locate the assembly "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(2110,5): warning MSB3245: Could not resolve this reference. Could not locate the assembly "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors. [D:\a\9\s\Conwell.WebServices.Google\Conwell.WebServices.Google.csproj]

Any Idea how to make NuGet to restore to the correct directory?

I just created a standard Pipeline for the project type Asp.NET

Body:
Why is my repositoryPath ignored in Azure DevOps / TFS?

Since the nuget restore task restoring the packages into the wrong folder \dev\packages, it seems the settings repositoryPath in the NuGet.Config is ignored.

To resolve this issue, you could try to specify the nuget.config when you set the nuget restore task to make sure you have use the NuGet.Config:

Then my nuget.config looks like:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="AzureDevOpsFeed" value="https://pkgs.dev.azure.com/xxxn/_packaging/xxx/nuget/v3/index.json" />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
  </packageSources>

  <config>
    <add key="repositoryPath" value=".\ExternalReferences\Packages" />
  </config>

</configuration>

Then, as test result, I could get the package in the folder ExternalReferences\Packages:

Hope this helps.


问:
Navigation drawer crashes when isDrawerOpen is called
I am trying to implement a navigation drawer in android studio. All of the examples I find seem to be using a ListView, I would prefer a linearLayout.

The problem I am having is that when I call isDrawerOpen, my app crashes with "No drawer view found with gravity LEFT".

I have searched all day on Stack and Google but have not found anything that worked. I have tried:

```<code>navDrawerLayout.isDrawerOpen(Gravity.LEFT)
navDrawerLayout.isDrawerOpen(Gravity.RIGHT)
navDrawerLayout.isDrawerOpen(GravityCompat.START)
navDrawerLayout.isDrawerOpen(GravityCompat.END)
navDrawerLayout.isDrawerOpen(navLinearLayout)
android:gravity="left"
android:gravity="start"
android:gravity="left|start"
android:gravity="start|left"
android:gravity="right"
android:gravity="end"
android:gravity="right|end"
android:gravity="end|right"
</code>```

and every combination of the above, but nothing seems to work. What else could I be doing wrong to cause this crash?

MainActivity.java

```<code>import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;

public class MainActivity extends ActionBarActivity {

    private Toolbar toolbar;
    private DrawerLayout navDrawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    private LinearLayout navLinearLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        loadToolbar();
        loadNavigationDrawer();
    }

    private void loadNavigationDrawer() {
        navDrawerLayout = (DrawerLayout) findViewById(R.id.nav_drawer_layout);
        navLinearLayout = (LinearLayout) findViewById(R.id.nav_linear_layout);

        actionBarDrawerToggle = new ActionBarDrawerToggle(
                this,
                navDrawerLayout,
                toolbar,
                R.string.navigation_drawer_open,
                R.string.navigation_drawer_close
        ) {
            public void onDrawerClosed(View view){
                super.onDrawerClosed(view);
                invalidateOptionsMenu();
                syncState();
            }
            public void onDrawerOpened(View view){
                super.onDrawerOpened(view);
                invalidateOptionsMenu();
                syncState();
            }
        };
        navDrawerLayout.setDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();
    }

    private void loadToolbar(){
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        actionBarDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        actionBarDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                if (navDrawerLayout.isDrawerOpen(GravityCompat.START)){
                    //navDrawerLayout.closeDrawer(Gravity.LEFT);
                } else {
                    //navDrawerLayout.openDrawer(Gravity.LEFT);
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
       }
    }
}
</code>```

activity_main.xml

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/primary"
        app:theme="@style/ToolbarTheme"
        app:popupTheme="@style/Theme.AppCompat"/>

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/nav_drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <LinearLayout
            android:id="@+id/nav_linear_layout"
            android:background="@color/white"
            android:layout_width="@dimen/navigation_drawer_width"
            android:layout_height="match_parent"
            android:gravity="start"
            android:orientation="vertical" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Header"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Item 1" />

        </LinearLayout>

    </android.support.v4.widget.DrawerLayout>

</LinearLayout>
</code>```

The Error

```<code>java.lang.IllegalArgumentException: No drawer view found with gravity LEFT
        at android.support.v4.widget.DrawerLayout.openDrawer(DrawerLayout.java:1293)
        at android.support.v7.app.ActionBarDrawerToggle.toggle(ActionBarDrawerToggle.java:290)
        at android.support.v7.app.ActionBarDrawerToggle.access$100(ActionBarDrawerToggle.java:64)
        at android.support.v7.app.ActionBarDrawerToggle$1.onClick(ActionBarDrawerToggle.java:200)
        at android.view.View.performClick(View.java:4756)
        at android.view.View$PerformClick.run(View.java:19749)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
</code>```

答:
I solved it as below:</p>

```<code>if (drawerLayout.isDrawerOpen (drawerLayout.getChildAt(1)))
            drawerLayout.closeDrawer (drawerLayout.getChildAt(1));

else
            drawerLayout.openDrawer (drawerLayout.getChildAt(1));
</code>```

Body:
I am trying to implement a navigation drawer in android studio. All of the examples I find seem to be using a ListView, I would prefer a linearLayout.

The problem I am having is that when I call isDrawerOpen, my app crashes with "No drawer view found with gravity LEFT".

I have searched all day on Stack and Google but have not found anything that worked. I have tried:

navDrawerLayout.isDrawerOpen(Gravity.LEFT)
navDrawerLayout.isDrawerOpen(Gravity.RIGHT)
navDrawerLayout.isDrawerOpen(GravityCompat.START)
navDrawerLayout.isDrawerOpen(GravityCompat.END)
navDrawerLayout.isDrawerOpen(navLinearLayout)
android:gravity="left"
android:gravity="start"
android:gravity="left|start"
android:gravity="start|left"
android:gravity="right"
android:gravity="end"
android:gravity="right|end"
android:gravity="end|right"

and every combination of the above, but nothing seems to work. What else could I be doing wrong to cause this crash?

MainActivity.java

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;

public class MainActivity extends ActionBarActivity {

    private Toolbar toolbar;
    private DrawerLayout navDrawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    private LinearLayout navLinearLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        loadToolbar();
        loadNavigationDrawer();
    }

    private void loadNavigationDrawer() {
        navDrawerLayout = (DrawerLayout) findViewById(R.id.nav_drawer_layout);
        navLinearLayout = (LinearLayout) findViewById(R.id.nav_linear_layout);

        actionBarDrawerToggle = new ActionBarDrawerToggle(
                this,
                navDrawerLayout,
                toolbar,
                R.string.navigation_drawer_open,
                R.string.navigation_drawer_close
        ) {
            public void onDrawerClosed(View view){
                super.onDrawerClosed(view);
                invalidateOptionsMenu();
                syncState();
            }
            public void onDrawerOpened(View view){
                super.onDrawerOpened(view);
                invalidateOptionsMenu();
                syncState();
            }
        };
        navDrawerLayout.setDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();
    }

    private void loadToolbar(){
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        actionBarDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        actionBarDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                if (navDrawerLayout.isDrawerOpen(GravityCompat.START)){
                    //navDrawerLayout.closeDrawer(Gravity.LEFT);
                } else {
                    //navDrawerLayout.openDrawer(Gravity.LEFT);
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
       }
    }
}

activity_main.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/primary"
        app:theme="@style/ToolbarTheme"
        app:popupTheme="@style/Theme.AppCompat"/>

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/nav_drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <LinearLayout
            android:id="@+id/nav_linear_layout"
            android:background="@color/white"
            android:layout_width="@dimen/navigation_drawer_width"
            android:layout_height="match_parent"
            android:gravity="start"
            android:orientation="vertical" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Header"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Item 1" />

        </LinearLayout>

    </android.support.v4.widget.DrawerLayout>

</LinearLayout>

The Error

java.lang.IllegalArgumentException: No drawer view found with gravity LEFT
        at android.support.v4.widget.DrawerLayout.openDrawer(DrawerLayout.java:1293)
        at android.support.v7.app.ActionBarDrawerToggle.toggle(ActionBarDrawerToggle.java:290)
        at android.support.v7.app.ActionBarDrawerToggle.access$100(ActionBarDrawerToggle.java:64)
        at android.support.v7.app.ActionBarDrawerToggle$1.onClick(ActionBarDrawerToggle.java:200)
        at android.view.View.performClick(View.java:4756)
        at android.view.View$PerformClick.run(View.java:19749)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Body:
I solved it as below:

if (drawerLayout.isDrawerOpen (drawerLayout.getChildAt(1)))
            drawerLayout.closeDrawer (drawerLayout.getChildAt(1));

else
            drawerLayout.openDrawer (drawerLayout.getChildAt(1));


问:
Read file located in class library
I have a project containing just a class library. The project is later going to be used as a nuget package.

In the class library, I have a settings.json where I have my connectionString. But I don't know how to read the file?

I have tried to do like this:

```<code>public static class Injections
{
    public static IServiceCollection AddServiceAndRoleSecurity(this IServiceCollection services)
    {
        builder.AddJsonFile("settings.json");
        var Configuration = builder.Build();
    }
}
</code>```

The settings.json is in the same folder as the Injections.cs, but this don't work.

However, it works if I use the full path to the file:

```<code>public static class Injections
{
    public static IServiceCollection AddServiceAndRoleSecurity(this IServiceCollection services)
    {
        //Works
        builder.AddJsonFile(@"C:\Projects\classlibs\Security\Application\Configuration\settings.json");
        var Configuration = builder.Build();
    }
}
</code>```

But I don't want to use the full path.

答:
If your intent to add a separate settings.json file is to allow end user to update connectionstring, which willbe used in your class library(evantually NuGet package).

Then I'd suggest you to create a parameterized constructor/method in your class library, which takes connectionstring as a parameter from user.

This way user will have freedom to save connectionstring to wherever they want like web.config/app.config/hard-coded...

Example -

```<code>public MyNuGetPackage
{
    public MyNuGetPackage(string connectionString)
    {
        //use it wherever you want
    }

    -- OR --

    public SetConnectionString(string connectionString)
    {
        //use it wherever you want
    }

}
</code>```

Then, end user can use your package as -

```<code>var obj = new MyNuGetPackage(ConfigurationManager.AppSettings["MyConnectionString"]);

-- OR --

var obj = new MyNuGetPackage();
obj.SetConnectionString(ConfigurationManager.AppSettings["MyConnectionString"]);
</code>```

Title: Read file located in class library

Body:
I have a project containing just a class library. The project is later going to be used as a nuget package.

In the class library, I have a settings.json where I have my connectionString. But I don't know how to read the file?

I have tried to do like this:

public static class Injections
{
    public static IServiceCollection AddServiceAndRoleSecurity(this IServiceCollection services)
    {
        builder.AddJsonFile("settings.json");
        var Configuration = builder.Build();
    }
}

The settings.json is in the same folder as the Injections.cs, but this don't work.

However, it works if I use the full path to the file:

public static class Injections
{
    public static IServiceCollection AddServiceAndRoleSecurity(this IServiceCollection services)
    {
        //Works
        builder.AddJsonFile(@"C:\Projects\classlibs\Security\Application\Configuration\settings.json");
        var Configuration = builder.Build();
    }
}

But I don't want to use the full path.

Body:
If your intent to add a separate settings.json file is to allow end user to update connectionstring, which willbe used in your class library(evantually NuGet package).

Then I'd suggest you to create a parameterized constructor/method in your class library, which takes connectionstring as a parameter from user.

This way user will have freedom to save connectionstring to wherever they want like web.config/app.config/hard-coded...

Example -

public MyNuGetPackage
{
    public MyNuGetPackage(string connectionString)
    {
        //use it wherever you want
    }

    -- OR --

    public SetConnectionString(string connectionString)
    {
        //use it wherever you want
    }

}

Then, end user can use your package as -

var obj = new MyNuGetPackage(ConfigurationManager.AppSettings["MyConnectionString"]);

-- OR --

var obj = new MyNuGetPackage();
obj.SetConnectionString(ConfigurationManager.AppSettings["MyConnectionString"]);


问:
Laravel old for selectbox options
So i'm working on a standalone laravel project (still a bit new to this..). Using the same form blade file adding and editing records. I've set old to the fields for validation checks, however i can't seem to get old working correctly for dropdowns. The select options are loaded in a foreach, and ive got a check to set it to selected if the record on edit matches the dropdown option selected, however when i add the old method to it, select a new option (E.G. "broker") and force validation to throw an error it works as expected & saves whatever i've selected (option "broker"), it saves the option on submit, but then when i go to edit another record (option "assessor") it displays the same option i previously selected (option "broker")...if any of that made sense!

Here's the foreach with option select from the blade file:

```<code><select class="form-control" name="other_party_details[party_type_id]" id="other_party_details[party_type_id]">
<option value="">--- Please Select ---</option>
@foreach($partyTypes as $partyType)
<option value="{{ $partyType->id }}" {{old('other_party_details.party_type_id', !empty($claim->otherParty->party_type_id)) == $partyType->id ? 'selected' : '' }}>
{{ $partyType->label }}
</option>
@endforeach
</select>
</code>```

What am i doing wrong?

I've exhausted google as for the most it seems to show results for multi select (mine is not), or using LaravelCollective (which i'm not), so running out of places to look!

Thanks in advance

答:
You can try below code</p>

```<code><option value="{{$partyType->id}}" @if(old('party_type_id') == $partyType->id || $claim->otherParty->party_type_id == $partyType->id ) selected @endif> {{ $partyType->label }}</option>
</code>```

Title: Laravel old for selectbox options

Body:
So i'm working on a standalone laravel project (still a bit new to this..). Using the same form blade file adding and editing records. I've set old to the fields for validation checks, however i can't seem to get old working correctly for dropdowns. The select options are loaded in a foreach, and ive got a check to set it to selected if the record on edit matches the dropdown option selected, however when i add the old method to it, select a new option (E.G. "broker") and force validation to throw an error it works as expected & saves whatever i've selected (option "broker"), it saves the option on submit, but then when i go to edit another record (option "assessor") it displays the same option i previously selected (option "broker")...if any of that made sense!

Here's the foreach with option select from the blade file:

<select class="form-control" name="other_party_details[party_type_id]" id="other_party_details[party_type_id]">
<option value="">--- Please Select ---</option>
@foreach($partyTypes as $partyType)
<option value="{{ $partyType->id }}" {{old('other_party_details.party_type_id', !empty($claim->otherParty->party_type_id)) == $partyType->id ? 'selected' : '' }}>
{{ $partyType->label }}
</option>
@endforeach
</select>

What am i doing wrong?

I've exhausted google as for the most it seems to show results for multi select (mine is not), or using LaravelCollective (which i'm not), so running out of places to look!

Thanks in advance

Body:
You can try below code

<option value="{{$partyType->id}}" @if(old('party_type_id') == $partyType->id || $claim->otherParty->party_type_id == $partyType->id ) selected @endif> {{ $partyType->label }}</option>


问:
Insert Python Dictionary using Psycopg2
What is the best way to insert a Python dictionary with many keys into a Postgres database without having to enumerate all keys?

I would like to do something like...

```<code>song = dict()
song['title'] = 'song 1'
song['artist'] = 'artist 1'
...

cursor.execute('INSERT INTO song_table (song.keys()) VALUES (song)')
</code>```

答:
Python has certain inbuilt features such as join and list using which one can generate the query. Also,the python dictionary offers keys() and values() which can be used to extract column name and column values respectively. This is the approach I used and this should work.

```<code>song = dict()
song['title'] = 'song 1'
song['artist'] = 'artist 1'

query = '''insert into song_table (''' +','.join(list(song.keys()))+''') values '''+ str(tuple(song.values()))
cursor.execute(query)
</code>```

Title: Insert Python Dictionary using Psycopg2

Body:
What is the best way to insert a Python dictionary with many keys into a Postgres database without having to enumerate all keys?

I would like to do something like...

song = dict()
song['title'] = 'song 1'
song['artist'] = 'artist 1'
...

cursor.execute('INSERT INTO song_table (song.keys()) VALUES (song)')

Body:
Python has certain inbuilt features such as join and list using which one can generate the query. Also,the python dictionary offers keys() and values() which can be used to extract column name and column values respectively. This is the approach I used and this should work.

song = dict()
song['title'] = 'song 1'
song['artist'] = 'artist 1'

query = '''insert into song_table (''' +','.join(list(song.keys()))+''') values '''+ str(tuple(song.values()))
cursor.execute(query)


问:
Rmarkdown space without line break ~
In Latex, it is possible to insert a space that does not end a line by a ~ character. So writing Fig.~\ref{fig:f1} will write as

Fig. 1

and it makes sure that text wrapping never breaks a line between Fig. and the number 1.

However, in Rmarkdown writing Fig.~\@ref(fig:f1), Fig.\~\@ref(fig:f1), or Fig.\\~\@ref(fig:f1 translates to Fig.\textasciitilde{}\ref{fig:f1} giving

Fig.~1

in the output.
How do you insert the equivalent of ~ in rmarkdown? I am actually using bookdown.

答:
Use \  i.e. backslash then a space.

```<code>Fig.\ \@ref{fig:f1}
</code>```

You could also use $~$, but this works only for PDF.

```<code>Fig.$~$\@ref{fig:f1}
</code>```

Title: Rmarkdown space without line break ~

Body:
Use \  i.e. backslash then a space.

Fig.\ \@ref{fig:f1}

You could also use $~$, but this works only for PDF.

Fig.$~$\@ref{fig:f1}


问:
How to process an array one by one in javascript?
I have an array of values in a stream and you wish to pipe it such that it will emit the arrays values individually, one by one and wait for them all to be completed before processing another array</p>

```<code>// This is the array:
let arr = [[1,2,3], [4,5,6]];

let data = arr.filter( (value) => {
  let newdata = value.filter((newVal, index) => {
    if (newVal !== value[index]) {
      return '' ;
    }
  });
});

console.log(data);
// Output: []
// Expected output: [[], []]
</code>```

答:
```<code>arr.map(x => x.map((y, index) => {if(y !== y[index]){return ''}}))
</code>```

This will return [["", "", ""], ["", "", ""]]

For [[], []] filter out those blank strings:

```<code>arr.map(x => x.map((y, index) => {if(y !== y[index]){return ''}}).filter(z => z !== ""))
</code>```

Body:
I have an array of values in a stream and you wish to pipe it such that it will emit the arrays values individually, one by one and wait for them all to be completed before processing another array

// This is the array:
let arr = [[1,2,3], [4,5,6]];

let data = arr.filter( (value) => {
  let newdata = value.filter((newVal, index) => {
    if (newVal !== value[index]) {
      return '' ;
    }
  });
});

console.log(data);
// Output: []
// Expected output: [[], []]

Body:
arr.map(x => x.map((y, index) => {if(y !== y[index]){return ''}}))

This will return [["", "", ""], ["", "", ""]]

For [[], []] filter out those blank strings:

arr.map(x => x.map((y, index) => {if(y !== y[index]){return ''}}).filter(z => z !== ""))


问:
dplyr group_by returns blank
I have a data frame with the following dimensions:

```<code>18549282 obs. of  3 variables:

$ road: chr  "MULTILINESTRING((30.5592664 -30.5971316,30.5597665 -30.5964615))" ...
$ n1       : int  0 0 0 0 0 0 0 0 0 0 ...
$ n2       : int  0 0 0 0 0 0 0 0 0 0 ...
</code>```

There are no blank records in the road column, meaning that every record has a character.

When I use dplyr's group_by along with summarize to get the sum of n1 and sum of n2 by road I get a sum of n1 and n2 but I see a blank in the road column. e.g.

```<code>tt %>%
group_by(road) %>%
summarize(sn1 = sum(n1),
sn2 = sum(n2))
</code>```

I get:

Again I'm 100% sure that there are no blanks in the road column.

But when I create a data frame with, lets say 1000 records as follows

```<code>small_dataset <- head(tt, 1000)
</code>```

I don't see any blank records in the results:

Seems that dplyr strudels with the large amount of data.

Any ideas on how I can handle this issue?

答:
I found a solution, found a package I wasn't familiar with called rquery.

```<code>tt  %>%
rquery::project(.,
count := n(),
 n1 := sum(n1),
n2 :=  sum(n2),
groupby = 'road')
</code>```

solved my issue and it is faster than dplyr's group_by function.

Title: dplyr group_by returns blank

Body:
I have a data frame with the following dimensions:

18549282 obs. of  3 variables:

$ road: chr  "MULTILINESTRING((30.5592664 -30.5971316,30.5597665 -30.5964615))" ...
$ n1       : int  0 0 0 0 0 0 0 0 0 0 ...
$ n2       : int  0 0 0 0 0 0 0 0 0 0 ...

There are no blank records in the road column, meaning that every record has a character.

When I use dplyr's group_by along with summarize to get the sum of n1 and sum of n2 by road I get a sum of n1 and n2 but I see a blank in the road column. e.g.

tt %>%
group_by(road) %>%
summarize(sn1 = sum(n1),
sn2 = sum(n2))

I get:

Again I'm 100% sure that there are no blanks in the road column.

But when I create a data frame with, lets say 1000 records as follows

small_dataset <- head(tt, 1000)

I don't see any blank records in the results:

Seems that dplyr strudels with the large amount of data.

Any ideas on how I can handle this issue?

Body:
I found a solution, found a package I wasn't familiar with called rquery.

tt  %>%
rquery::project(.,
count := n(),
 n1 := sum(n1),
n2 :=  sum(n2),
groupby = 'road')

solved my issue and it is faster than dplyr's group_by function.


问:
I can not install my Android app to my phone
I am new in android app development.
I made an android app. When I run it from Android Studio to my phone it works perfectly.
Then I back it up to my SD card and try to install it and it gives me an  "Installation failed" message.
I tried using various phones but it didn't work.

What is the problem actually?
What should I do to install my app on other phones (regarding the SDK version)?

答: If you have to install your app via usb  then u have to open a developer option and inside the developer option you have to on usb tethering and install via usb option</p>


问:
How to add resources like images,sound,swf into a sharepoint webpart project?
I am trying to create a webpart using visual studio 2010.
In my project I would like to add some files like images and swf.
These files are there on my system, so how do i add these resources into
the project( and refer them) so that they are packaged and deployed along with the web part ?</p>

答: Steps 12-15 of this: http://msdn.microsoft.com/en-us/gg620532 will show you how to use the mapped folder aspect of Visual Studio 2010.</p>


问:
Performing background tasking using Job Scheduler at exact time
I am working on News app. And I needed to get latest news once a day. For this I used Jobsheduler.Here is the code :

```<code>ComponentName componentName = new ComponentName(this, JobService.class);
        JobInfo jobInfo = new JobInfo.Builder(123, componentName)
                .setRequiresCharging(false)
                .setPeriodic(24 * 60 * 60 * 1000)
                .setPersisted(true)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .build();
        JobScheduler jobScheduler = (JobScheduler)getApplicationContext().getSystemService(JOB_SCHEDULER_SERVICE);
        int resultCode = jobScheduler.schedule(jobInfo);

        if (resultCode == JobScheduler.RESULT_SUCCESS){
            Log.d(TAG, "Job Scheduled");
        }
        else {
            Log.d(TAG, "Job Scheduling failed");
        }
</code>```

But now I need to do this work once in the morning after 6:00 when there will be internet connection.
Is there a way to do this with Job Scheduler. I know that I can do this using Alarm Manager but Job Scheduler is far more better than Alarm Manager in conditions like if there is connection, if device  charging. Or can I achieve this using Workmanager which uses Job Scheduler and AlarmManager if it needs to. Or is there another way of doing this??? Any suggestions are apprecieated.

答: You can use broadcast receiver along with Work Manager which let you know the connection is available and complete your scheduled task OR you can trigger Worker for every 15 minutes after 6:00 AM(Minimum time for 2 consecutive workers) and check if internet is available and do your work

Body:
I am working on News app. And I needed to get latest news once a day. For this I used Jobsheduler.Here is the code :

ComponentName componentName = new ComponentName(this, JobService.class);
        JobInfo jobInfo = new JobInfo.Builder(123, componentName)
                .setRequiresCharging(false)
                .setPeriodic(24 * 60 * 60 * 1000)
                .setPersisted(true)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .build();
        JobScheduler jobScheduler = (JobScheduler)getApplicationContext().getSystemService(JOB_SCHEDULER_SERVICE);
        int resultCode = jobScheduler.schedule(jobInfo);

        if (resultCode == JobScheduler.RESULT_SUCCESS){
            Log.d(TAG, "Job Scheduled");
        }
        else {
            Log.d(TAG, "Job Scheduling failed");
        }

But now I need to do this work once in the morning after 6:00 when there will be internet connection.
Is there a way to do this with Job Scheduler. I know that I can do this using Alarm Manager but Job Scheduler is far more better than Alarm Manager in conditions like if there is connection, if device  charging. Or can I achieve this using Workmanager which uses Job Scheduler and AlarmManager if it needs to. Or is there another way of doing this??? Any suggestions are apprecieated.


问:
android studio 3.6 how to set gradle offline
there is no switch in gradle setting of AS version 3.6

答:
You can find the information here

It is written there:

To enable or disable Gradle's offline mode, first select View > Tool Windows > Gradle from the menu bar. Then, near the top of the Gradle window, click Toggle Offline Mode Gradle offline button in the Gradle panel


问:
node version always is back , after closing terminal
I installed node 10.13 and am using mac 10.14.6.

However, after closing terminal, the version of the node is changed to 10.0.

I would appreciate it if you would tell me how to stick the node version.

```<code>$sudo n 10.13
$export PATH=$HOME/.nodebrew/current/bin:$PATH
</code>```

答:
You need to add the path to nodebrew to your bash profile file. For example:

```<code>echo 'export PATH=$PATH:$HOME/.nodebrew/current/bin' >> ~/.bashrc
</code>```

After this, you need to either reopen the terminal or run:

```<code>source ~/.bashrc
</code>```

If you are using zsh, you will have to change .zshrc instead.

But as @Deep Kakkar mentioned, I also recommend using nvm to manage different versions of node.

Body:
I installed node 10.13 and am using mac 10.14.6.

However, after closing terminal, the version of the node is changed to 10.0.

I would appreciate it if you would tell me how to stick the node version.

$sudo n 10.13
$export PATH=$HOME/.nodebrew/current/bin:$PATH

Body:
You need to add the path to nodebrew to your bash profile file. For example:

echo 'export PATH=$PATH:$HOME/.nodebrew/current/bin' >> ~/.bashrc

After this, you need to either reopen the terminal or run:

source ~/.bashrc

If you are using zsh, you will have to change .zshrc instead.

But as @Deep Kakkar mentioned, I also recommend using nvm to manage different versions of node.


问:
Couldn't match type ‘PersistEntityBackend U’ with ‘SqlBackend’
The following code produces a compile error Couldn't match type ‘PersistEntityBackend U’ with ‘SqlBackend’ arising from a use of ‘insertUser’ due to the commented line:

```<code>sampleUser :: Entity User
sampleUser = Entity (toSqlKey 1) $ User
  { userName = "admin"
  , userEmail = "admin@test.com"
  }

type U = Entity User

connectInfo :: MySQLConnectInfo
connectInfo = undefined

runAction :: (MonadUnliftIO m, IsPersistBackend r, BaseBackend r ~ SqlBackend) => MySQLConnectInfo -> ReaderT r (LoggingT m) a -> m a
runAction connectInfo action = runStdoutLoggingT $ withMySQLConn connectInfo $ \backend ->
  runReaderT action backend

insertUser :: (PersistEntity U, PersistRecordBackend U SqlBackend) =>
             U -> ReaderT SqlBackend (LoggingT IO) (Key U)
insertUser = insert

doDBStuff :: IO ()
doDBStuff = do
  runAction connectInfo (runMigration migrateAll)
  runAction connectInfo (insertUser sampleUser) -- compile error
  return ()
</code>```

As far as I can see, I've specialized all the types in insertUser and have added all necessary constraints (having read the related SO question). What am I missing?

答:
Asking ghci :info User gave me the right hint: It shows its class instances. It turns out that it is wrong to use Entity User directly. I suspect that while this creates the entity, all the class instances generated by Database.Persist.TH.share are missing from it. Following code compiles, having also removed the redundant constraint as mentioned by Bjartur:

```<code>sampleUser :: User
sampleUser = User
  { userName = "admin"
  , userEmail = "admin@test.com"
  }

type U = User

connectInfo :: MySQLConnectInfo
connectInfo = undefined

runAction :: (MonadUnliftIO m, IsPersistBackend r, BaseBackend r ~ SqlBackend) => MySQLConnectInfo -> ReaderT r (LoggingT m) a -> m a
runAction connectInfo action = runStdoutLoggingT $ withMySQLConn connectInfo $ \backend ->
  runReaderT action backend

insertUser :: (PersistRecordBackend U SqlBackend) =>
             U -> ReaderT SqlBackend (LoggingT IO) (Key U)
insertUser = insert

doDBStuff :: IO ()
doDBStuff = do
  runAction connectInfo (runMigration migrateAll)
  runAction connectInfo (insertUser sampleUser) -- compile error fixed
  return ()
</code>```

Body:
The following code produces a compile error Couldn't match type ‘PersistEntityBackend U’ with ‘SqlBackend’ arising from a use of ‘insertUser’ due to the commented line:

sampleUser :: Entity User
sampleUser = Entity (toSqlKey 1) $ User
  { userName = "admin"
  , userEmail = "admin@test.com"
  }

type U = Entity User

connectInfo :: MySQLConnectInfo
connectInfo = undefined

runAction :: (MonadUnliftIO m, IsPersistBackend r, BaseBackend r ~ SqlBackend) => MySQLConnectInfo -> ReaderT r (LoggingT m) a -> m a
runAction connectInfo action = runStdoutLoggingT $ withMySQLConn connectInfo $ \backend ->
  runReaderT action backend

insertUser :: (PersistEntity U, PersistRecordBackend U SqlBackend) =>
             U -> ReaderT SqlBackend (LoggingT IO) (Key U)
insertUser = insert

doDBStuff :: IO ()
doDBStuff = do
  runAction connectInfo (runMigration migrateAll)
  runAction connectInfo (insertUser sampleUser) -- compile error
  return ()

As far as I can see, I've specialized all the types in insertUser and have added all necessary constraints (having read the related SO question). What am I missing?

Body:
Asking ghci :info User gave me the right hint: It shows its class instances. It turns out that it is wrong to use Entity User directly. I suspect that while this creates the entity, all the class instances generated by Database.Persist.TH.share are missing from it. Following code compiles, having also removed the redundant constraint as mentioned by Bjartur:

sampleUser :: User
sampleUser = User
  { userName = "admin"
  , userEmail = "admin@test.com"
  }

type U = User

connectInfo :: MySQLConnectInfo
connectInfo = undefined

runAction :: (MonadUnliftIO m, IsPersistBackend r, BaseBackend r ~ SqlBackend) => MySQLConnectInfo -> ReaderT r (LoggingT m) a -> m a
runAction connectInfo action = runStdoutLoggingT $ withMySQLConn connectInfo $ \backend ->
  runReaderT action backend

insertUser :: (PersistRecordBackend U SqlBackend) =>
             U -> ReaderT SqlBackend (LoggingT IO) (Key U)
insertUser = insert

doDBStuff :: IO ()
doDBStuff = do
  runAction connectInfo (runMigration migrateAll)
  runAction connectInfo (insertUser sampleUser) -- compile error fixed
  return ()


问:
Checking if a URL is valid via responcecodes
My App gets a lot of URLs back via JSON data.

Some of the URLS have no content (Code 204) and some do (Code 200).

At the moment I get the response code by making a call to the URl and the response code comes back along with all the data at that URL. So it pretty much downloads everything at the URL just so I can check its response code.

Is there a way to make a call to only get the response code and not all the data? There can be a lot of data sometimes so its slow and a waste of the users data allowance.

Many Thanks,
Code

答:
Are you sure you are getting content with 204 status code?

The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.

For other status codes, consider using HEAD method instead of GET. Off course you can not use HEAD instead of POST, PUT etc. because they are supposed to modify server state so it doesn't make sense to just get metainformation for these methods.


问:
C# Fastest way to intersect lists of strings
I am using hashet, linq Intersect() and Count() to find intersection of two lists of strings.

Code being used

```<code>private HashSet<string> Words { get; }

public Sentence(IEnumerable<string> words)
{
    Words = words.ToHashSet();
}

public int GetSameWordCount(Sentence sentence)
{
    return Words.Intersect(sentence.Words).Count();
}
</code>```

Method GetSameWordCount is Taking > 90% of program runtime as there are milions of Sentences to compare with each other.

Is there any faster way to do this?

I am using .net core 3.1.1 / C# 8 so any recent features can be used.

More info:

  Input data is coming from text file (e.g. book excerpt, articles from web).
  Sentences are then unaccented, lowercased and split to words by whitespace >regex.
  Short words (<3 length) are ignored.

  I am creating groups of sentences which have N words in common and ordering >these groups by number of shared words.

答:
The below code will utilize HashSet<T>.Contains method which is more performant. Time complexity of HashSet<T>.Contains is O(1).

public int GetSameWordCount(Sentence sentence)
{
    var count;
    foreach(var word in sentence.Words)
    {
         if(Words.Contains(word))
             count++;
    }
    return count;
}
```

<p><strong>Note</strong></p>

<p>If the list of the words is sorted you can use below approach.</p>

<pre class="lang-cs prettyprint-override"><code>        var enumerator1 = set1.GetEnumerator();
        var enumerator2 = set2.GetEnumerator();
        var count = 0;
        if (enumerator1.MoveNext() && enumerator2.MoveNext())
        {
            while (true)
            {
                var value = enumerator1.Current.CompareTo(enumerator2.Current);
                if (value == 0)
                {
                    count++;
                    if (!enumerator1.MoveNext() || !enumerator2.MoveNext())
                        break;
                }
                else if (value < 0)
                {
                    if (!enumerator1.MoveNext())
                        break;
                }
                else
                {
                    if (!enumerator2.MoveNext())
                        break;
                }
            }
        }
</code>```

Body:
I am using hashet, linq Intersect() and Count() to find intersection of two lists of strings.

Code being used

private HashSet<string> Words { get; }

public Sentence(IEnumerable<string> words)
{
    Words = words.ToHashSet();
}

public int GetSameWordCount(Sentence sentence)
{
    return Words.Intersect(sentence.Words).Count();
}

Method GetSameWordCount is Taking > 90% of program runtime as there are milions of Sentences to compare with each other.

Is there any faster way to do this?

I am using .net core 3.1.1 / C# 8 so any recent features can be used.

More info:

  Input data is coming from text file (e.g. book excerpt, articles from web).
  Sentences are then unaccented, lowercased and split to words by whitespace >regex.
  Short words (<3 length) are ignored.

  I am creating groups of sentences which have N words in common and ordering >these groups by number of shared words.

Body:
The below code will utilize HashSet<T>.Contains method which is more performant. Time complexity of HashSet<T>.Contains is O(1).

public int GetSameWordCount(Sentence sentence)
{
    var count;
    foreach(var word in sentence.Words)
    {
         if(Words.Contains(word))
             count++;
    }
    return count;
}

Note

If the list of the words is sorted you can use below approach.

        var enumerator1 = set1.GetEnumerator();
        var enumerator2 = set2.GetEnumerator();
        var count = 0;
        if (enumerator1.MoveNext() && enumerator2.MoveNext())
        {
            while (true)
            {
                var value = enumerator1.Current.CompareTo(enumerator2.Current);
                if (value == 0)
                {
                    count++;
                    if (!enumerator1.MoveNext() || !enumerator2.MoveNext())
                        break;
                }
                else if (value < 0)
                {
                    if (!enumerator1.MoveNext())
                        break;
                }
                else
                {
                    if (!enumerator2.MoveNext())
                        break;
                }
            }
        }


问:
Redirect to another page on submit JavaScript
I am trying to integrate firebase auth in node js express based application.

But I am getting this error:

nexttick.js:45 Uncaught TypeError: Cannot read property 'redirect' of
  undefined

This is my register.js file:

```<code>signUpForm.addEventListener('submit', (e) => {
    e.preventDefault();

    //get user info
    const email = signUpForm["email"].value;
    const password = signUpForm["password"].value;

    //sign up the user
    auth.createUserWithEmailAndPassword(email, password).then((req, res) => {
        res.redirect('/');
    })
});

</code>```

Can anyone tell me what am I doing wrong?

答:
You are using the auth.createUserWithEmailAndPassword the wrong way. The method is a promise so it's okay to attach a .then or .catch to it, however, from what I saw in the docs, auth.createUserWithEmailAndPassword promise does not resolve to a req or res parameters like you added to the .then method and it rejects when there is an error in the create user process. So this is how you are supposed to use the method:

```<code>auth.createUserWithEmailAndPassword(email, password)
.then(() => {
  window.location.replace('/')
})
.catch((error) => {
  // Handle errors here.
});
</code>```

You can take a look at this doc for the possible types of errors that can be rejected.

For redirecting, you can make use of either the location.replace or location.assign API available as global variables in the browser

Body:
I am trying to integrate firebase auth in node js express based application.

But I am getting this error:

nexttick.js:45 Uncaught TypeError: Cannot read property 'redirect' of
  undefined

This is my register.js file:

signUpForm.addEventListener('submit', (e) => {
    e.preventDefault();

    //get user info
    const email = signUpForm["email"].value;
    const password = signUpForm["password"].value;

    //sign up the user
    auth.createUserWithEmailAndPassword(email, password).then((req, res) => {
        res.redirect('/');
    })
});

Can anyone tell me what am I doing wrong?

Body:
You are using the auth.createUserWithEmailAndPassword the wrong way. The method is a promise so it's okay to attach a .then or .catch to it, however, from what I saw in the docs, auth.createUserWithEmailAndPassword promise does not resolve to a req or res parameters like you added to the .then method and it rejects when there is an error in the create user process. So this is how you are supposed to use the method:

auth.createUserWithEmailAndPassword(email, password)
.then(() => {
  window.location.replace('/')
})
.catch((error) => {
  // Handle errors here.
});

You can take a look at this doc for the possible types of errors that can be rejected.

For redirecting, you can make use of either the location.replace or location.assign API available as global variables in the browser


问:
How do you include a custom npm package to Google Dialogflow?
I have been trying to add package "alphanum-increment" to my fulfillment of the Google Dialogflow. I've found couple of pointers to include it in package.json under dependencies but couldn't find the exact way to include it.

Thanks in advance for the solution

答:
The answer is pretty simple since you said you want to include it in your package.json. You have to include the name of the npm package.

```<code> {
    "some": "crazyPropsFoo",
    "engines": {},
    "scripts": {},
    "dependencies": {
      "actions-on-google": "^1.5.x",
      "firebase-admin": "~4.1.2",
      "firebase-functions": "~0.5",
      "alphanum-increment": "0.0.2",   // Here you include yours
      }
    }
</code>```

Then you just need to require the package in your 'index.js' file:

```<code>var PackageObj = require("alphanum-increment").PackageObject;
var yourVar = new PackageObj();
</code>```

Body:
The answer is pretty simple since you said you want to include it in your package.json. You have to include the name of the npm package.

 {
    "some": "crazyPropsFoo",
    "engines": {},
    "scripts": {},
    "dependencies": {
      "actions-on-google": "^1.5.x",
      "firebase-admin": "~4.1.2",
      "firebase-functions": "~0.5",
      "alphanum-increment": "0.0.2",   // Here you include yours
      }
    }

Then you just need to require the package in your 'index.js' file:

var PackageObj = require("alphanum-increment").PackageObject;
var yourVar = new PackageObj();


问:
How to get the indexpath.row when an element is activated?
I have a tableview with buttons and I want to use the indexpath.row when one of them is tapped.
This is what I currently have, but it always is 0</p>

```<code>var point = Int()
func buttonPressed(sender: AnyObject) {
    let pointInTable: CGPoint =         sender.convertPoint(sender.bounds.origin, toView: self.tableView)
    let cellIndexPath = self.tableView.indexPathForRowAtPoint(pointInTable)
    println(cellIndexPath)
    point = cellIndexPath!.row
    println(point)
}
</code>```

答:
Very Simple getting Index Path swift 4, 5

let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! Cell
cell.btn.tag = indexPath.row
cell.btn.addTarget(self, action: "buttonTapped:", forControlEvents:
UIControlEvents.TouchUpInside)
```
<p>How to get IndexPath Inside Btn Click :</p>
<pre class="lang-swift prettyprint-override"><code>func buttonTapped(_ sender: UIButton) {
     print(sender.tag)
}
</code>```

Body:
I have a tableview with buttons and I want to use the indexpath.row when one of them is tapped.
This is what I currently have, but it always is 0

var point = Int()
func buttonPressed(sender: AnyObject) {
    let pointInTable: CGPoint =         sender.convertPoint(sender.bounds.origin, toView: self.tableView)
    let cellIndexPath = self.tableView.indexPathForRowAtPoint(pointInTable)
    println(cellIndexPath)
    point = cellIndexPath!.row
    println(point)
}

Body:
Very Simple getting Index Path swift 4, 5

let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! Cell
cell.btn.tag = indexPath.row
cell.btn.addTarget(self, action: "buttonTapped:", forControlEvents:
UIControlEvents.TouchUpInside)

How to get IndexPath Inside Btn Click :

func buttonTapped(_ sender: UIButton) {
     print(sender.tag)
}


问:
Missing visible-** and hidden-** in Bootstrap
In Bootstrap v3 I often use the hidden-** classes combined with clearfix to control multi column layouts at different screen widths. For example,

I could combine multiple hidden-** in one DIV to make my multi columns appear correctly at different screen widths.

As an example if I wanted to display rows of product photos, 4 per row on larger screen sizes, 3 on smaller screens, then 2 on very small screens. The product photos might be different heights so I need the clearfix to ensure the row breaks properly.

Here's an example in v3...

http://jsbin.com/tosebayode/edit?html,css,output

Now that v4 has done away with these classes, and replaced them with the visible/hidden-**-up/down classes I seem to have to do the same thing with multiple DIVs instead.

Here's a similar example in v4...

http://jsbin.com/sagowihowa/edit?html,css,output

So I've gone from single DIVs to having to add multiple DIVs with lots of up/down classes to achieve the same thing.

From...

```<code><div class="clearfix visible-xs-block visible-sm-block"></div>
</code>```

to...

```<code><div class="clearfix hidden-sm-up"></div>
<div class="clearfix hidden-md-up hidden-xs-down"></div>
<div class="clearfix hidden-md-down"></div>
</code>```

Is there a better way of doing this in v4 that I have overlooked?

答:
For bootstrap 4, here's a matrix image explaining the classes used to show / hide elements depends on the screen size:

Source : Meduim : Bootstrap 4 Hidden & Visible

Body:
In Bootstrap v3 I often use the hidden-** classes combined with clearfix to control multi column layouts at different screen widths. For example,

I could combine multiple hidden-** in one DIV to make my multi columns appear correctly at different screen widths.

As an example if I wanted to display rows of product photos, 4 per row on larger screen sizes, 3 on smaller screens, then 2 on very small screens. The product photos might be different heights so I need the clearfix to ensure the row breaks properly.

Here's an example in v3...

http://jsbin.com/tosebayode/edit?html,css,output

Now that v4 has done away with these classes, and replaced them with the visible/hidden-**-up/down classes I seem to have to do the same thing with multiple DIVs instead.

Here's a similar example in v4...

http://jsbin.com/sagowihowa/edit?html,css,output

So I've gone from single DIVs to having to add multiple DIVs with lots of up/down classes to achieve the same thing.

From...

to...

Is there a better way of doing this in v4 that I have overlooked?


问:
How to start my td's as revealed and unreveal them on click
Example of my table So basically im making a minesweeper game with PHP/Javascript. The thing is that I would like my td's to be revealed at first, and when you click on a td it unreveals itself including the content. Since im very new to programming I need all the help I can get. And if possible, explain what does what with comments or so. posted below is my javascript that im using. If you need the PHP code as well, let me know :)
BUG = mine</p>

```<code>$(document).ready(function () {
    $("td").click(function () {
        if ($(this).text() == '') {
            $(this).css('background-color', 'DarkGray');
            console.log("Je hebt op een leeg vakje geklikt");
        }

        if ($(this).text() == 'BUG') {
            $("td:contains('BUG')").css('background-color', 'Gray');
            $("td:not(:contains('BUG'))").css('background-color', 'DarkGray');
            console.log("Je hebt op een bug geklikt");
        }

        $("#renew").click(function () {
            location.reload();
        });
    })
});
</code>```

答:
You want to hide / reveal specific table cell texts based on user clicks.

You cannot do that with background-color, since that will not override the text (the text will still be written above the background color).

Trying not to diverge from your current implementation, you could make all your td cells have font-size: 0px, and then when the user clicks, change the font size to be mlarger than 0 so the text shows (along with changing backgrounds and whatever else you want).

CSS

```<code>td{
font-size: 0px;
}
</code>```

JS

```<code>$(document).ready(function () {
$("td").click(function () {

    $(this).css('font-size', '18px');

    if ($(this).text() == '') {
        $(this).css('background-color', 'DarkGray');
        console.log("Je hebt op een leeg vakje geklikt");
    }

    if ($(this).text() == 'BUG') {
        $("td:contains('BUG')").css('background-color', 'Gray');
        $("td:not(:contains('BUG'))").css('background-color', 'DarkGray');
        console.log("Je hebt op een bug geklikt");
    }

    $("#renew").click(function () {
        location.reload();
    });
})
</code>```

});

Edit:
This is a clunky way of implementing the desired functionality. A better way would be to, instead of adding BUG text directly into your td, write your td to hold information about whether or not it contains a BUG.

For example:

```<code><td data-type="BUG"></td>
<td data-type="NOT"></td>
<td data-type="BUG"></td>
</code>```

Then, when the user clicks on a td, you check if data-type is BUG, and if it is, add 'BUG' into the clicked td, and in that way you 'reveal' what the td was.

For example with before mentioned html:

```<code>$("td").click(function(){
   if($(this).attr("data-type") === "BUG"){
       //user clicked on a td with a BUG
       $(this).text('BUG');
   }
});
</code>```

Body:
Example of my table So basically im making a minesweeper game with PHP/Javascript. The thing is that I would like my td's to be revealed at first, and when you click on a td it unreveals itself including the content. Since im very new to programming I need all the help I can get. And if possible, explain what does what with comments or so. posted below is my javascript that im using. If you need the PHP code as well, let me know :)
BUG = mine

$(document).ready(function () {
    $("td").click(function () {
        if ($(this).text() == '') {
            $(this).css('background-color', 'DarkGray');
            console.log("Je hebt op een leeg vakje geklikt");
        }

        if ($(this).text() == 'BUG') {
            $("td:contains('BUG')").css('background-color', 'Gray');
            $("td:not(:contains('BUG'))").css('background-color', 'DarkGray');
            console.log("Je hebt op een bug geklikt");
        }

        $("#renew").click(function () {
            location.reload();
        });
    })
});

Body:
You want to hide / reveal specific table cell texts based on user clicks.

You cannot do that with background-color, since that will not override the text (the text will still be written above the background color).

Trying not to diverge from your current implementation, you could make all your td cells have font-size: 0px, and then when the user clicks, change the font size to be mlarger than 0 so the text shows (along with changing backgrounds and whatever else you want).

CSS

td{
font-size: 0px;
}

JS

$(document).ready(function () {
$("td").click(function () {

    $(this).css('font-size', '18px');

    if ($(this).text() == '') {
        $(this).css('background-color', 'DarkGray');
        console.log("Je hebt op een leeg vakje geklikt");
    }

    if ($(this).text() == 'BUG') {
        $("td:contains('BUG')").css('background-color', 'Gray');
        $("td:not(:contains('BUG'))").css('background-color', 'DarkGray');
        console.log("Je hebt op een bug geklikt");
    }

    $("#renew").click(function () {
        location.reload();
    });
})

});

Edit:
This is a clunky way of implementing the desired functionality. A better way would be to, instead of adding BUG text directly into your td, write your td to hold information about whether or not it contains a BUG.

For example:

<td data-type="BUG"></td>
<td data-type="NOT"></td>
<td data-type="BUG"></td>

Then, when the user clicks on a td, you check if data-type is BUG, and if it is, add 'BUG' into the clicked td, and in that way you 'reveal' what the td was.

For example with before mentioned html:

$("td").click(function(){
   if($(this).attr("data-type") === "BUG"){
       //user clicked on a td with a BUG
       $(this).text('BUG');
   }
});


问:
IntelliJ web service and Java client IllegalArgumentException TestWebService is not an interface
In IntelliJ 10.0.3

I use the menu option "new web service" and this generates a class file and adds to sun-jaxws.xml - this is fine - it's working.

Now if I try to write a Java client for this web service I get IllegalArgumentException TestWebService is not an interface

Here's my client code:

```<code>public class WebServiceTest {

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://localhost/services/TestWebService?wsdl");
        //1st argument service URI, refer to wsdl document above
        //2nd argument is service name, refer to wsdl document above
        QName qname = new QName("http://ws.mydomain.com/", "TestWebServiceService");

        Service service = Service.create(url, qname);

        TestWebService test = service.getPort(TestWebService.class); // fails here

        System.out.println(test.sayHelloWorldFrom("TESTING...."));
    }
}
</code>```

How should I implement this? Should I have an interface and a class?  Is there a good example? Best practice?

this is my endpoint definition in sun-jaxws.xml

```<code><endpoint
        name='TestWebService'
        implementation='com.allscripts.ws.TestWebService'
        url-pattern='/services/TestWebService'/>
</code>```

答: I was getting messed up because I was trying to use the web service withing my application using the same classpath.  Running a test in a different java project works fine.</p>

Body:
In IntelliJ 10.0.3

I use the menu option "new web service" and this generates a class file and adds to sun-jaxws.xml - this is fine - it's working.

Now if I try to write a Java client for this web service I get IllegalArgumentException TestWebService is not an interface

Here's my client code:

public class WebServiceTest {

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://localhost/services/TestWebService?wsdl");
        //1st argument service URI, refer to wsdl document above
        //2nd argument is service name, refer to wsdl document above
        QName qname = new QName("http://ws.mydomain.com/", "TestWebServiceService");

        Service service = Service.create(url, qname);

        TestWebService test = service.getPort(TestWebService.class); // fails here

        System.out.println(test.sayHelloWorldFrom("TESTING...."));
    }
}

How should I implement this? Should I have an interface and a class?  Is there a good example? Best practice?

this is my endpoint definition in sun-jaxws.xml

<endpoint
        name='TestWebService'
        implementation='com.allscripts.ws.TestWebService'
        url-pattern='/services/TestWebService'/>


问:
SSIS - Query table using id's from other database
I have a table containing just id's in SQL Server, it has almost 1 million id's.
Now I have to use those id's to search a table in Oracle and bring back only those
rows that match those 1 million id's (one to one match).

The issue is in Oracle, the data coming from Oracle is not from a single table, it is a query with multiple joins to different tables.

Also, the Oracle table has billions of rows, so I don't want to load all rows and perform a lookup function.

The id's will go in the query in where clause e.g.

```<code>where ID in (select ID from sql_server_table)
</code>```

What is the efficient way to do this in SSIS?

答:
1.First complete data store in to staging table from your multi table.

2.select ID from sql_server_table Data Store into the Cache file using Cache Transform.

3.Now in new data flow use staging table as source table and compare data with Cache file using
   look up for more information

https://mask-me.net/datamaskingwiki/wiki/169/ssis-help-cache-and-lookup-transform

Body:
I have a table containing just id's in SQL Server, it has almost 1 million id's.
Now I have to use those id's to search a table in Oracle and bring back only those
rows that match those 1 million id's (one to one match).

The issue is in Oracle, the data coming from Oracle is not from a single table, it is a query with multiple joins to different tables.

Also, the Oracle table has billions of rows, so I don't want to load all rows and perform a lookup function.

The id's will go in the query in where clause e.g.

where ID in (select ID from sql_server_table)

What is the efficient way to do this in SSIS?


问:
Testing for memory leak in Fortran (using pFUnit)
I've wrote my first program using allocatable. It works as expected. But, does it really? And more importantly, how can I set up a unit-test to catch memory leaks?

The idea behind the program is to allocate a chunck of storage room for my list of objects in the first place. And every time I add one more element more to the list than the allocated size, I double the allocation. I do this to reduce the number of allocations and subsequent copying of data from the old allocated memory, to the newly allocated memory.

I might over complicate this, but I'd like to spend some time now understanding the pitfalls, rather than falling head first into them a year or two down into the project.

The ode is compiled with gfortran 8.3.0 on linux. And using pFUnit 4.1. The code below is an extract to test only the allocation part.

Heres my test-program:

```<code>  program test_realloc
    use class_test_malloc
    integer :: i
    real :: x, y
    type(tmalloc) :: myobject

    call myobject%initialize()

    do i=1, 100
      x = i * i
      y = sqrt(x)
      call myobject%add_nbcell(i, x, y)
    end do

    call myobject%dump()

end program test_realloc
</code>```

array_reallocation.f:

```<code>        !
    ! Simple test to see if my understanding of dynamicly allocation
    ! of arrays is correct.
    !

    module class_test_malloc
       use testinglistobj
       implicit none

  type tmalloc
      integer :: numnbcells, maxnbcells
      type(listobj), allocatable :: nbcells(:)
  contains

      procedure, public :: initialize => init
      procedure, public :: add_nbcell    ! Might be private?
      procedure, private :: expand_nbcells
      procedure, public :: dump

  end type tmalloc

  contains

    subroutine init(this)
      class(tmalloc), intent(inout) :: this

      this%numnbcells = 0
      this%maxnbcells = 4
      allocate (this%nbcells(this%maxnbcells))
    end subroutine init

    subroutine add_nbcell(this, idx, x, y)
      class(tmalloc), intent(inout) :: this
      integer, intent(in) :: idx
      real, intent(in) :: x, y
      type(listobj) :: nbcell

      if(this%numnbcells .eq. this%maxnbcells) then
        call this%expand_nbcells()
        print *,"Expanding"
      endif

      this%numnbcells = this%numnbcells + 1
      nbcell%idx = idx
      nbcell%x = x
      nbcell%y = y
      this%nbcells(this%numnbcells) = nbcell
      print *,"Adding"
    end subroutine add_nbcell

    subroutine expand_nbcells(this)
      class(tmalloc), intent(inout) :: this
      type(listobj), allocatable :: tmpnbcells(:)
      integer :: size

      size = this%maxnbcells *2
      allocate (tmpnbcells(size))
      tmpnbcells(1:this%maxnbcells) = this%nbcells
      call move_alloc( from=tmpnbcells, to=this%nbcells)
      this%maxnbcells = size
    end subroutine

    subroutine dump(this)
      class(tmalloc), intent(inout) :: this
      integer :: i

      do i=1, this%numnbcells
        print*, this%nbcells(i)%x, this%nbcells(i)%y
      end do
    end subroutine

  end module
</code>```

listobj.f:

```<code>  module testinglistobj
  type listobj
       integer :: idx
       real :: x
       real :: y
  end type
  end module testinglistobj
</code>```

答:
You will not get any memory leaks with this code. The reason is, and this is fundamental to the understanding of allocatable arrays, is that in Fortran 95 onwards it is required that allocatable arrays without the save attribute automatically get deallocated when they go out of scope. The nett result of this is that memory leaks for such arrays are impossible. This is one very good reason why you should prefer allocatable arrays to pointers. Related is the general software engineering principle of keeping the scope of variables as limited as possible, so that arrays are in memory for as short a period as possible.

Note this does not mean that you should never deallocate them as an array may remain in scope long after it is actually useful. Here "manual" deallocation may be of use. But it is not a memory leak.

Body:
I've wrote my first program using allocatable. It works as expected. But, does it really? And more importantly, how can I set up a unit-test to catch memory leaks?

The idea behind the program is to allocate a chunck of storage room for my list of objects in the first place. And every time I add one more element more to the list than the allocated size, I double the allocation. I do this to reduce the number of allocations and subsequent copying of data from the old allocated memory, to the newly allocated memory.

I might over complicate this, but I'd like to spend some time now understanding the pitfalls, rather than falling head first into them a year or two down into the project.

The ode is compiled with gfortran 8.3.0 on linux. And using pFUnit 4.1. The code below is an extract to test only the allocation part.

Heres my test-program:

  program test_realloc
    use class_test_malloc
    integer :: i
    real :: x, y
    type(tmalloc) :: myobject

    call myobject%initialize()

    do i=1, 100
      x = i * i
      y = sqrt(x)
      call myobject%add_nbcell(i, x, y)
    end do

    call myobject%dump()

end program test_realloc

array_reallocation.f:

        !
    ! Simple test to see if my understanding of dynamicly allocation
    ! of arrays is correct.
    !

    module class_test_malloc
       use testinglistobj
       implicit none

  type tmalloc
      integer :: numnbcells, maxnbcells
      type(listobj), allocatable :: nbcells(:)
  contains

      procedure, public :: initialize => init
      procedure, public :: add_nbcell    ! Might be private?
      procedure, private :: expand_nbcells
      procedure, public :: dump

  end type tmalloc

  contains

    subroutine init(this)
      class(tmalloc), intent(inout) :: this

      this%numnbcells = 0
      this%maxnbcells = 4
      allocate (this%nbcells(this%maxnbcells))
    end subroutine init

    subroutine add_nbcell(this, idx, x, y)
      class(tmalloc), intent(inout) :: this
      integer, intent(in) :: idx
      real, intent(in) :: x, y
      type(listobj) :: nbcell

      if(this%numnbcells .eq. this%maxnbcells) then
        call this%expand_nbcells()
        print *,"Expanding"
      endif

      this%numnbcells = this%numnbcells + 1
      nbcell%idx = idx
      nbcell%x = x
      nbcell%y = y
      this%nbcells(this%numnbcells) = nbcell
      print *,"Adding"
    end subroutine add_nbcell

    subroutine expand_nbcells(this)
      class(tmalloc), intent(inout) :: this
      type(listobj), allocatable :: tmpnbcells(:)
      integer :: size

      size = this%maxnbcells *2
      allocate (tmpnbcells(size))
      tmpnbcells(1:this%maxnbcells) = this%nbcells
      call move_alloc( from=tmpnbcells, to=this%nbcells)
      this%maxnbcells = size
    end subroutine

    subroutine dump(this)
      class(tmalloc), intent(inout) :: this
      integer :: i

      do i=1, this%numnbcells
        print*, this%nbcells(i)%x, this%nbcells(i)%y
      end do
    end subroutine

  end module

listobj.f:

  module testinglistobj
  type listobj
       integer :: idx
       real :: x
       real :: y
  end type
  end module testinglistobj