问:
How to save STDOUT outputs to a text file?
I have a program which utilizes a 3rd party command line tool to generate logs. The 3rd party generates all its output to the STDOUT which the user must then use the " > test.txt" command to save the file.

However the program somehow generates a certain amount of report generated but not the entire report. This was test by using the command

C:\Test\ftk\ripxp>ripxp.exe -r C:\test\ftk\ntuser.dat -d "C:\System Volume\_rest
ore{BB12863B-2C77-46C9-BCDA-1810E52F1089}" -p runmru > C:\test\test05.txt

on the command line console which works and on the program which works only partially.

The errors were narrowed down to either the arguments error or the file saving error part (streamReader). Therefore the error could be due to the STDOUT not being properly saved.

Therefore may someone please advise on the codes? Thanks!

The Arguments for the 3rd party tool(2008 H. Carvey):

```<code>RipXP v.20081001 - CLI RegRipper tool
RipXP [-r Reg hive file] [-p plugin module][-d RP dir][-lgh]
Parse Windows Registry files, using either a single module from the plugins folder.
Then parse all corresponding hive files from the XP Restore Points (extracted from
image) using the same plugin.

-r Reg hive file...Registry hive file to parse
-g ................Guess the hive file (experimental)
-d RP directory....Path to the Restore Point directory
-p plugin module...use only this module
-l ................list all plugins
-h.................Help (print this information)

Ex: C:\>rip -g
C:\>rip -r d:\cases\ntuser.dat -d d:\cases\svi -p userassist

All output goes to STDOUT; use redirection (ie, > or >>) to output to a file.

copyright 2008 H. Carvey
</code>```

The Codes:

```<code>static void Main(string[] args)
    {
        // Automatically finds folder that starts with _restore
        DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\System Volume\");
        DirectoryInfo restoreFolder = directoryInfo.GetDirectories().FirstOrDefault(d => d.Name.StartsWith("_restore"));

        // Gets the folder name
        String baka = restoreFolder.Name;

        if (restoreFolder == null)
            throw new DirectoryNotFoundException();

            Process process = new Process();
            process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
            process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume\" + restoreFolder.Name + " -p runmru";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();

            String text = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume\" +restoreFolder.Name  + " -p runmru";
            Console.WriteLine(baka);
            Console.WriteLine(text);

            // Strangely the program only outputs the first section "-r C:\test\ftk\ntuser.dat" argument results.....
            System.IO.StreamReader reader = process.StandardOutput;
            String sRes = reader.ReadToEnd();
            StreamWriter SW;
            SW = File.CreateText(@"C:\test\test01.txt");
            SW.WriteLine(sRes);
            SW.Close();
            Console.WriteLine("File Created Successfully");
            reader.Close();

    }
</code>```

答:
You can have .NET inform you when the process has exited and then read the output. Because, as detunized mentioned in his answer+comment, if you call reader.ReadToEnd() before it has completed, you won't get all the output. If you think of it, it's quite obvious - the data hasn't been produced yet, so how can you expect the reader to read it?

By using events you will not block the method that starts the thread which can be quite useful if you have a GUI application and don't want to freeze the user interface while the child process is running.

```<code>// tell it to raise events and hook up a callback to when it completes
process.EnableRaisingEvents = true;
process.Exited += process_Exited;
process.Start();
</code>```

This method will be called when the process has completed:

```<code>void process_Exited(object sender, EventArgs e)
{
    var process = (Process)sender;
    using (var f = File.CreateText(@"..."))
    {
        f.WriteLine(process.StandardOutput.ReadToEnd());
    }
}
</code>```

Body:
I have a program which utilizes a 3rd party command line tool to generate logs. The 3rd party generates all its output to the STDOUT which the user must then use the " > test.txt" command to save the file.

However the program somehow generates a certain amount of report generated but not the entire report. This was test by using the command

C:\Test\ftk\ripxp>ripxp.exe -r C:\test\ftk\ntuser.dat -d "C:\System Volume\_rest
ore{BB12863B-2C77-46C9-BCDA-1810E52F1089}" -p runmru > C:\test\test05.txt

on the command line console which works and on the program which works only partially.

The errors were narrowed down to either the arguments error or the file saving error part (streamReader). Therefore the error could be due to the STDOUT not being properly saved.

Therefore may someone please advise on the codes? Thanks!

The Arguments for the 3rd party tool(2008 H. Carvey):

RipXP v.20081001 - CLI RegRipper tool
RipXP [-r Reg hive file] [-p plugin module][-d RP dir][-lgh]
Parse Windows Registry files, using either a single module from the plugins folder.
Then parse all corresponding hive files from the XP Restore Points (extracted from
image) using the same plugin.

-r Reg hive file...Registry hive file to parse
-g ................Guess the hive file (experimental)
-d RP directory....Path to the Restore Point directory
-p plugin module...use only this module
-l ................list all plugins
-h.................Help (print this information)

Ex: C:\>rip -g
C:\>rip -r d:\cases\ntuser.dat -d d:\cases\svi -p userassist

All output goes to STDOUT; use redirection (ie, > or >>) to output to a file.

copyright 2008 H. Carvey

The Codes:

static void Main(string[] args)
    {
        // Automatically finds folder that starts with _restore
        DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\System Volume\");
        DirectoryInfo restoreFolder = directoryInfo.GetDirectories().FirstOrDefault(d => d.Name.StartsWith("_restore"));

        // Gets the folder name
        String baka = restoreFolder.Name;

        if (restoreFolder == null)
            throw new DirectoryNotFoundException();

            Process process = new Process();
            process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
            process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume\" + restoreFolder.Name + " -p runmru";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();

            String text = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume\" +restoreFolder.Name  + " -p runmru";
            Console.WriteLine(baka);
            Console.WriteLine(text);

            // Strangely the program only outputs the first section "-r C:\test\ftk\ntuser.dat" argument results.....
            System.IO.StreamReader reader = process.StandardOutput;
            String sRes = reader.ReadToEnd();
            StreamWriter SW;
            SW = File.CreateText(@"C:\test\test01.txt");
            SW.WriteLine(sRes);
            SW.Close();
            Console.WriteLine("File Created Successfully");
            reader.Close();

    }

Body:
You can have .NET inform you when the process has exited and then read the output. Because, as detunized mentioned in his answer+comment, if you call reader.ReadToEnd() before it has completed, you won't get all the output. If you think of it, it's quite obvious - the data hasn't been produced yet, so how can you expect the reader to read it?

By using events you will not block the method that starts the thread which can be quite useful if you have a GUI application and don't want to freeze the user interface while the child process is running.

// tell it to raise events and hook up a callback to when it completes
process.EnableRaisingEvents = true;
process.Exited += process_Exited;
process.Start();

This method will be called when the process has completed:

void process_Exited(object sender, EventArgs e)
{
    var process = (Process)sender;
    using (var f = File.CreateText(@"..."))
    {
        f.WriteLine(process.StandardOutput.ReadToEnd());
    }
}


来源: stackexchange

问:
Add id css via rails enum
I would like to know I can set id via rails enum. For example,

```<code><% @products.each_with_index do |product, index| %>
            <tr id="<% #{index} %>" >
                      .
                      .
<% end %>
</code>```

答:
Yep you should add '=' right after <% like that

```<code><% @products.each_with_index do |product, index| %>
  <tr id="<%= index %>" >
 .
 .
<% end %>
</code>```

or

ContentLicense: CC BY-SA 3.0

Title: Add id css via rails enum

Body:
I would like to know I can set id via rails enum. For example,

<% @products.each_with_index do |product, index| %>
            <tr id="<% #{index} %>" >
                      .
                      .
<% end %>

Body:
Yep you should add '=' right after <% like that

<% @products.each_with_index do |product, index| %>
  <tr id="<%= index %>" >
 .
 .
<% end %>

or <tr id="#{index}">


问:
Need solution to avoid repeated scanning in huge table
I have a event table which has 40 columns and fill up to 2 billion records. In that event table i would like to query for a combination event i.e Event A with Event B. Sometimes I may want to find more combination like Event A with B and C. It may goes to 5 or 6 combination.

I don't want to scan that table for every event in combination i.e Scanning for event A and scanning for event B. And I need a generic approach for more combination scanning as well.

Note: That 2 billion records is partitioned based on event date and data is been equally split.

Eg:

Need to find id's which has event A,B,C and need to find id's which has only A,B.

This number of combination is dynamic. I don't want to scan that table for each event and finally intersect the result.

答:
```<code>SELECT * from table as A
JOIN table AS B
    ON A.Id = B.Id AND A.Date = B.Date
WHERE Date = '1-Jan'
AND A.Event = 'A'
AND B.Event = 'B'
</code>```

This will give you rows, where Date is '1-Jan' and Id is same for both events.
You can join table again and again if you want to filter by more events.

Body:
SELECT * from table as A
JOIN table AS B
    ON A.Id = B.Id AND A.Date = B.Date
WHERE Date = '1-Jan'
AND A.Event = 'A'
AND B.Event = 'B'

This will give you rows, where Date is '1-Jan' and Id is same for both events.
You can join table again and again if you want to filter by more events.


问:
How to set hostname in global service in Docker Swarm
I have a service deployed to my Docker Swarm Cluster as global service (ELK Metricbeat).

I want to each of this service to have a hostname the same as the hostname of the running node (host)?

in another word, how I can achieve the same result in the yml file such as:

```<code> docker run -h `hostname` elastic/metricbeat:5.4.1
</code>```

this is my yml file:

```<code>metricbeat:
  image: elastic/metricbeat:5.4.1
  command: metricbeat -e -c /etc/metricbeat/metricbeat.yml -system.hostfs=/hostfs
  hostname: '`hostname`'
  volumes:
    - /proc:/hostfs/proc:ro
    - /sys/fs/cgroup:/hostfs/sys/fs/cgroup:ro
    - /:/hostfs:ro
    - /var/run/docker.sock:/var/run/docker.sock
  networks:
    - net
  user: root
  deploy:
    mode: global
</code>```

I have tried:

```<code>  hostname: '`hostname`'
  hostname: '${hostname}'
</code>```

but no success.

Any solution?

Thank you in advance.

答:
I resolved the issue by mounting the host hostname file under /etc/nodehostname and changing the service container to use an entrypoint that read the file and replace a variable (name) in metricbeat.yml

docker-entrypoint.sh

```<code>export NODE_HOSTNAME=$(eval cat /etc/nodehostname)

envsubst '$NODE_HOSTNAME' </etc/metricbeat/metricbeat.yml.tpl > /etc/metricbeat/metricbeat.yml
</code>```

Body:
I have a service deployed to my Docker Swarm Cluster as global service (ELK Metricbeat).

I want to each of this service to have a hostname the same as the hostname of the running node (host)?

in another word, how I can achieve the same result in the yml file such as:

 docker run -h `hostname` elastic/metricbeat:5.4.1

this is my yml file:

metricbeat:
  image: elastic/metricbeat:5.4.1
  command: metricbeat -e -c /etc/metricbeat/metricbeat.yml -system.hostfs=/hostfs
  hostname: '`hostname`'
  volumes:
    - /proc:/hostfs/proc:ro
    - /sys/fs/cgroup:/hostfs/sys/fs/cgroup:ro
    - /:/hostfs:ro
    - /var/run/docker.sock:/var/run/docker.sock
  networks:
    - net
  user: root
  deploy:
    mode: global

I have tried:

  hostname: '`hostname`'
  hostname: '${hostname}'

but no success.

Any solution?

Thank you in advance.

Body:
I resolved the issue by mounting the host hostname file under /etc/nodehostname and changing the service container to use an entrypoint that read the file and replace a variable (name) in metricbeat.yml

docker-entrypoint.sh

export NODE_HOSTNAME=$(eval cat /etc/nodehostname)

envsubst '$NODE_HOSTNAME' </etc/metricbeat/metricbeat.yml.tpl > /etc/metricbeat/metricbeat.yml


问:
MapBox SDK not working android
I just started to use the MapBox SDK but its not working I was following the steps on the documentation but Im not getting any classes from their SDK here is my code:

build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.1"

    defaultConfig {
        applicationId "com.mapp.hello"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
repositories {
    mavenCentral()
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile ('com.mapbox.mapboxsdk:mapbox-android-sdk:4.2.0-beta.2@aar'){
        transitive=true
    }
}
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest package="com.mapp.hello"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <service android:name="com.mapbox.mapboxsdk.telemetry.TelemetryService"/>
    </application>

</manifest>
</code>```

The com.mapbox.mapboxsdk.telemetry.TelemetryService is shown in red and I cannot import the MapboxAccountManager

答:
I know it's an old question, but I just had the same error while trying to update from Mapbox 4.x to 5.x and it turns out you have to change:

<service android:name="com.mapbox.mapboxsdk.telemetry.TelemetryService"/>

to

```<code><service android:name="com.mapbox.services.android.telemetry.service.TelemetryService" />
</code>```

Update:
Turns out in the latest version (5.x) you don't have to declare it in the Manifest at all, as Mapbox now makes use of Manifest merge feature.

Title: MapBox SDK not working android

Body:
I just started to use the MapBox SDK but its not working I was following the steps on the documentation but Im not getting any classes from their SDK here is my code:

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.1"

    defaultConfig {
        applicationId "com.mapp.hello"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
repositories {
    mavenCentral()
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile ('com.mapbox.mapboxsdk:mapbox-android-sdk:4.2.0-beta.2@aar'){
        transitive=true
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.mapp.hello"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <service android:name="com.mapbox.mapboxsdk.telemetry.TelemetryService"/>
    </application>

</manifest>

The com.mapbox.mapboxsdk.telemetry.TelemetryService is shown in red and I cannot import the MapboxAccountManager

Body:
I know it's an old question, but I just had the same error while trying to update from Mapbox 4.x to 5.x and it turns out you have to change:

<service android:name="com.mapbox.mapboxsdk.telemetry.TelemetryService"/>

to

<service android:name="com.mapbox.services.android.telemetry.service.TelemetryService" />

Update:
Turns out in the latest version (5.x) you don't have to declare it in the Manifest at all, as Mapbox now makes use of Manifest merge feature.


问:
Angular 4: `ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked
Every EventEmiiter in my child module gives this error and I can't find a fix for this.

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.

This is what triggers my EventEmitter:

ngOnChanges(changes: any) {
    if (changes.groupingTabValid) {
        if (changes.groupingTabValid.currentValue !== changes.groupingTabValid.previousValue) {
            this.groupingTabValidChange.emit(this.groupingTabValid);
        }
    }
}
```

<p>Here is my "main" componenent's HTML</p>

<pre class="lang-xml prettyprint-override"><code><year-overview-grouping [definitionDetails]="definitionDetails"
                        [fixedData]="fixedData"
                        [showValidation]="showValidation"
                        [groupingTabValid]="groupingTabValid"
                        (groupingTabValidChange)="setValidators('groupingTab', $event)">

</year-overview-grouping>
</code>```

Which calls this function

public setValidators(validator: string, e: boolean) {
    switch (validator) {
        case "groupingTab":
            this.groupingTabValid = e;
            break;

        case "selectionTab":
            this.selectionTabValid = e;
            break;
    }

    if (this.groupingTabValid && this.selectionTabValid) {
        this.valid = true;
    } else {
        this.valid = false;
    }
}
```

1) In a a simple explanation, what's causing this error?

2) What steps can I take to solve this?

答:
Abide by the unidirectional data flow rule

Try to postpone the call to emit for one tick with a setTimeout

if (changes.groupingTabValid.currentValue !== changes.groupingTabValid.previousValue) {
    setTimeout(() => this.groupingTabValidChange.emit(this.groupingTabValid), 0)
}
```

Body:
Every EventEmiiter in my child module gives this error and I can't find a fix for this.

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.

This is what triggers my EventEmitter:

ngOnChanges(changes: any) {
    if (changes.groupingTabValid) {
        if (changes.groupingTabValid.currentValue !== changes.groupingTabValid.previousValue) {
            this.groupingTabValidChange.emit(this.groupingTabValid);
        }
    }
}

Here is my "main" componenent's HTML

<year-overview-grouping [definitionDetails]="definitionDetails"
                        [fixedData]="fixedData"
                        [showValidation]="showValidation"
                        [groupingTabValid]="groupingTabValid"
                        (groupingTabValidChange)="setValidators('groupingTab', $event)">

</year-overview-grouping>

Which calls this function

public setValidators(validator: string, e: boolean) {
    switch (validator) {
        case "groupingTab":
            this.groupingTabValid = e;
            break;

        case "selectionTab":
            this.selectionTabValid = e;
            break;
    }

    if (this.groupingTabValid && this.selectionTabValid) {
        this.valid = true;
    } else {
        this.valid = false;
    }
}

1) In a a simple explanation, what's causing this error?

2) What steps can I take to solve this?


问:
why static method can not be called inside instance method?
The error says that global name "get_words" is not defined. But I did define a static method named get_words. What should I do if I want to call get_words function inside train()</p>

```<code>class classfier(object):
    def __init__(self):
        self.fc = {}
        self.cc = {}

    @staticmethod
    def get_words(item):
        words = re.split(r"\W+",item.strip())
        words =  [element.lower() for element in words if len(element)>2 and len(element)<20]
        return set(words)

    def train(self,item,cat):
        features = get_words(item)
        for f in features:
            self.incf(f,cat)
        self.incc(cat)
</code>```

答:
Calling a static method inside of an instance needs the name of the Class as identifier:

```<code>features = classfier.get_words(item)
</code>```

will work. self always refers to the object or instance itself, a class or static method or value can be called by the class name.

Body:
The error says that global name "get_words" is not defined. But I did define a static method named get_words. What should I do if I want to call get_words function inside train()

class classfier(object):
    def __init__(self):
        self.fc = {}
        self.cc = {}

    @staticmethod
    def get_words(item):
        words = re.split(r"\W+",item.strip())
        words =  [element.lower() for element in words if len(element)>2 and len(element)<20]
        return set(words)

    def train(self,item,cat):
        features = get_words(item)
        for f in features:
            self.incf(f,cat)
        self.incc(cat)

Body:
Calling a static method inside of an instance needs the name of the Class as identifier:

features = classfier.get_words(item)

will work. self always refers to the object or instance itself, a class or static method or value can be called by the class name.


问:
Is there a way to scrape the dataLayer available on the page instead of the regular HTML Elements in excel VBA?
I am trying to fetch some data from the web pages using Excel VBA and have been fairly successful.

However I have realized that most of the pages do have data-layer available on the page and thus if I am able to use the same, lot of effort can be reduced in massaging the data to bring it in usable format.

I tried to call the data layer by Document.getElement method but this seems not to be working.

I am not a hard core developer just can swim for my needs so please let me know if this is possible as all of my search results so far have yielded nothing.

答:
I normally use SeleniumBasic (Excel Plugin) for WebScraping Needs. They way it can be done is by using</p>

```<code>driver.ExecuteScript("return dataLayer[x].variableName")
</code>```

Body:
I normally use SeleniumBasic (Excel Plugin) for WebScraping Needs. They way it can be done is by using

driver.ExecuteScript("return dataLayer[x].variableName")


问:
Big ugly SQL query problem
I have two tables:
Status(status_id, desc1, desc2, desc3, desc4)
Status_Level(status_level_id, desc, levelD, levelS)

The connection is on the desc1..4 fileds in Status and desc in Status_Level.
I need to select status_id, levelD and levelS where levelD and levelS are highest levels of all four descs.

I tried this:

```<code>SELECT Status.status_id, MAX(levelS) AS ds_column, MAX(levelD) AS ss_column
FROM Status, Status_level WHERE
Status_level.desc=Status.desc1 OR
Status_level.desc=Status.desc2 OR
Status_level.desc=Status.desc3 OR
Status_level.desc=Status.desc4
GROUP BY Status.status_id
</code>```

My SQL is very rusty so any help would be greatly appreciated.
Thanks.

edit:
example:

```<code>Status:
-----------------------------------------------------------
| 1 | ABC_LEVEL_1 | DEF_LEVEL_5| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------
| 2 | ABC_LEVEL_1 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_1|
-----------------------------------------------------------
| 3 | ABC_LEVEL_4 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------

Status_Level:
---------------------------
| 1 | ABC_LEVEL_1 | 1 | 7 |
---------------------------
| 1 | DEF_LEVEL_5 | 5 | 6 |
---------------------------
| 1 | CBA_LEVEL_2 | 2 | 3 |
---------------------------
| 1 | ABC_LEVEL_4 | 4 | 5 |
---------------------------
| 1 | DEF_LEVEL_1 | 1 | 2 |

Desired output:

-------------
| 1 | 5 | 7 | <- 5 from DEF_LEVEL_5 and 7 from ABC_LEVEL_1
-------------
| 2 | 2 | 7 | <- 2 from CBA_LEVEL_2 and 7 from ABC_LEVEL_1
-------------
| 3 | 4 | 5 | <- 4 from ABC_LEVEL_4 and 5 from ABC_LEVEL_4
-------------
</code>```

答:
This will work (from my mocked up example below):

```<code>select S.status_id, max(levelD), max(levelS)
from @status s
inner join @Status_Level sl1 on sl1.[desc] in (s.desc1,s.desc2,s.desc3,s.desc4)
group by status_id
</code>```

Here is the complete mock up which you can paste into your Query Editor window:

```<code>declare @status table (status_id int, desc1 varchar(20), desc2 varchar(20), desc3 varchar(20), desc4 varchar(20))
declare @Status_Level table (status_level_id int, [desc]varchar(20), levelD int, levelS int)

insert into @status values(1, 'ABC_LEVEL_1','DEF_LEVEL_5','CBA_LEVEL_2','ABC_LEVEL_4')
insert into @status values(2, 'ABC_LEVEL_1','DEF_LEVEL_1','CBA_LEVEL_2','ABC_LEVEL_1')
insert into @status values(3, 'ABC_LEVEL_4','DEF_LEVEL_1','CBA_LEVEL_2','ABC_LEVEL_4')

insert into @Status_Level values(1, 'ABC_LEVEL_1',1,7)
insert into @Status_Level values(1, 'DEF_LEVEL_5',5,6)
insert into @Status_Level values(1, 'CBA_LEVEL_2',2,3)
insert into @Status_Level values(1, 'ABC_LEVEL_4',4,5)
insert into @Status_Level values(1, 'DEF_LEVEL_1',1,2)

--The select statement
select S.status_id, max(levelD), max(levelS)
from @status s
inner join @Status_Level sl1 on sl1.[desc] in (s.desc1,s.desc2,s.desc3,s.desc4)
group by status_id
</code>```

ContentLicense: CC BY-SA 2.5

Title: Big ugly SQL query problem

Body:
I have two tables:
Status(status_id, desc1, desc2, desc3, desc4)
Status_Level(status_level_id, desc, levelD, levelS)

The connection is on the desc1..4 fileds in Status and desc in Status_Level.
I need to select status_id, levelD and levelS where levelD and levelS are highest levels of all four descs.

I tried this:

SELECT Status.status_id, MAX(levelS) AS ds_column, MAX(levelD) AS ss_column
FROM Status, Status_level WHERE
Status_level.desc=Status.desc1 OR
Status_level.desc=Status.desc2 OR
Status_level.desc=Status.desc3 OR
Status_level.desc=Status.desc4
GROUP BY Status.status_id

My SQL is very rusty so any help would be greatly appreciated.
Thanks.

edit:
example:

Status:
-----------------------------------------------------------
| 1 | ABC_LEVEL_1 | DEF_LEVEL_5| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------
| 2 | ABC_LEVEL_1 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_1|
-----------------------------------------------------------
| 3 | ABC_LEVEL_4 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------

Status_Level:
---------------------------
| 1 | ABC_LEVEL_1 | 1 | 7 |
---------------------------
| 1 | DEF_LEVEL_5 | 5 | 6 |
---------------------------
| 1 | CBA_LEVEL_2 | 2 | 3 |
---------------------------
| 1 | ABC_LEVEL_4 | 4 | 5 |
---------------------------
| 1 | DEF_LEVEL_1 | 1 | 2 |

Desired output:

-------------
| 1 | 5 | 7 | <- 5 from DEF_LEVEL_5 and 7 from ABC_LEVEL_1
-------------
| 2 | 2 | 7 | <- 2 from CBA_LEVEL_2 and 7 from ABC_LEVEL_1
-------------
| 3 | 4 | 5 | <- 4 from ABC_LEVEL_4 and 5 from ABC_LEVEL_4
-------------

Body:
This will work (from my mocked up example below):

select S.status_id, max(levelD), max(levelS)
from @status s
inner join @Status_Level sl1 on sl1.[desc] in (s.desc1,s.desc2,s.desc3,s.desc4)
group by status_id

Here is the complete mock up which you can paste into your Query Editor window:

declare @status table (status_id int, desc1 varchar(20), desc2 varchar(20), desc3 varchar(20), desc4 varchar(20))
declare @Status_Level table (status_level_id int, [desc]varchar(20), levelD int, levelS int)

insert into @status values(1, 'ABC_LEVEL_1','DEF_LEVEL_5','CBA_LEVEL_2','ABC_LEVEL_4')
insert into @status values(2, 'ABC_LEVEL_1','DEF_LEVEL_1','CBA_LEVEL_2','ABC_LEVEL_1')
insert into @status values(3, 'ABC_LEVEL_4','DEF_LEVEL_1','CBA_LEVEL_2','ABC_LEVEL_4')

insert into @Status_Level values(1, 'ABC_LEVEL_1',1,7)
insert into @Status_Level values(1, 'DEF_LEVEL_5',5,6)
insert into @Status_Level values(1, 'CBA_LEVEL_2',2,3)
insert into @Status_Level values(1, 'ABC_LEVEL_4',4,5)
insert into @Status_Level values(1, 'DEF_LEVEL_1',1,2)

--The select statement
select S.status_id, max(levelD), max(levelS)
from @status s
inner join @Status_Level sl1 on sl1.[desc] in (s.desc1,s.desc2,s.desc3,s.desc4)
group by status_id


问:
How to get ios permissions list from .ipa file
I am using java 1.8 and spring-boot-starter-parent 1.5.1.RELEASE version.

I am trying to get list of permissions from .ipa file. I did fetch Android permissions from .apk, like extracted AndroidManifest.xml from .apk and get get permissions from that xml file.

```<code>{
  "permissions": [
    "android.permission.INTERNET",
    "android.permission.ACCESS_NETWORK_STATE",
    "android.permission.BLUETOOTH",
    "android.permission.BLUETOOTH_ADMIN",
    "android.permission.RECEIVE_BOOT_COMPLETED",
    "android.permission.ACCESS_COARSE_LOCATION",
    "android.permission.ACCESS_WIFI_STATE",
    "android.permission.ACCESS_FINE_LOCATION",
    "android.permission.READ_EXTERNAL_STORAGE",
    "android.permission.WRITE_EXTERNAL_STORAGE",
    "android.permission.BATTERY_STATS",
    "android.permission.WAKE_LOCK"
  ]
}
</code>```

Like the same way, Is there any way to get permissions for iOS?

I have extracted .ipa file using the java code, it returns the two directories as "Payload" and "Symbols". The Payload directory contains the "Info.plist" file.

答:
You can add permission according to your requirement in info.plist.

You can check this link add permission in info.plist

```<code><key>NSAppleMusicUsageDescription</key>
<string>${PRODUCT_NAME} Music Usage</string>

<key>NSMicrophoneUsageDescription</key>
<string>${PRODUCT_NAME} Microphone Usage</string>

<key>NSCalendarsUsageDescription</key>
<string>${PRODUCT_NAME} Calendar Usage</string>

<key>NSContactsUsageDescription</key>
<string>${PRODUCT_NAME} Contact fetch</string>

<key>NSHealthShareUsageDescription</key>
<string>${PRODUCT_NAME} Health Description</string>

<key>NSHealthUpdateUsageDescription</key>
<string>${PRODUCT_NAME} Health Updates</string>

<key>NSHomeKitUsageDescription</key>
<string>${PRODUCT_NAME} HomeKit Usage</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} Use location always</string>

<key>NSCameraUsageDescription</key>
<string>${PRODUCT_NAME} Camera Usage</string>

<key>NSBluetoothPeripheralUsageDescription</key>
<string>${PRODUCT_NAME} BluetoothPeripheral</string>

<key>NSLocationUsageDescription</key>
<string>${PRODUCT_NAME} Location Updates</string>

<key>NSLocationWhenInUseUsageDescription</key>
<string>${PRODUCT_NAME} WhenInUse Location</string>

<key>NSMotionUsageDescription</key>
<string>${PRODUCT_NAME} Motion Usage</string>

<key>kTCCServiceMediaLibrary</key>
<string>${PRODUCT_NAME} MediaLibrary Usage</string>

<key>NSSpeechRecognitionUsageDescription</key>
<string>${PRODUCT_NAME} Speech Recognition Usage</string>

<key>NSVideoSubscriberAccountUsageDescription</key>
<string>${PRODUCT_NAME} Video Subscribe Usage</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>${PRODUCT_NAME} PhotoLibrary Usage</string>

<key>NSRemindersUsageDescription</key>
<string>${PRODUCT_NAME} Reminder Usage</string>

<key>NSSiriUsageDescription</key>
<string>${PRODUCT_NAME} Siri Usage</string>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using java 1.8 and spring-boot-starter-parent 1.5.1.RELEASE version.

I am trying to get list of permissions from .ipa file. I did fetch Android permissions from .apk, like extracted AndroidManifest.xml from .apk and get get permissions from that xml file.

{
  "permissions": [
    "android.permission.INTERNET",
    "android.permission.ACCESS_NETWORK_STATE",
    "android.permission.BLUETOOTH",
    "android.permission.BLUETOOTH_ADMIN",
    "android.permission.RECEIVE_BOOT_COMPLETED",
    "android.permission.ACCESS_COARSE_LOCATION",
    "android.permission.ACCESS_WIFI_STATE",
    "android.permission.ACCESS_FINE_LOCATION",
    "android.permission.READ_EXTERNAL_STORAGE",
    "android.permission.WRITE_EXTERNAL_STORAGE",
    "android.permission.BATTERY_STATS",
    "android.permission.WAKE_LOCK"
  ]
}

Like the same way, Is there any way to get permissions for iOS?

I have extracted .ipa file using the java code, it returns the two directories as "Payload" and "Symbols". The Payload directory contains the "Info.plist" file.

Body:
You can add permission according to your requirement in info.plist.

You can check this link add permission in info.plist

<key>NSAppleMusicUsageDescription</key>
<string>${PRODUCT_NAME} Music Usage</string>

<key>NSMicrophoneUsageDescription</key>
<string>${PRODUCT_NAME} Microphone Usage</string>

<key>NSCalendarsUsageDescription</key>
<string>${PRODUCT_NAME} Calendar Usage</string>

<key>NSContactsUsageDescription</key>
<string>${PRODUCT_NAME} Contact fetch</string>

<key>NSHealthShareUsageDescription</key>
<string>${PRODUCT_NAME} Health Description</string>

<key>NSHealthUpdateUsageDescription</key>
<string>${PRODUCT_NAME} Health Updates</string>

<key>NSHomeKitUsageDescription</key>
<string>${PRODUCT_NAME} HomeKit Usage</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} Use location always</string>

<key>NSCameraUsageDescription</key>
<string>${PRODUCT_NAME} Camera Usage</string>

<key>NSBluetoothPeripheralUsageDescription</key>
<string>${PRODUCT_NAME} BluetoothPeripheral</string>

<key>NSLocationUsageDescription</key>
<string>${PRODUCT_NAME} Location Updates</string>

<key>NSLocationWhenInUseUsageDescription</key>
<string>${PRODUCT_NAME} WhenInUse Location</string>

<key>NSMotionUsageDescription</key>
<string>${PRODUCT_NAME} Motion Usage</string>

<key>kTCCServiceMediaLibrary</key>
<string>${PRODUCT_NAME} MediaLibrary Usage</string>

<key>NSSpeechRecognitionUsageDescription</key>
<string>${PRODUCT_NAME} Speech Recognition Usage</string>

<key>NSVideoSubscriberAccountUsageDescription</key>
<string>${PRODUCT_NAME} Video Subscribe Usage</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>${PRODUCT_NAME} PhotoLibrary Usage</string>

<key>NSRemindersUsageDescription</key>
<string>${PRODUCT_NAME} Reminder Usage</string>

<key>NSSiriUsageDescription</key>
<string>${PRODUCT_NAME} Siri Usage</string>


问:
Cast dynamic matrix to fixed matrix in Eigen
For flexibility, I'm loading data into dynamic-sized matrices (e.g. Eigen::MatrixXf) using the C++ library Eigen. I've written some functions which require mixed- or fixed-sized matrices as parameters (e.g. Eigen::Matrix<float, 3, Eigen::Dynamic> or Eigen::Matrix4f). Assuming I do the proper assertions for row and column size, how can I convert the dynamic matrix (size set at runtime) to a fixed matrix (size set at compile time)?

The only solution I can think of is to map it, for example:

```<code>Eigen::MatrixXf dyn = Eigen::MatrixXf::Random(3, 100);
Eigen::Matrix<float, 3, Eigen::Dynamic> fixed =
    Eigen::Map<float, 3, Eigen::Dynamic>(dyn.data(), 3, dyn.cols());
</code>```

But it's unclear to me if that will work either because the fixed size map constructor doesn't accept rows and columns as parameters in the docs. Is there a better solution? Simply assigning dynamic- to fixed-sized matrices doesn't work.

答:
You can use Ref for that purpose, it's usage in your case is simpler, and it will do the runtime assertion checks for you, e.g.:

```<code>MatrixXf A_dyn(4,4);
Ref<Matrix4f> A_fixed(A_dyn);
</code>```

You might even require a fixed outer-stride and aligned memory:

```<code> Ref<Matrix4f,Aligned16,OuterStride<4> > A_fixed(A_dyn);
</code>```

In this case, A_fixed is really like a Matrix4f.

Body:
For flexibility, I'm loading data into dynamic-sized matrices (e.g. Eigen::MatrixXf) using the C++ library Eigen. I've written some functions which require mixed- or fixed-sized matrices as parameters (e.g. Eigen::Matrix<float, 3, Eigen::Dynamic> or Eigen::Matrix4f). Assuming I do the proper assertions for row and column size, how can I convert the dynamic matrix (size set at runtime) to a fixed matrix (size set at compile time)?

The only solution I can think of is to map it, for example:

Eigen::MatrixXf dyn = Eigen::MatrixXf::Random(3, 100);
Eigen::Matrix<float, 3, Eigen::Dynamic> fixed =
    Eigen::Map<float, 3, Eigen::Dynamic>(dyn.data(), 3, dyn.cols());

But it's unclear to me if that will work either because the fixed size map constructor doesn't accept rows and columns as parameters in the docs. Is there a better solution? Simply assigning dynamic- to fixed-sized matrices doesn't work.

Body:
You can use Ref for that purpose, it's usage in your case is simpler, and it will do the runtime assertion checks for you, e.g.:

MatrixXf A_dyn(4,4);
Ref<Matrix4f> A_fixed(A_dyn);

You might even require a fixed outer-stride and aligned memory:

 Ref<Matrix4f,Aligned16,OuterStride<4> > A_fixed(A_dyn);

In this case, A_fixed is really like a Matrix4f.


问:
Why there are the same variables of mine with a ':' in Visual Studio auto complete list?
What's the difference between myVar and myVar: in VS auto-complete list while working with functions. Why the second one is added to this list ?

答:
C# 4.0 introduced named arguments. This feature allows you to identify method arguments by their names instead of their position:

```<code>public void Foo(int bar, string quux)
{
}

// Before C# 4.0:
Foo(42, "text");

// After C# 4.0:
Foo(bar: 42, quux: "text");

// Or, equivalently:
Foo(quux: "text", bar: 42);
</code>```

Intellisense has been updated to support that feature, that's why its autocompletion mechanism now offers both choices when a symbol accessible from the current scope has the same name as a method argument.

Body:
C# 4.0 introduced named arguments. This feature allows you to identify method arguments by their names instead of their position:

public void Foo(int bar, string quux)
{
}

// Before C# 4.0:
Foo(42, "text");

// After C# 4.0:
Foo(bar: 42, quux: "text");

// Or, equivalently:
Foo(quux: "text", bar: 42);

Intellisense has been updated to support that feature, that's why its autocompletion mechanism now offers both choices when a symbol accessible from the current scope has the same name as a method argument.


问:
Change part of controltemplate in styled controls?
I have customized the ToggleButton control using a ControlTemplate like so:

```<code><StackPanel>
    <StackPanel.Resources>
        <Style x:Key="OptionBarButton" TargetType="{x:Type ToggleButton}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ToggleButton">
                        <Border Padding="18,12,18,12" Background="{TemplateBinding Background}">
                            <ContentPresenter />
                        </Border>
                        <ControlTemplate.Triggers>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsChecked" Value="True" />
                                    <Condition Property="IsMouseOver" Value="True" />
                                </MultiTrigger.Conditions>
                                <MultiTrigger.Setters>
                                    <Setter Property="Background" Value="DarkBlue" />
                                </MultiTrigger.Setters>
                            </MultiTrigger>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsChecked" Value="True" />
                                    <Condition Property="IsMouseOver" Value="False" />
                                </MultiTrigger.Conditions>
                                <MultiTrigger.Setters>
                                    <Setter Property="Background" Value="SkyBlue" />
                                </MultiTrigger.Setters>
                            </MultiTrigger>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsChecked" Value="False" />
                                    <Condition Property="IsMouseOver" Value="False" />
                                </MultiTrigger.Conditions>
                                <MultiTrigger.Setters>
                                    <Setter Property="Background" Value="#88000000" />
                                </MultiTrigger.Setters>
                            </MultiTrigger>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsChecked" Value="False" />
                                    <Condition Property="IsMouseOver" Value="True" />
                                </MultiTrigger.Conditions>
                                <MultiTrigger.Setters>
                                    <Setter Property="Background" Value="#F0000000" />
                                </MultiTrigger.Setters>
                            </MultiTrigger>
                        </ControlTemplate.Triggers>

                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </StackPanel.Resources>

    <ToggleButton Style="{StaticResource OptionBarButton}">
        <Image Source="../Assets/icons/action.png" Height="26" RenderOptions.BitmapScalingMode="Fant" />
    </ToggleButton>

    <ToggleButton Style="{StaticResource OptionBarButton}">
        <Image Source="../Assets/icons/action2.png" Height="26" RenderOptions.BitmapScalingMode="Fant" />
    </ToggleButton>

</StackPanel>
</code>```

This works fine, however I would now want to change some parts of the template in some of the styled controls, namely the IsChecked color states (SkyBlue/DarkBlue).

Is it possible to modify / pass these colors in/to the template when using it? I know I can use attached properties or/and subclass the ToggleButton class (adding dependency properties to it), but I was wondering if there isn't a more idiomatic way to solve this, perhaps only with xaml. Having to write custom code in C# seems a little bit overkill for such a simple use case?

答:
There is no easy way to do this without code, as far as I know, but if you really want to - you can utilize dynamic resources in certain way. Usually dynamic resources are used to change appearence of ALL instances of control at runtime. You reference dynamic resource from template, then change that resource and all controls reflect this change. This is probably not what you need in this case, because you want to change "some parts of the template in some of the styled controls". You can still do it like this:

```<code><!-- default checked and over color -->
<SolidColorBrush x:Key="TgCheckedAndOver" Color="DarkBlue" />
<!-- default checked color -->
<SolidColorBrush x:Key="TgChecked" Color="SkyBlue" />
<Style
       TargetType="{x:Type ToggleButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ToggleButton">
                <Border Padding="18,12,18,12"
                        Background="{TemplateBinding Background}">
                    <ContentPresenter />
                </Border>
                <ControlTemplate.Triggers>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsChecked"
                                       Value="True" />
                            <Condition Property="IsMouseOver"
                                       Value="True" />
                        </MultiTrigger.Conditions>
                        <MultiTrigger.Setters>
                            <Setter Property="Background"
                                    Value="{DynamicResource TgCheckedAndOver}" />
                        </MultiTrigger.Setters>
                    </MultiTrigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsChecked"
                                       Value="True" />
                            <Condition Property="IsMouseOver"
                                       Value="False" />
                        </MultiTrigger.Conditions>
                        <MultiTrigger.Setters>
                            <Setter Property="Background"
                                    Value="{DynamicResource TgChecked}" />
                        </MultiTrigger.Setters>
                    </MultiTrigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsChecked"
                                       Value="False" />
                            <Condition Property="IsMouseOver"
                                       Value="False" />
                        </MultiTrigger.Conditions>
                        <MultiTrigger.Setters>
                            <Setter Property="Background"
                                    Value="#88000000" />
                        </MultiTrigger.Setters>
                    </MultiTrigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsChecked"
                                       Value="False" />
                            <Condition Property="IsMouseOver"
                                       Value="True" />
                        </MultiTrigger.Conditions>
                        <MultiTrigger.Setters>
                            <Setter Property="Background"
                                    Value="#F0000000" />
                        </MultiTrigger.Setters>
                    </MultiTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

This is regular use of dynamic resource. Now when you want to change appearence just for particular control, you do this:

```<code><ToggleButton>
    <ToggleButton.Resources>
        <!-- override default resources -->
        <SolidColorBrush x:Key="TgChecked" Color="Yellow" />
        <SolidColorBrush x:Key="TgCheckedAndOver"
                         Color="Green" />
    </ToggleButton.Resources>
    <Image Source="../Assets/icons/action.png" Height="26" RenderOptions.BitmapScalingMode="Fant" />
</ToggleButton>
</code>```

Because you place new resources with the same keys "closer" to the control - template will use them instead of default ones, and just this particular control will do that, not all of them.

Body:
I have customized the ToggleButton control using a ControlTemplate like so:

<StackPanel>
    <StackPanel.Resources>

    </StackPanel.Resources>

    <ToggleButton Style="{StaticResource OptionBarButton}">
        <Image Source="../Assets/icons/action.png" Height="26" RenderOptions.BitmapScalingMode="Fant" />
    </ToggleButton>

    <ToggleButton Style="{StaticResource OptionBarButton}">
        <Image Source="../Assets/icons/action2.png" Height="26" RenderOptions.BitmapScalingMode="Fant" />
    </ToggleButton>

</StackPanel>

This works fine, however I would now want to change some parts of the template in some of the styled controls, namely the IsChecked color states (SkyBlue/DarkBlue).

Is it possible to modify / pass these colors in/to the template when using it? I know I can use attached properties or/and subclass the ToggleButton class (adding dependency properties to it), but I was wondering if there isn't a more idiomatic way to solve this, perhaps only with xaml. Having to write custom code in C# seems a little bit overkill for such a simple use case?

Body:
There is no easy way to do this without code, as far as I know, but if you really want to - you can utilize dynamic resources in certain way. Usually dynamic resources are used to change appearence of ALL instances of control at runtime. You reference dynamic resource from template, then change that resource and all controls reflect this change. This is probably not what you need in this case, because you want to change "some parts of the template in some of the styled controls". You can still do it like this:

<!-- default checked and over color -->
<SolidColorBrush x:Key="TgCheckedAndOver" Color="DarkBlue" />
<!-- default checked color -->
<SolidColorBrush x:Key="TgChecked" Color="SkyBlue" />
<Style
       TargetType="{x:Type ToggleButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ToggleButton">
                <Border Padding="18,12,18,12"
                        Background="{TemplateBinding Background}">
                    <ContentPresenter />
                </Border>
                <ControlTemplate.Triggers>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsChecked"
                                       Value="True" />
                            <Condition Property="IsMouseOver"
                                       Value="True" />
                        </MultiTrigger.Conditions>
                        <MultiTrigger.Setters>
                            <Setter Property="Background"
                                    Value="{DynamicResource TgCheckedAndOver}" />
                        </MultiTrigger.Setters>
                    </MultiTrigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsChecked"
                                       Value="True" />
                            <Condition Property="IsMouseOver"
                                       Value="False" />
                        </MultiTrigger.Conditions>
                        <MultiTrigger.Setters>
                            <Setter Property="Background"
                                    Value="{DynamicResource TgChecked}" />
                        </MultiTrigger.Setters>
                    </MultiTrigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsChecked"
                                       Value="False" />
                            <Condition Property="IsMouseOver"
                                       Value="False" />
                        </MultiTrigger.Conditions>
                        <MultiTrigger.Setters>
                            <Setter Property="Background"
                                    Value="#88000000" />
                        </MultiTrigger.Setters>
                    </MultiTrigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsChecked"
                                       Value="False" />
                            <Condition Property="IsMouseOver"
                                       Value="True" />
                        </MultiTrigger.Conditions>
                        <MultiTrigger.Setters>
                            <Setter Property="Background"
                                    Value="#F0000000" />
                        </MultiTrigger.Setters>
                    </MultiTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

This is regular use of dynamic resource. Now when you want to change appearence just for particular control, you do this:

<ToggleButton>
    <ToggleButton.Resources>
        <!-- override default resources -->
        <SolidColorBrush x:Key="TgChecked" Color="Yellow" />
        <SolidColorBrush x:Key="TgCheckedAndOver"
                         Color="Green" />
    </ToggleButton.Resources>
    <Image Source="../Assets/icons/action.png" Height="26" RenderOptions.BitmapScalingMode="Fant" />
</ToggleButton>

Because you place new resources with the same keys "closer" to the control - template will use them instead of default ones, and just this particular control will do that, not all of them.


问:
Simulate a request inside a controller
I'm working in a symfony project and i have two function in my controller :

```<code>function1Action ($request Request, $product) {
    $quantity = $request->request->get('quantity')
    //dothingshere
}
function2Action($product, $value) {
    $em = $this->getDoctrine()->getManager();
    $pattern = $em->getRepository('repo')->find($value)
    //return an array ['quantity'=>x]
    $this->function1Action($pattern, $product)
}
</code>```

usually the user call the function 1 (post request) with the good request parameter. So here all is good. My problem is sometimes, the function 2 is gonna be call and when it is i need to call function 1 but i don't have a proper Request and i want to send $pattern

So i found 3 solution

Solution 1 :
create function1bis who does the same thing as function1 but take an array as parameter

Solution 2 : Initiate a null value in my first function

```<code>function1 ($request Request, $product, $patt=null) {
    if(!$patt){
        $quantity = $request->request->get('quantity')
    }
    else {
        $quantity = $patt['quantity']
    }
    //dothingshere
}
function2($product, $value) {
    $em = $this->getDoctrine()->getManager();
    $pattern = $em->getRepository('repo')->find($value)
    //return an array ['quantity'=>x]
    $this->function1Action(null, $product, $pattern);
}
</code>```

Solution 3 :
create an object Request inside function2.

I was trying to do solution 3 but i can't find how and i'm wondering wish one is 'the best'and if the solution 3 is not bad programming

答:
I finally did the option 1. Seems more logical and with that it can be used at other moment. Solution 2 seemed to be risky due to the null parameter who could have caused problem somewhere else and Solution 3 would have take much more ressources since i have to do a foreach inside my function2. So my solution looks like that : </p>

```<code>function1Action ($request Request, $product) {
    $quantity = $request->request->get('quantity')
    //dothingshere
}
function1bis($pattern, $product) {
    $quantity = $pattern['quantity']
    //dothingshere
}

function2Action($product, $value) {
    $em = $this->getDoctrine()->getManager();
    $pattern = $em->getRepository('repo')->find($value)
    //return an array ['quantity'=>x]
    $this->function1bis($pattern, $product)
}
</code>```

Title: Simulate a request inside a controller

Body:
I'm working in a symfony project and i have two function in my controller :

function1Action ($request Request, $product) {
    $quantity = $request->request->get('quantity')
    //dothingshere
}
function2Action($product, $value) {
    $em = $this->getDoctrine()->getManager();
    $pattern = $em->getRepository('repo')->find($value)
    //return an array ['quantity'=>x]
    $this->function1Action($pattern, $product)
}

usually the user call the function 1 (post request) with the good request parameter. So here all is good. My problem is sometimes, the function 2 is gonna be call and when it is i need to call function 1 but i don't have a proper Request and i want to send $pattern

So i found 3 solution

Solution 1 :
create function1bis who does the same thing as function1 but take an array as parameter

Solution 2 : Initiate a null value in my first function

function1 ($request Request, $product, $patt=null) {
    if(!$patt){
        $quantity = $request->request->get('quantity')
    }
    else {
        $quantity = $patt['quantity']
    }
    //dothingshere
}
function2($product, $value) {
    $em = $this->getDoctrine()->getManager();
    $pattern = $em->getRepository('repo')->find($value)
    //return an array ['quantity'=>x]
    $this->function1Action(null, $product, $pattern);
}

Solution 3 :
create an object Request inside function2.

I was trying to do solution 3 but i can't find how and i'm wondering wish one is 'the best'and if the solution 3 is not bad programming

Body:
I finally did the option 1. Seems more logical and with that it can be used at other moment. Solution 2 seemed to be risky due to the null parameter who could have caused problem somewhere else and Solution 3 would have take much more ressources since i have to do a foreach inside my function2. So my solution looks like that :

function1Action ($request Request, $product) {
    $quantity = $request->request->get('quantity')
    //dothingshere
}
function1bis($pattern, $product) {
    $quantity = $pattern['quantity']
    //dothingshere
}

function2Action($product, $value) {
    $em = $this->getDoctrine()->getManager();
    $pattern = $em->getRepository('repo')->find($value)
    //return an array ['quantity'=>x]
    $this->function1bis($pattern, $product)
}


问:
Hiding flash message after some seconds in codeigniter php
Hi i have tried with some script hiding the flash message once it is shown but it is not working.Displaying the flash message until i refresh the page.

Controller:

```<code>if ($this->email->send())
        {
           $this->session->set_flashdata('msg','<div class="alert alert-success text-center" id="successMessage">Thank you for contacting us we will get back to you soon!</div>');
            redirect('contact');
        }
        else
        {
            $this->session->set_flashdata('msg','<div class="alert alert-danger text-center">There is error in sending mail! Please try again later</div>');
            redirect('contact');
        }
</code>```

View:

```<code><script>
$(function() {
// setTimeout() function will be fired after page is loaded
// it will wait for 5 sec. and then will fire
// $("#successMessage").hide() function
setTimeout(function() {
    $(".alert-success").hide('blind', {}, 500)
}, 5000);
});
</script>
<div class="container">

<div class="row contactpageback">

        <div class="col-lg-6 contactuspagedetails">
            <form name="contact"  id="contactform" enctype="multipart/form-data" method="post" action="<?php echo base_url();?>contact">
            <?php echo  $this->session->flashdata('msg');?>
            <?php if(isset($msg)){?>
             <?php echo $msg;?>
               <?php } ?>
</code>```

答:
Is this what you want. Hope this helps you out.

$(function() {
// setTimeout() function will be fired after page is loaded
// it will wait for 5 sec. and then will fire
// $("#successMessage").hide() function

    $(".hide-it").hide(5000);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div>
  <h1 class='hide-it'>Flash Data value here</h1>
</div>
</body>
</html></code>```

Body:
Hi i have tried with some script hiding the flash message once it is shown but it is not working.Displaying the flash message until i refresh the page.

Controller:

if ($this->email->send())
        {
           $this->session->set_flashdata('msg','
Thank you for contacting us we will get back to you soon!
');
            redirect('contact');
        }
        else
        {
            $this->session->set_flashdata('msg','
There is error in sending mail! Please try again later
');
            redirect('contact');
        }

View:

            <form name="contact"  id="contactform" enctype="multipart/form-data" method="post" action="<?php echo base_url();?>contact">
            <?php echo  $this->session->flashdata('msg');?>
            <?php if(isset($msg)){?>
             <?php echo $msg;?>
               <?php } ?>

Body:
Is this what you want. Hope this helps you out.

$(function() {
// setTimeout() function will be fired after page is loaded
// it will wait for 5 sec. and then will fire
// $("#successMessage").hide() function

    $(".hide-it").hide(5000);

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div>
  <h1 class='hide-it'>Flash Data value here</h1>
</div>
</body>
</html>


问:
Smaller set of rules in FxCOp 10.0?
I have used FxCop 1.36 and I recently upgarded to FxCop 10.0. Using the same set of rules and the same set of assemblies now I got less warnings.

Have they removed some rules from the FxCop 10.0? If so, why?

答:
it's difficult to trac the different versions of fxcop. Is version 10 compatible with 3.6?
Can version 10 also profile .net 3.5 code?</p>

Title: Smaller set of rules in FxCOp 10.0?


问:
How do I make a placeholder for a 'select' box?
I'm using placeholders for text inputs which is working out just fine. But I'd like to use a placeholder for my selectboxes as well. Of course I can just use this code:

```<code><select>
    <option value="">Select your option</option>
    <option value="hurr">Durr</option>
</select>
</code>```

But the 'Select your option' is in black instead of lightgrey. So my solution could possibly be CSS-based. jQuery is fine too.

This only makes the option grey in the dropdown (so after clicking the arrow):

option:first {
    color: #999;
}
```

<p>The question is: How do people create placeholders in selectboxes? But it has already been answered, cheers.</p>

<p>And using this results in the selected value always being grey (even after selecting a real option):</p>

<pre class="lang-css prettyprint-override"><code>select {
    color: #999;
}
</code>```

答:
I wanted the SELECT to be grey until selected so for this piece of HTML:

```<code><select>
  <option value="" disabled selected>Select your option</option>
  <option value="hurr">Durr</option>
</select>
</code>```

I've added these CSS definitions:

```<code>select { color: grey; }
select:valid { color: black; }
</code>```

It works as expected in Chrome / Safari and maybe also in other browsers, but I haven't checked.

Body:
I'm using placeholders for text inputs which is working out just fine. But I'd like to use a placeholder for my selectboxes as well. Of course I can just use this code:

<select>
    <option value="">Select your option</option>
    <option value="hurr">Durr</option>
</select>

But the 'Select your option' is in black instead of lightgrey. So my solution could possibly be CSS-based. jQuery is fine too.

This only makes the option grey in the dropdown (so after clicking the arrow):

option:first {
    color: #999;
}

The question is: How do people create placeholders in selectboxes? But it has already been answered, cheers.

And using this results in the selected value always being grey (even after selecting a real option):

select {
    color: #999;
}

Body:
I wanted the SELECT to be grey until selected so for this piece of HTML:

<select>
  <option value="" disabled selected>Select your option</option>
  <option value="hurr">Durr</option>
</select>

I've added these CSS definitions:

select { color: grey; }
select:valid { color: black; }

It works as expected in Chrome / Safari and maybe also in other browsers, but I haven't checked.


问:
How to play .mp4 video as a background video in Android?
I have watched many tutorials but somethings wrong. I have simple mainactivity and there is a VideoView on the it's layout. I downloaded a video from youtube as a .mp4 file size is about 10 mb. I found a great sample about videoview on youtube as the following link.

https://www.youtube.com/watch?v=tPeDn18FrGY&t=75s

ublic class MainActivity extends AppCompatActivity {

```<code>private VideoView bgVideo;

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

        bgVideo=(VideoView) findViewById(R.id.bg_videoview);

        Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.bgvideo);

        bgVideo.setVideoURI(uri);
        bgVideo.start();

        bgVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
            }
        });
    }
}
</code>```

I use genymotion emulator. While i run the app i take "can't play this" error. And at the android monitor things like this.

```<code>06-07 03:16:28.675 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.675 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.692 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.692 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.709 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.709 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.742 2146-2146/com.sample E/MediaPlayer: Error (1,-32)
06-07 03:16:28.742 2146-2146/com.sample D/VideoView: Error: 1,-32
06-07 03:16:28.758 2146-2146/com.sample E/MediaPlayer: Error (1,-38)
06-07 03:16:28.758 2146-2146/com.sample D/VideoView: Error: 1,-38
06-07 03:16:29.526 2146-2146/com.sample I/Choreographer: Skipped 44 frames!  The application may be doing too much work on its main thread.
</code>```

How can i fix it ?

答:
Did you try to start bgVideo after onPreparedListener?

```<code>bgVideo.setVideoURI(uri);

        bgVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
            }
        });

        bgVideo.start();
</code>```

Also what API versions are you using?

Body:
I have watched many tutorials but somethings wrong. I have simple mainactivity and there is a VideoView on the it's layout. I downloaded a video from youtube as a .mp4 file size is about 10 mb. I found a great sample about videoview on youtube as the following link.

https://www.youtube.com/watch?v=tPeDn18FrGY&t=75s

ublic class MainActivity extends AppCompatActivity {

private VideoView bgVideo;

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

        bgVideo=(VideoView) findViewById(R.id.bg_videoview);

        Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.bgvideo);

        bgVideo.setVideoURI(uri);
        bgVideo.start();

        bgVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
            }
        });
    }
}

I use genymotion emulator. While i run the app i take "can't play this" error. And at the android monitor things like this.

06-07 03:16:28.675 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.675 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.692 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.692 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.709 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.709 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.742 2146-2146/com.sample E/MediaPlayer: Error (1,-32)
06-07 03:16:28.742 2146-2146/com.sample D/VideoView: Error: 1,-32
06-07 03:16:28.758 2146-2146/com.sample E/MediaPlayer: Error (1,-38)
06-07 03:16:28.758 2146-2146/com.sample D/VideoView: Error: 1,-38
06-07 03:16:29.526 2146-2146/com.sample I/Choreographer: Skipped 44 frames!  The application may be doing too much work on its main thread.

How can i fix it ?

Body:
Did you try to start bgVideo after onPreparedListener?

bgVideo.setVideoURI(uri);

        bgVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
            }
        });

        bgVideo.start();

Also what API versions are you using?


问:
mocking a constructor to see if it throws an exception
```<code>Java 8
</code>```

I have the following constructor I want to test using Mockito.

I want the test to throw an exception if a null is passed for the repository.

```<code>public PresenterImp(@Nonnull IRepository repository, IScheduler scheduler) {
        super(schedulerFactory);
        this.repository = Preconditions.checkNotNull(repository);
 }
</code>```

What would be the best way to do this? As my presenter is not a mock so I can’t use a when..

In my setup I do the following:

```<code>@Before
public void setup() throws Exception {

    repository = Mockito.mock(IRepository.class);

    iScheduler = Mockito.mock(IScheduler.class);
    viewContract = Mockito.mock(ViewContract.class);

    presenter = new PresenterImp(repository, iScheduler);

              optInNotificationPresenter.attachView(viewContract);
}
</code>```

Many thanks for any suggestions

答:
Can do it as:</p>

```<code> @Test(expected=NullPointerException.class )
 public void testNullCheck() throws Exception
           new PresenterImp(null, mock);

    }
</code>```

Body:
Java 8

I have the following constructor I want to test using Mockito.

I want the test to throw an exception if a null is passed for the repository.

public PresenterImp(@Nonnull IRepository repository, IScheduler scheduler) {
        super(schedulerFactory);
        this.repository = Preconditions.checkNotNull(repository);
 }

What would be the best way to do this? As my presenter is not a mock so I can’t use a when..

In my setup I do the following:

@Before
public void setup() throws Exception {

    repository = Mockito.mock(IRepository.class);

    iScheduler = Mockito.mock(IScheduler.class);
    viewContract = Mockito.mock(ViewContract.class);

    presenter = new PresenterImp(repository, iScheduler);

              optInNotificationPresenter.attachView(viewContract);
}

Many thanks for any suggestions

Body:
Can do it as:

 @Test(expected=NullPointerException.class )
 public void testNullCheck() throws Exception
           new PresenterImp(null, mock);

    }


问:
How to find a number that isn't there?
We have a custom number field on a training record, the number is recorded sequentially but there are gaps.  How do I find those gaps?  Consider this pseudocode

```<code>SELECT MIN(X)
FROM DUAL
WHERE X BETWEEN 1 AND 999999
  AND X NOT IN (SELECT AG_TRNID
                FROM PS_TRAINING
                WHERE AG_TRNID = X)
</code>```

This doesn't work, "X" is unknown.

Thanks!
Bruce

答:
Create all numbers from min(ag_trnid) to max(ag_trnid). From these remove the existing numbers:

```<code>with nums(num, maxnum) as
(
  select min(ag_trnid) as num, max(ag_trnid) as maxnum from ps_training
  union all
  select num + 1, maxnum from nums where num < maxnum
)
select num from nums
minus
select ag_trnid from ps_training;
</code>```

Start with 1 (or 0 for that matter) instead of min(ag_trnid), if you consider numbers before the minimum ag_trnid gaps, too.

Title: How to find a number that isn't there?

Body:
We have a custom number field on a training record, the number is recorded sequentially but there are gaps.  How do I find those gaps?  Consider this pseudocode

SELECT MIN(X)
FROM DUAL
WHERE X BETWEEN 1 AND 999999
  AND X NOT IN (SELECT AG_TRNID
                FROM PS_TRAINING
                WHERE AG_TRNID = X)

This doesn't work, "X" is unknown.

Thanks!
Bruce

Body:
Create all numbers from min(ag_trnid) to max(ag_trnid). From these remove the existing numbers:

with nums(num, maxnum) as
(
  select min(ag_trnid) as num, max(ag_trnid) as maxnum from ps_training
  union all
  select num + 1, maxnum from nums where num < maxnum
)
select num from nums
minus
select ag_trnid from ps_training;

Start with 1 (or 0 for that matter) instead of min(ag_trnid), if you consider numbers before the minimum ag_trnid gaps, too.


问:
GitLog Command with Path
I try to make a GitLog from projects in diffrent places.
Is there any solution to add a Path at the GitLog command ? </p>

<p>I try this but it doesnt work : </p>

```<code>git log --pretty=format:"%H \"%an\" %ad \"%s\"" --numstat --date=short -- Code/code1/git
</code>```

答:
Simply add --git-dir before log command

git --git-dir=Code/code1/.git log --pretty=format:"%H \"%an\" %ad \"%s\"" --numstat --date=short

Title: GitLog Command with Path

Body:
I try to make a GitLog from projects in diffrent places.
Is there any solution to add a Path at the GitLog command ?

I try this but it doesnt work :

git log --pretty=format:"%H \"%an\" %ad \"%s\"" --numstat --date=short -- Code/code1/git


问:
Why doesn't npm start run electron app?
I have the following in package.json for several electron apps:

```<code>  "name": "my-app",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
      "scripts": {
        "start": "electron ."
      },
</code>```

When I'd do npm start in the app folder, the corresponding app use to run. I just started getting the following output for all of my electron apps when using npm start:

electron .

module.js:471

      throw err;
      ^

Error: Cannot find module './'

      at Function.Module._resolveFilename (module.js:469:15)

      at Function.Module._load (module.js:417:25).

      at Module.require (module.js:497:17)

      at require (internal/module.js:20:19)

      at Object. (/Users/me/electron/my-app/node_modules/.bin/electron:3:16)

      at Module._compile (module.js:570:32)

      at Object.Module._extensions..js (module.js:579:10)

      at Module.load (module.js:487:32)

      at tryModuleLoad (module.js:446:12)

      at Function.Module._load (module.js:438:3)

  npm ERR! code ELIFECYCLE

  npm ERR! errno 1

  npm ERR! m1@1.0.0 start: electron .

  npm ERR! Exit status 1

  npm ERR!

  npm ERR! Failed at the m1@1.0.0 start script.

  npm ERR! This is probably not a problem with npm. There is

  likely additional logging output above.

However, I can do either of the following successfully on the command line:

```<code>electron main.js
electron .
</code>```

Anyone know what might have broken the package.json script? Or some other suggestions?

答: Delete the node_modules folder and then run npm install.

Title: Why doesn't npm start run electron app?

Body:
I have the following in package.json for several electron apps:

  "name": "my-app",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
      "scripts": {
        "start": "electron ."
      },

When I'd do npm start in the app folder, the corresponding app use to run. I just started getting the following output for all of my electron apps when using npm start:

electron .

module.js:471

      throw err;
      ^

Error: Cannot find module './'

      at Function.Module._resolveFilename (module.js:469:15)

      at Function.Module._load (module.js:417:25).

      at Module.require (module.js:497:17)

      at require (internal/module.js:20:19)

      at Object. (/Users/me/electron/my-app/node_modules/.bin/electron:3:16)

      at Module._compile (module.js:570:32)

      at Object.Module._extensions..js (module.js:579:10)

      at Module.load (module.js:487:32)

      at tryModuleLoad (module.js:446:12)

      at Function.Module._load (module.js:438:3)

  npm ERR! code ELIFECYCLE

  npm ERR! errno 1

  npm ERR! m1@1.0.0 start: electron .

  npm ERR! Exit status 1

  npm ERR!

  npm ERR! Failed at the m1@1.0.0 start script.

  npm ERR! This is probably not a problem with npm. There is

  likely additional logging output above.

However, I can do either of the following successfully on the command line:

electron main.js
electron .

Anyone know what might have broken the package.json script? Or some other suggestions?


问:
How to copy files automatically from Linux hadoop edge node to windows shared drive directly?
could you please share your thoughts/processes to copy files from linux machine to windows shared folder automatically using shell script and ftp/scp options ??

I knew that we can download the  files to local windows machine from linux using winscp and filezilla , but if we wants to copy files directly to windows shared drive.
Thanks in advance for the help .

答:
Mount the windows share on the Linux machine and set a cron job to copy the files if you need it automated.

If you have Ubuntu then follow this tutorial on mounting the shared drive.
 https://wiki.ubuntu.com/MountWindowsSharesPermanently

Or if your windows has a ssh server running you can run a cron job to copy over sftp. Using this tutorial

https://askleo.com/how_can_i_automate_an_sftp_transfer_between_two_servers/


问:
Unable to bring uploaded images into uploads file using php
After creating a form and typing the php code, i have a form where i am able to input a file, specifically an image, and without reciving any error messages, as well as getting the success message in my url, the image uploaded still can not be found in its destination folder.

Here is the HTML

```<code><form action="" class="navbar-form navbar-right" role="search">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="Find Art Here">
                    </div>
                    <button type="submit" class="btn btn-primary">Search</button>
                </form>
</code>```

and here's the php

```<code><?php
if (isset($_POST['submit'])) {
$file = $_FILES['file'];

$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];

$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));

$allow = array('jpg', 'jpeg', 'png', 'pdf');

if (in_array($fileActualExt, $allow)) {
    if($fileError === 0){
        if($fileSize < 5000000) {
            $fileNameNew = uniqid('', true).".".$fileActualExt;
        $fileDestination = 'uplaods/'.$fileNameNew;
        move_uploaded_file($fileTmpName, $fileDestination);
            header("Location: index.php?uploadsucess");
        } else{
            echo "Your file is too big";
        }
    } else {
        echo "There was an error uplaoding your file!";
    }
} else{
    echo "You cannot upload files of this type!";
}
</code>```

}

Code is based and modified from this video : https://www.youtube.com/watch?v=JaRq73y5MJk

Any help would be much appreciated!

答:
1) Add enctype="multipart/form-data" in your form tag.
2) fileDestination = 'uplaods/'.$fileNameNew;spelling mistake on file name. (If it is intentional, then my bad).
3) <input type='file'> type should be file.

Body:
After creating a form and typing the php code, i have a form where i am able to input a file, specifically an image, and without reciving any error messages, as well as getting the success message in my url, the image uploaded still can not be found in its destination folder.

Here is the HTML

<form action="" class="navbar-form navbar-right" role="search">

                        <input type="text" class="form-control" placeholder="Find Art Here">

                    <button type="submit" class="btn btn-primary">Search</button>
                </form>

and here's the php

<?php
if (isset($_POST['submit'])) {
$file = $_FILES['file'];

$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];

$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));

$allow = array('jpg', 'jpeg', 'png', 'pdf');

if (in_array($fileActualExt, $allow)) {
    if($fileError === 0){
        if($fileSize < 5000000) {
            $fileNameNew = uniqid('', true).".".$fileActualExt;
        $fileDestination = 'uplaods/'.$fileNameNew;
        move_uploaded_file($fileTmpName, $fileDestination);
            header("Location: index.php?uploadsucess");
        } else{
            echo "Your file is too big";
        }
    } else {
        echo "There was an error uplaoding your file!";
    }
} else{
    echo "You cannot upload files of this type!";
}

}

Code is based and modified from this video : https://www.youtube.com/watch?v=JaRq73y5MJk

Any help would be much appreciated!


问:
Self-join Query
Is it possible to do parent-child query just using join without looping through temporary table?

Database sample :

```<code>menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0002   Master Nominal      A0001   /master/nominal.aspx
A0003   Master Satuan Other A0001   /master/satuan.aspx
A0004   Master Kondisi      A0000   /master/kondisi.aspx
A0005   Master Tujuan       A0003   /master/tujuan.aspx
A0006   Master Item         A0003   /master/item.aspx
A0007   Master Warehouse    A0000   /master/warehouse.aspx
A0008   Master Kapal        A0006   /master/kapal.aspx
</code>```

Desired result if choosed uri = '/master/kapal.aspx' :

```<code>menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0003   Master Satuan Other A0001   /master/satuan.aspx
A0006   Master Item         A0003   /master/item.aspx
A0008   Master Kapal        A0006   /master/kapal.aspx
</code>```

Desired result if choosed uri = /master/tujuan.aspx' :

```<code>menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0005   Master Tujuan       A0003   /master/tujuan.aspx
</code>```

Sample query :

```<code>declare @menuid varchar(255) = 'menuid'
declare @parent varchar(255) = 'parent'
declare @temp_parent varchar(255)
declare @i smallint = 0

delete from temp_menu
while (@menuid <> @parent)
begin
  if(@i = 0)
  begin
    insert into temp_menu
    select * from menu where uri = '/master/kapal.aspx'
    select @menuid = menuid, @parent = parent from menu where uri = '/master/kapal.aspx'
    set @i = 1;
    end
  else
  begin
    insert into temp_menu
    select * from menu where menuid = @parent
    select @menuid = menuid, @temp_parent = parent from menu where menuid = @parent
    set @parent = @temp_parent;
    end
end
select * from temp_menu
</code>```

Sample with hieararchy :

```<code>A0000
|_______________________
|               |       |
A0001           A0004   A0007
|________
|       |
A0002   A0003
        |_______
        |       |
        A0005   A0006
                |
                A0008
</code>```

UPDATED :
I want to get all rows from  the longest branch possible from nodes parent to menuid and stopped if the parent same with menuid or there is no menuid match with parent.

ADDED WITH SCRIPT AND SAMPLES

```<code>IF OBJECT_ID('dbo.menu', 'U') IS NOT NULL
  DROP TABLE dbo.menu
GO

IF OBJECT_ID('dbo.temp_menu', 'U') IS NOT NULL
  DROP TABLE dbo.temp_menu
GO

IF OBJECTPROPERTY(object_id('dbo.sp_get_parent'), N'IsProcedure') = 1
  DROP PROCEDURE dbo.sp_get_parent
GO

create table dbo.menu (
menuid varchar(255)
, name varchar(255)
, parent varchar(255)
, uri varchar(255)
);

insert into dbo.menu (menuid, name, parent, uri)
values ('A0000', 'Master', 'A0000', '#')
, ('A0001', 'Rekening', 'A0000', '/master/rekening.aspx')
, ('A0002', 'Master Nominal', 'A0001', '/master/nominal.aspx')
, ('A0003', 'Master Satuan Other', 'A0001', '/master/satuan.aspx')
, ('A0004', 'Master Kondisi', 'A0000', '/master/kondisi.aspx')
, ('A0005', 'Master Tujuan', 'A0003', '/master/tujuan.aspx')
, ('A0006', 'Master Item', 'A0003', '/master/item.aspx')
, ('A0007', 'Master Warehouse', 'A0000', '/master/warehouse.aspx')
, ('A0008', 'Master Kapal', 'A0006', '/master/kapal.aspx');

create table dbo.temp_menu (
menuid varchar(255)
, name varchar(255)
, parent varchar(255)
, uri varchar(255)
);

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[sp_get_parent]
@uri VARCHAR (255)
AS

declare @menuid varchar(255) = 'menuid'
declare @parent varchar(255) = 'parent'
declare @temp_parent varchar(255)
declare @i smallint = 0

delete from temp_menu
while (@menuid <> @parent)
begin
  if(@i = 0)
  begin
    insert into temp_menu
    select * from menu where uri = @uri
    select @menuid = menuid, @parent = parent from menu where uri = @uri
    set @i = 1;
  end
  else
  begin
    insert into temp_menu
    select * from menu where menuid = @parent
    select @menuid = menuid, @temp_parent = parent from menu where menuid = @parent
    set @parent = @temp_parent;
  end
end
select * from temp_menu order by menuid asc
GO
</code>```

For desired sample above can try this query :

```<code>sp_get_parent '/master/kapal.aspx'
</code>```

AND

```<code>sp_get_parent '/master/tujuan.aspx'
</code>```

答:
```<code>declare @uri nvarchar(256) = '/master/kapal.aspx'

; with cte as (
    select MenuId, Name, Parent, Url
    , 1 reverseOrder
    from MyTable
    where url = @uri

    union all

    select b.MenuId, b.Name, b.Parent, b.Url
    , a.reverseOrder + 1
    from cte a
    inner join MyTable b
    where b.MenuId = a.Parent
    and b.MenuId = a.MenuId --don't repeat ourselves after reaching the root
)
select MenuId, Name, Parent, Url
from cte
ordre by reverseOrder desc
</code>```

Update

For the second part of your question (i.e. longest branch), try:

```<code>; with cte as (
    select MenuId, Name, Parent, Url
    , 1 branchLength
    , cast(MenuId as nvarchar(max)) branchPath
    from MyTable
    where Parent = menuid --i.e. top level / root elements

    union all

    select b.MenuId, b.Name, b.Parent, b.Url
    , a.branchLength + 1
    , a.branchPath + '\' + cast(b.MenuId as nvarchar(max)) branchPath
    from cte a
    inner join MyTable b
    where b.Parent = a.MenuId --i.e. branch of previous result
    and b.MenuId != a.MenuId --ensure we don't repeat ourselves
)
select a.MenuId, a.Name, a.Parent, a.Url
from cte a
inner join (
    select top 1 branchPath
    from cte
    order by branchLength Desc
) b
on b.branchPath like a.branchPath + '%' --gives us an easy way to traverse back up the tree, without recording every possible paths' inheritance / by using a directory structure
ordre by a.branchLength desc
</code>```

Title: Self-join Query

Body:
Is it possible to do parent-child query just using join without looping through temporary table?

Database sample :

menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0002   Master Nominal      A0001   /master/nominal.aspx
A0003   Master Satuan Other A0001   /master/satuan.aspx
A0004   Master Kondisi      A0000   /master/kondisi.aspx
A0005   Master Tujuan       A0003   /master/tujuan.aspx
A0006   Master Item         A0003   /master/item.aspx
A0007   Master Warehouse    A0000   /master/warehouse.aspx
A0008   Master Kapal        A0006   /master/kapal.aspx

Desired result if choosed uri = '/master/kapal.aspx' :

menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0003   Master Satuan Other A0001   /master/satuan.aspx
A0006   Master Item         A0003   /master/item.aspx
A0008   Master Kapal        A0006   /master/kapal.aspx

Desired result if choosed uri = /master/tujuan.aspx' :

menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0005   Master Tujuan       A0003   /master/tujuan.aspx

Sample query :

declare @menuid varchar(255) = 'menuid'
declare @parent varchar(255) = 'parent'
declare @temp_parent varchar(255)
declare @i smallint = 0

delete from temp_menu
while (@menuid <> @parent)
begin
  if(@i = 0)
  begin
    insert into temp_menu
    select * from menu where uri = '/master/kapal.aspx'
    select @menuid = menuid, @parent = parent from menu where uri = '/master/kapal.aspx'
    set @i = 1;
    end
  else
  begin
    insert into temp_menu
    select * from menu where menuid = @parent
    select @menuid = menuid, @temp_parent = parent from menu where menuid = @parent
    set @parent = @temp_parent;
    end
end
select * from temp_menu

Sample with hieararchy :

A0000
|_______________________
|               |       |
A0001           A0004   A0007
|________
|       |
A0002   A0003
        |_______
        |       |
        A0005   A0006
                |
                A0008

UPDATED :
I want to get all rows from  the longest branch possible from nodes parent to menuid and stopped if the parent same with menuid or there is no menuid match with parent.

ADDED WITH SCRIPT AND SAMPLES

IF OBJECT_ID('dbo.menu', 'U') IS NOT NULL
  DROP TABLE dbo.menu
GO

IF OBJECT_ID('dbo.temp_menu', 'U') IS NOT NULL
  DROP TABLE dbo.temp_menu
GO

IF OBJECTPROPERTY(object_id('dbo.sp_get_parent'), N'IsProcedure') = 1
  DROP PROCEDURE dbo.sp_get_parent
GO

create table dbo.menu (
menuid varchar(255)
, name varchar(255)
, parent varchar(255)
, uri varchar(255)
);

insert into dbo.menu (menuid, name, parent, uri)
values ('A0000', 'Master', 'A0000', '#')
, ('A0001', 'Rekening', 'A0000', '/master/rekening.aspx')
, ('A0002', 'Master Nominal', 'A0001', '/master/nominal.aspx')
, ('A0003', 'Master Satuan Other', 'A0001', '/master/satuan.aspx')
, ('A0004', 'Master Kondisi', 'A0000', '/master/kondisi.aspx')
, ('A0005', 'Master Tujuan', 'A0003', '/master/tujuan.aspx')
, ('A0006', 'Master Item', 'A0003', '/master/item.aspx')
, ('A0007', 'Master Warehouse', 'A0000', '/master/warehouse.aspx')
, ('A0008', 'Master Kapal', 'A0006', '/master/kapal.aspx');

create table dbo.temp_menu (
menuid varchar(255)
, name varchar(255)
, parent varchar(255)
, uri varchar(255)
);

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[sp_get_parent]
@uri VARCHAR (255)
AS

declare @menuid varchar(255) = 'menuid'
declare @parent varchar(255) = 'parent'
declare @temp_parent varchar(255)
declare @i smallint = 0

delete from temp_menu
while (@menuid <> @parent)
begin
  if(@i = 0)
  begin
    insert into temp_menu
    select * from menu where uri = @uri
    select @menuid = menuid, @parent = parent from menu where uri = @uri
    set @i = 1;
  end
  else
  begin
    insert into temp_menu
    select * from menu where menuid = @parent
    select @menuid = menuid, @temp_parent = parent from menu where menuid = @parent
    set @parent = @temp_parent;
  end
end
select * from temp_menu order by menuid asc
GO

For desired sample above can try this query :

sp_get_parent '/master/kapal.aspx'

AND

sp_get_parent '/master/tujuan.aspx'

Body:
declare @uri nvarchar(256) = '/master/kapal.aspx'

; with cte as (
    select MenuId, Name, Parent, Url
    , 1 reverseOrder
    from MyTable
    where url = @uri

    union all

    select b.MenuId, b.Name, b.Parent, b.Url
    , a.reverseOrder + 1
    from cte a
    inner join MyTable b
    where b.MenuId = a.Parent
    and b.MenuId = a.MenuId --don't repeat ourselves after reaching the root
)
select MenuId, Name, Parent, Url
from cte
ordre by reverseOrder desc

Update

For the second part of your question (i.e. longest branch), try:

; with cte as (
    select MenuId, Name, Parent, Url
    , 1 branchLength
    , cast(MenuId as nvarchar(max)) branchPath
    from MyTable
    where Parent = menuid --i.e. top level / root elements

    union all

    select b.MenuId, b.Name, b.Parent, b.Url
    , a.branchLength + 1
    , a.branchPath + '\' + cast(b.MenuId as nvarchar(max)) branchPath
    from cte a
    inner join MyTable b
    where b.Parent = a.MenuId --i.e. branch of previous result
    and b.MenuId != a.MenuId --ensure we don't repeat ourselves
)
select a.MenuId, a.Name, a.Parent, a.Url
from cte a
inner join (
    select top 1 branchPath
    from cte
    order by branchLength Desc
) b
on b.branchPath like a.branchPath + '%' --gives us an easy way to traverse back up the tree, without recording every possible paths' inheritance / by using a directory structure
ordre by a.branchLength desc