问:
ng cli generate component with module broken
I'm using the ng cli for the first time. I'm trying to make a new module ('foo') and a new component ('bar') under the foo module. Though, how I think I'm supposed to do it in ng cli doesn't seem to work:

```<code>mbp:my-new-app chris$ ng g m foo
installing module
create src/app/foo/foo.module.ts

mbp:my-new-app chris$ ng g c bar -m foo
installing component
create src/app/bar/bar.component.scss
create src/app/bar/bar.component.html
create src/app/bar/bar.component.spec.ts
create src/app/bar/bar.component.ts

EISDIR: illegal operation on a directory, read
Error: EISDIR: illegal operation on a directory, read
at Error (native)
at Object.fs.readSync (fs.js:732:19)
at tryReadSync (fs.js:487:20)
at Object.fs.readFileSync (fs.js:535:19)
at Class.afterInstall (/Users/chris/code/my-new-app/node_modules/@angular/cli/blueprints/component/index.js:209:34)
at tryCatch (/Users/chris/code/my-new-app/node_modules/rsvp/dist/rsvp.js:539:12)
at invokeCallback (/Users/chris/code/my-new-app/node_modules/rsvp/dist/rsvp.js:554:13)
at publish (/Users/chris/code/my-new-app/node_modules/rsvp/dist/rsvp.js:522:7)
at flush (/Users/chris/code/my-new-app/node_modules/rsvp/dist/rsvp.js:2414:5)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
</code>```

ng cli version:

```<code>mbp:my-new-app chris$ ng version
    _                      _                 ____ _     ___
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
               |___/
@angular/cli: 1.0.0
node: 6.10.1
os: darwin x64
@angular/common: 4.0.1
@angular/compiler: 4.0.1
@angular/core: 4.0.1
@angular/forms: 4.0.1
@angular/http: 4.0.1
@angular/platform-browser: 4.0.1
@angular/platform-browser-dynamic: 4.0.1
@angular/router: 4.0.1
@angular/cli: 1.0.0
@angular/compiler-cli: 4.0.1
</code>```

Am I doing using this wrong? I haven't found documentation specifically on this feature.

Thanks!

答:
instead of running

```<code>ng g c bar -m foo
</code>```

try to run (without -m)

```<code>ng g c foo/bar
</code>```

if you want to reference a module, which should export/import your new component, you should provide a relative path to this module, like:

```<code>ng g c bar -m foo/foo.module
</code>```

in this case bar component will be imported/exported by foo.module, but located under src/app.

EASDIR error occurred because you provided a directory (foo) instead of file (foo/foo.module)

as answered for example here:

EISDIR means that the target of the operation is a directory in reality but that the expected filetype of the target is something other than a directory.

Body:
I'm using the ng cli for the first time. I'm trying to make a new module ('foo') and a new component ('bar') under the foo module. Though, how I think I'm supposed to do it in ng cli doesn't seem to work:

mbp:my-new-app chris$ ng g m foo
installing module
create src/app/foo/foo.module.ts

mbp:my-new-app chris$ ng g c bar -m foo
installing component
create src/app/bar/bar.component.scss
create src/app/bar/bar.component.html
create src/app/bar/bar.component.spec.ts
create src/app/bar/bar.component.ts

EISDIR: illegal operation on a directory, read
Error: EISDIR: illegal operation on a directory, read
at Error (native)
at Object.fs.readSync (fs.js:732:19)
at tryReadSync (fs.js:487:20)
at Object.fs.readFileSync (fs.js:535:19)
at Class.afterInstall (/Users/chris/code/my-new-app/node_modules/@angular/cli/blueprints/component/index.js:209:34)
at tryCatch (/Users/chris/code/my-new-app/node_modules/rsvp/dist/rsvp.js:539:12)
at invokeCallback (/Users/chris/code/my-new-app/node_modules/rsvp/dist/rsvp.js:554:13)
at publish (/Users/chris/code/my-new-app/node_modules/rsvp/dist/rsvp.js:522:7)
at flush (/Users/chris/code/my-new-app/node_modules/rsvp/dist/rsvp.js:2414:5)
at _combinedTickCallback (internal/process/next_tick.js:73:7)

ng cli version:

mbp:my-new-app chris$ ng version
    _                      _                 ____ _     ___
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
               |___/
@angular/cli: 1.0.0
node: 6.10.1
os: darwin x64
@angular/common: 4.0.1
@angular/compiler: 4.0.1
@angular/core: 4.0.1
@angular/forms: 4.0.1
@angular/http: 4.0.1
@angular/platform-browser: 4.0.1
@angular/platform-browser-dynamic: 4.0.1
@angular/router: 4.0.1
@angular/cli: 1.0.0
@angular/compiler-cli: 4.0.1

Am I doing using this wrong? I haven't found documentation specifically on this feature.

Thanks!

Body:
instead of running

ng g c bar -m foo

try to run (without -m)

ng g c foo/bar

if you want to reference a module, which should export/import your new component, you should provide a relative path to this module, like:

ng g c bar -m foo/foo.module

in this case bar component will be imported/exported by foo.module, but located under src/app.

EASDIR error occurred because you provided a directory (foo) instead of file (foo/foo.module)

as answered for example here:

EISDIR means that the target of the operation is a directory in reality but that the expected filetype of the target is something other than a directory.


来源: stackexchange

问:
C# Method overload resolution not selecting concrete generic override
This complete C# program illustrates the issue:

```<code>public abstract class Executor<T>
{
    public abstract void Execute(T item);
}

class StringExecutor : Executor<string>
{
    public void Execute(object item)
    {
        // why does this method call back into itself instead of binding
        // to the more specific "string" overload.
        this.Execute((string)item);
    }

    public override void Execute(string item) { }
}

class Program
{
    static void Main(string[] args)
    {
        object item = "value";
        new StringExecutor()
            // stack overflow
            .Execute(item);
    }
}
</code>```

I ran into a StackOverlowException that I traced back to this call pattern where I was trying to forward calls to a more specific overload. To my surprise, the invocation was not selecting the more specific overload however, but calling back into itself. It clearly has something to do with the base type being generic, but I don't understand why it wouldn't select the Execute(string) overload.

Does anyone have any insight into this?

The above code was simplified to show the pattern, the actual structure is a bit more complicated, but the issue is the same.

答:
As other answers have noted, this is by design.

Let's consider a less complicated example:

```<code>class Animal
{
  public virtual void Eat(Apple a) { ... }
}
class Giraffe : Animal
{
  public void Eat(Food f) { ... }
  public override void Eat(Apple a) { ... }
}
</code>```

The question is why giraffe.Eat(apple) resolves to Giraffe.Eat(Food) and not the virtual Animal.Eat(Apple).

This is a consequence of two rules:

(1) The type of the receiver is more important than the type of any argument when resolving overloads.

I hope it is clear why this must be the case. The person writing the derived class has strictly more knowledge than the person writing the base class, because the person writing the derived class used the base class, and not vice versa.

The person who wrote Giraffe said "I have a way for a Giraffe to eat any food" and that requires special knowledge of the internals of giraffe digestion. That information is not present in the base class implementation, which only knows how to eat apples.

So overload resolution should always prioritize choosing an applicable method of a derived class over choosing a method of a base class, regardless of the betterness of the argument type conversions.

(2) Choosing to override or not override a virtual method is not part of the public surface area of a class. That's a private implementation detail.  Therefore no decision must be made when doing overload resolution that would change depending on whether or not a method is overridden.

Overload resolution must never say "I'm going to choose virtual Animal.Eat(Apple) because it was overridden".

Now, you might well say "OK, suppose I am inside Giraffe when I am making the call."  Code inside Giraffe has all the knowledge of private implementation details, right? So it could make the decision to call virtual Animal.Eat(Apple) instead of Giraffe.Eat(Food) when faced with giraffe.Eat(apple), right? Because it knows that there is an implementation that understands the needs of giraffes that eat apples.

That's a cure worse than the disease.  Now we have a situation where identical code has different behaviour depending on where it is run!  You can imagine having a call to giraffe.Eat(apple) outside of the class, refactor it so that it is inside of the class, and suddenly observable behaviour changes!

Or, you might say, hey, I realize that my Giraffe logic is actually sufficiently general to move to a base class, but not to Animal, so I am going to refactor my Giraffe code to:

```<code>class Mammal : Animal
{
  public void Eat(Food f) { ... }
  public override void Eat(Apple a) { ... }
}
class Giraffe : Mammal
{
  ...
}
</code>```

And now all calls to giraffe.Eat(apple) inside Giraffe suddenly have different overload resolution behaviour after the refactoring?  That would be very unexpected!

C# is a pit-of-success language; we want very much to make sure that simple refactorings like changing where in a hierarchy a method is overridden do not cause subtle changes in behaviour.

Summing up:

Overload resolution prioritizes receivers over other arguments because calling specialized code that knows the internals of the receiver is better than calling more general code that does not.

Whether and where a method is overridden is not considered during overload resolution; all methods are treated as though they were never overridden for purposes of overload resolution. It's an implementation detail, not part of the surface of the type.

Overload resolution problems are solved -- modulo accessibility of course! -- the same way no matter where the problem occurs in the code. We do not have one algorithm for resolution where the receiver is of the type of the containing code, and another for when the call is in a different class.

Additional thoughts on related issues can be found here: https://ericlippert.com/2013/12/23/closer-is-better/ and here https://blogs.msdn.microsoft.com/ericlippert/2007/09/04/future-breaking-changes-part-three/

ContentLicense: CC BY-SA 3.0

Body:
This complete C# program illustrates the issue:

public abstract class Executor<T>
{
    public abstract void Execute(T item);
}

class StringExecutor : Executor<string>
{
    public void Execute(object item)
    {
        // why does this method call back into itself instead of binding
        // to the more specific "string" overload.
        this.Execute((string)item);
    }

    public override void Execute(string item) { }
}

class Program
{
    static void Main(string[] args)
    {
        object item = "value";
        new StringExecutor()
            // stack overflow
            .Execute(item);
    }
}

I ran into a StackOverlowException that I traced back to this call pattern where I was trying to forward calls to a more specific overload. To my surprise, the invocation was not selecting the more specific overload however, but calling back into itself. It clearly has something to do with the base type being generic, but I don't understand why it wouldn't select the Execute(string) overload.

Does anyone have any insight into this?

The above code was simplified to show the pattern, the actual structure is a bit more complicated, but the issue is the same.

Body:
As other answers have noted, this is by design.

Let's consider a less complicated example:

class Animal
{
  public virtual void Eat(Apple a) { ... }
}
class Giraffe : Animal
{
  public void Eat(Food f) { ... }
  public override void Eat(Apple a) { ... }
}

The question is why giraffe.Eat(apple) resolves to Giraffe.Eat(Food) and not the virtual Animal.Eat(Apple).

This is a consequence of two rules:

(1) The type of the receiver is more important than the type of any argument when resolving overloads.

I hope it is clear why this must be the case. The person writing the derived class has strictly more knowledge than the person writing the base class, because the person writing the derived class used the base class, and not vice versa.

The person who wrote Giraffe said "I have a way for a Giraffe to eat any food" and that requires special knowledge of the internals of giraffe digestion. That information is not present in the base class implementation, which only knows how to eat apples.

So overload resolution should always prioritize choosing an applicable method of a derived class over choosing a method of a base class, regardless of the betterness of the argument type conversions.

(2) Choosing to override or not override a virtual method is not part of the public surface area of a class. That's a private implementation detail.  Therefore no decision must be made when doing overload resolution that would change depending on whether or not a method is overridden.

Overload resolution must never say "I'm going to choose virtual Animal.Eat(Apple) because it was overridden".

Now, you might well say "OK, suppose I am inside Giraffe when I am making the call."  Code inside Giraffe has all the knowledge of private implementation details, right? So it could make the decision to call virtual Animal.Eat(Apple) instead of Giraffe.Eat(Food) when faced with giraffe.Eat(apple), right? Because it knows that there is an implementation that understands the needs of giraffes that eat apples.

That's a cure worse than the disease.  Now we have a situation where identical code has different behaviour depending on where it is run!  You can imagine having a call to giraffe.Eat(apple) outside of the class, refactor it so that it is inside of the class, and suddenly observable behaviour changes!

Or, you might say, hey, I realize that my Giraffe logic is actually sufficiently general to move to a base class, but not to Animal, so I am going to refactor my Giraffe code to:

class Mammal : Animal
{
  public void Eat(Food f) { ... }
  public override void Eat(Apple a) { ... }
}
class Giraffe : Mammal
{
  ...
}

And now all calls to giraffe.Eat(apple) inside Giraffe suddenly have different overload resolution behaviour after the refactoring?  That would be very unexpected!

C# is a pit-of-success language; we want very much to make sure that simple refactorings like changing where in a hierarchy a method is overridden do not cause subtle changes in behaviour.

Summing up:

Overload resolution prioritizes receivers over other arguments because calling specialized code that knows the internals of the receiver is better than calling more general code that does not.

Whether and where a method is overridden is not considered during overload resolution; all methods are treated as though they were never overridden for purposes of overload resolution. It's an implementation detail, not part of the surface of the type.

Overload resolution problems are solved -- modulo accessibility of course! -- the same way no matter where the problem occurs in the code. We do not have one algorithm for resolution where the receiver is of the type of the containing code, and another for when the call is in a different class.

Additional thoughts on related issues can be found here: https://ericlippert.com/2013/12/23/closer-is-better/ and here https://blogs.msdn.microsoft.com/ericlippert/2007/09/04/future-breaking-changes-part-three/


问:
Doesn't work http request from custom components/services in jHipster application
When I create new components and services in app create by jHipster generator, http requests doesn't work in my components/services.

Sorry if I some skip and make wrong, but in the simple angular app this(http) works fine.

I've created simple example and pushed to this repository
https://github.com/SerhiiTsybulskyi/jhiHttpIssue
See this file: https://github.com/SerhiiTsybulskyi/jhiHttpIssue/blob/master/src/main/webapp/app/test/test.component.ts

What are doing wrong?

答:
http.get() returns an Observable, if you don't subscribe to it the request is not sent. See the documentation

```<code>  onClick() {
    this.http.get('management/health').map((res) => res.json()).subscribe();
  }
</code>```

Body:
http.get() returns an Observable, if you don't subscribe to it the request is not sent. See the documentation

  onClick() {
    this.http.get('management/health').map((res) => res.json()).subscribe();
  }


问:
"#include" a text file in a C program as a char[]
Is there a way to include an entire text file as a string in a C program at compile-time?

something like:

file.txt:

```<code>This is
a little
text file
</code>```

main.c:

```<code>#include <stdio.h>
int main(void) {
   #blackmagicinclude("file.txt", content)
   /*
   equiv: char[] content = "This is\na little\ntext file";
   */
   printf("%s", content);
}
</code>```

obtaining a little program that prints on stdout "This is
a little
text file"

At the moment I used an hackish python script, but it's butt-ugly and limited to only one variable name, can you tell me another way to do it?

答:
I had similar issues, and for small files the aforementioned solution of Johannes Schaub worked like a charm for me.

However, for files that are a bit larger, it ran into issues with the character array limit of the compiler. Therefore, I wrote a small encoder application that converts file content into a 2D character array of equally sized chunks (and possibly padding zeros). It produces output textfiles with 2D array data like this:

```<code>const char main_js_file_data[8][4]= {
    {'\x69','\x73','\x20','\0'},
    {'\x69','\x73','\x20','\0'},
    {'\x61','\x20','\x74','\0'},
    {'\x65','\x73','\x74','\0'},
    {'\x20','\x66','\x6f','\0'},
    {'\x72','\x20','\x79','\0'},
    {'\x6f','\x75','\xd','\0'},
    {'\xa','\0','\0','\0'}};
</code>```

where 4 is actually a variable MAX_CHARS_PER_ARRAY in the encoder. The file with the resulting C code, called, for example "main_js_file_data.h" can then easily be inlined into the C++ application, for example like this:

```<code>#include "main_js_file_data.h"
</code>```

Here is the source code of the encoder:

```<code>#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>

#define MAX_CHARS_PER_ARRAY 2048

int main(int argc, char * argv[])
{
    // three parameters: input filename, output filename, variable name
    if (argc < 4)
    {
        return 1;
    }

    // buffer data, packaged into chunks
    std::vector<char> bufferedData;

    // open input file, in binary mode
    {
        std::ifstream fStr(argv[1], std::ios::binary);
        if (!fStr.is_open())
        {
            return 1;
        }

        bufferedData.assign(std::istreambuf_iterator<char>(fStr),
                            std::istreambuf_iterator<char>()     );
    }

    // write output text file, containing a variable declaration,
    // which will be a fixed-size two-dimensional plain array
    {
        std::ofstream fStr(argv[2]);
        if (!fStr.is_open())
        {
            return 1;
        }
        const std::size_t numChunks = std::size_t(std::ceil(double(bufferedData.size()) / (MAX_CHARS_PER_ARRAY - 1)));
        fStr << "const char " << argv[3] << "[" << numChunks           << "]"    <<
                                            "[" << MAX_CHARS_PER_ARRAY << "]= {" << std::endl;
        std::size_t count = 0;
        fStr << std::hex;
        while (count < bufferedData.size())
        {
            std::size_t n = 0;
            fStr << "{";
            for (; n < MAX_CHARS_PER_ARRAY - 1 && count < bufferedData.size(); ++n)
            {
                fStr << "'\\x" << int(unsigned char(bufferedData[count++])) << "',";
            }
            // fill missing part to reach fixed chunk size with zero entries
            for (std::size_t j = 0; j < (MAX_CHARS_PER_ARRAY - 1) - n; ++j)
            {
                fStr << "'\\0',";
            }
            fStr << "'\\0'}";
            if (count < bufferedData.size())
            {
                fStr << ",\n";
            }
        }
        fStr << "};\n";
    }

    return 0;
}
</code>```

OwnerDisplayName: ZeD

ContentLicense: CC BY-SA 2.5

Body:
Is there a way to include an entire text file as a string in a C program at compile-time?

something like:

file.txt:

This is
a little
text file

main.c:

#include <stdio.h>
int main(void) {
   #blackmagicinclude("file.txt", content)
   /*
   equiv: char[] content = "This is\na little\ntext file";
   */
   printf("%s", content);
}

obtaining a little program that prints on stdout "This is
a little
text file"

At the moment I used an hackish python script, but it's butt-ugly and limited to only one variable name, can you tell me another way to do it?

Body:
I had similar issues, and for small files the aforementioned solution of Johannes Schaub worked like a charm for me.

However, for files that are a bit larger, it ran into issues with the character array limit of the compiler. Therefore, I wrote a small encoder application that converts file content into a 2D character array of equally sized chunks (and possibly padding zeros). It produces output textfiles with 2D array data like this:

const char main_js_file_data[8][4]= {
    {'\x69','\x73','\x20','\0'},
    {'\x69','\x73','\x20','\0'},
    {'\x61','\x20','\x74','\0'},
    {'\x65','\x73','\x74','\0'},
    {'\x20','\x66','\x6f','\0'},
    {'\x72','\x20','\x79','\0'},
    {'\x6f','\x75','\xd','\0'},
    {'\xa','\0','\0','\0'}};

where 4 is actually a variable MAX_CHARS_PER_ARRAY in the encoder. The file with the resulting C code, called, for example "main_js_file_data.h" can then easily be inlined into the C++ application, for example like this:

#include "main_js_file_data.h"

Here is the source code of the encoder:

#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>

#define MAX_CHARS_PER_ARRAY 2048

int main(int argc, char * argv[])
{
    // three parameters: input filename, output filename, variable name
    if (argc < 4)
    {
        return 1;
    }

    // buffer data, packaged into chunks
    std::vector<char> bufferedData;

    // open input file, in binary mode
    {
        std::ifstream fStr(argv[1], std::ios::binary);
        if (!fStr.is_open())
        {
            return 1;
        }

        bufferedData.assign(std::istreambuf_iterator<char>(fStr),
                            std::istreambuf_iterator<char>()     );
    }

    // write output text file, containing a variable declaration,
    // which will be a fixed-size two-dimensional plain array
    {
        std::ofstream fStr(argv[2]);
        if (!fStr.is_open())
        {
            return 1;
        }
        const std::size_t numChunks = std::size_t(std::ceil(double(bufferedData.size()) / (MAX_CHARS_PER_ARRAY - 1)));
        fStr << "const char " << argv[3] << "[" << numChunks           << "]"    <<
                                            "[" << MAX_CHARS_PER_ARRAY << "]= {" << std::endl;
        std::size_t count = 0;
        fStr << std::hex;
        while (count < bufferedData.size())
        {
            std::size_t n = 0;
            fStr << "{";
            for (; n < MAX_CHARS_PER_ARRAY - 1 && count < bufferedData.size(); ++n)
            {
                fStr << "'\\x" << int(unsigned char(bufferedData[count++])) << "',";
            }
            // fill missing part to reach fixed chunk size with zero entries
            for (std::size_t j = 0; j < (MAX_CHARS_PER_ARRAY - 1) - n; ++j)
            {
                fStr << "'\\0',";
            }
            fStr << "'\\0'}";
            if (count < bufferedData.size())
            {
                fStr << ",\n";
            }
        }
        fStr << "};\n";
    }

    return 0;
}


问:
Check checkbox from antoher activity
I was wondering if anyone could tell me how I could check a checkBox in an  activity from another activity.

I'm making a homework app and I want to put a check next to the questions that have been completed.

So the first activity has a list of questions and next to them are unchecked boxes. When you click a question, the app takes you to the second activity. In the second activity, I want to check the box of the question that was completed.

答:
You can save checked check question to a bundle and pass it as extra to your second activity through intent and read it from that intent inside your second activity

In your first activity do something like this

```<code>public class FirstActivity extends Activity {

     public static final String EXTRA_CHECKED_QUESTION = "Checked Question";

     // other codes here

     private void startSecondActivity() {
         String checkedQuestion = getCheckedQuestion(); // a method to get checked question
         Intent intent = new Intent(this, SecondActivity.class);
         intent.putExtra(FirstActivity.EXTRA_CHECKED_QUESTION, checkedQuestion);
         startActivity(intent);
     }
}
</code>```

then in your second activity

```<code>public class SecondActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstance) {
        // other codes

        String checkedQuestion = getIntent().getStringExtra(FirstActivity.EXTRA_CHECKED_QUESTION);
        // do whatever you want with checkQuestion
    }
}
</code>```

Please note that the string which you pass as first parameter to putExtra() method in FirstActivity, should be same as the string you are using with getStringExtra() to retrieve your extra in SecondActivity, otherwise you can not retrieve your passed extra in SecondActivity.

Also, I did not write these codes inside idea, so there might be syntax error

Read more about intent here

Title: Check checkbox from antoher activity

Body:
You can save checked check question to a bundle and pass it as extra to your second activity through intent and read it from that intent inside your second activity

In your first activity do something like this

public class FirstActivity extends Activity {

     public static final String EXTRA_CHECKED_QUESTION = "Checked Question";

     // other codes here

     private void startSecondActivity() {
         String checkedQuestion = getCheckedQuestion(); // a method to get checked question
         Intent intent = new Intent(this, SecondActivity.class);
         intent.putExtra(FirstActivity.EXTRA_CHECKED_QUESTION, checkedQuestion);
         startActivity(intent);
     }
}

then in your second activity

public class SecondActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstance) {
        // other codes

        String checkedQuestion = getIntent().getStringExtra(FirstActivity.EXTRA_CHECKED_QUESTION);
        // do whatever you want with checkQuestion
    }
}

Please note that the string which you pass as first parameter to putExtra() method in FirstActivity, should be same as the string you are using with getStringExtra() to retrieve your extra in SecondActivity, otherwise you can not retrieve your passed extra in SecondActivity.

Also, I did not write these codes inside idea, so there might be syntax error

Read more about intent here


问:
How to ignore white space when comparing source in Visual Studio / TFS?
The compare tool in Visual Source Safe (pre TFS) had a handy checkbox to select "Ignore White Space".

Now we are using TFS with Visual Studio 2010, and the compare dialog no longer has this option. (A ridiculous oversight from Microsoft!)

So, is it possible somehow to work around this?

答:
In VS2015 it's possible to "ignore white space" when comparing clicking a little icon with the = symbol.

Go to "View/Toolbars/Compare Files". In the toolbar click on "Ignore trim whitespace".

Update 2020: we struggled a lot solving conflicts with VS comparison tool and the Tortoise SVN one, so after a research we decided to install Devart Code Compare (free version) which has integration with VS2015/2017/2019, SVN (Tortoise and Ankh), TFS, Mercurial, GIT, etc. and Windows Explorer, so no more nightmares/confusion between different comparisons tools. Give it a try, it's extremely useful. It has also Merge to solve conflicts and Folder diff, which is really useful when SVN does not merge for some reason. Also, clicking on the left/right arrows to copy the changes is a feature that I really like.

Below VS image is from Devart website, but in my case I setup Code Compare to open it outside VS instead of embedded, I think it behaves better. And in VS Options >  Source Control > Subversion Environment, I have this:

ContentLicense: CC BY-SA 4.0


问:
While loop - Beginner
I am a beginner in C (and programming) and I found mylsef with this problem.

The code compile, but it return to me until number 11. I set the "While loop" to stop when is "<= 10". So doesn't make much sense to me.

thanks in advance =).

#include <stdio.h>

int main (void)

{
    int n;

    n = 0;

    while (n <= 10) {
    n++;
    printf("%i\n", n);

}

return 0;

}
```

答: Because you set n to 0 and you iterate until 10 in your while loop, the loop iterates 11 times. Try n < 10!</p>

Title: While loop - Beginner


问:
python scatter plot legend border color refuses to change
This code might be useful to others struggling w/ scatter plots in matplotlib for python.  It works except for this one problem.  I have poured over many help topics on this site and elsewhere.  As per comments in my code, there are different ways to set the edgecolor on the border of the legend and yet none of them are working for me.  Python always throws an error indicating I am trying to set something that does not exist.

Can anyone see what the fix is here?

```<code>%matplotlib inline
import matplotlib.pyplot as plt

stLen = iris[Species=='setosa']['Petal.Length']
stWid = iris[Species=='setosa']['Petal.Width']

vsLen = iris[Species=='versicolor']['Petal.Length']
vsWid = iris[Species=='versicolor']['Petal.Width']

viLen = iris[Species=='virginica']['Petal.Length']
viWid = iris[Species=='virginica']['Petal.Width']

plt.rcParams['figure.figsize'] = 8, 6
plt.rc('axes',edgecolor='black')

fntsz = 12  # global font size adjustment

sctplt1 = plt.scatter(stLen, stWid, c='blue',   alpha=0.8)
sctplt2 = plt.scatter(vsLen, vsWid, c='red',    alpha=0.8)
sctplt3 = plt.scatter(viLen, viWid, c='purple', alpha=0.8)

plt.legend((sctplt1, sctplt2, sctplt3),
           ('setosa', 'versicolor', 'virginica'),
           scatterpoints=3,
           loc='upper left',
           ncol=1,
           fontsize=10, frameon=True).get_frame().set_edgecolor('black')
                        # help claimed edgecolor should be legend() argument but errors say otherwise
                        # .getframe().set_edgecolor() was supposed to do it but its not working

plt.title('Iris', fontsize = fntsz)     # defaults to center ... to change this:  plt.title('title', loc='right' | 'left')
plt.xlabel('Petal Length', fontsize = fntsz)
plt.ylabel('Petal Width', fontsize = fntsz)

# turn off grid lines:
plt.grid(b=False)

# to save to a file
# fig.savefig('test.jpg')

plt.show
</code>```

答:
Both methods work in matplotlib 2.0. Either use the edgecolor argument

```<code>plt.legend(edgecolor="limegreen")
</code>```

or set the property of the frame

```<code>legend = plt.legend()
legend.get_frame().set_edgecolor("limegreen")
</code>```

Earlier versions don't have those options.

Body:
This code might be useful to others struggling w/ scatter plots in matplotlib for python.  It works except for this one problem.  I have poured over many help topics on this site and elsewhere.  As per comments in my code, there are different ways to set the edgecolor on the border of the legend and yet none of them are working for me.  Python always throws an error indicating I am trying to set something that does not exist.

Can anyone see what the fix is here?

%matplotlib inline
import matplotlib.pyplot as plt

stLen = iris[Species=='setosa']['Petal.Length']
stWid = iris[Species=='setosa']['Petal.Width']

vsLen = iris[Species=='versicolor']['Petal.Length']
vsWid = iris[Species=='versicolor']['Petal.Width']

viLen = iris[Species=='virginica']['Petal.Length']
viWid = iris[Species=='virginica']['Petal.Width']

plt.rcParams['figure.figsize'] = 8, 6
plt.rc('axes',edgecolor='black')

fntsz = 12  # global font size adjustment

sctplt1 = plt.scatter(stLen, stWid, c='blue',   alpha=0.8)
sctplt2 = plt.scatter(vsLen, vsWid, c='red',    alpha=0.8)
sctplt3 = plt.scatter(viLen, viWid, c='purple', alpha=0.8)

plt.legend((sctplt1, sctplt2, sctplt3),
           ('setosa', 'versicolor', 'virginica'),
           scatterpoints=3,
           loc='upper left',
           ncol=1,
           fontsize=10, frameon=True).get_frame().set_edgecolor('black')
                        # help claimed edgecolor should be legend() argument but errors say otherwise
                        # .getframe().set_edgecolor() was supposed to do it but its not working

plt.title('Iris', fontsize = fntsz)     # defaults to center ... to change this:  plt.title('title', loc='right' | 'left')
plt.xlabel('Petal Length', fontsize = fntsz)
plt.ylabel('Petal Width', fontsize = fntsz)

# turn off grid lines:
plt.grid(b=False)

# to save to a file
# fig.savefig('test.jpg')

plt.show

Body:
Both methods work in matplotlib 2.0. Either use the edgecolor argument

plt.legend(edgecolor="limegreen")

or set the property of the frame

legend = plt.legend()
legend.get_frame().set_edgecolor("limegreen")

Earlier versions don't have those options.


问:
Do i have to use namespace to match xml documents?
Having a bit of trouble trying to get an xsd to match two documents:

XML Document 1:

```<code><?xml version="1.0" encoding="UTF-8"?>
<video contenttype="asf" fileextension=".wmv" hascontent="no" lang="en-GB" length="1800" pid="3678738364972" sid="">
    <lastmodified timestamp="1282678200000">
        Tue, 24 Aug 2010 19:30:00 +0000
    </lastmodified>
    <links/>
    <keywords/>
    <slides/>
    <copyright>
        Copyright owned by original broadcaster
    </copyright>
    <title>
        Friends
    </title>
    <comment>
        The One Where the Monkey Gets Away: Rachel accidentally lets Ross's pet monkey escape, then learns that her former best friend is engaged to marry her ex-fiancé.  [AD,S]
    </comment>
    <author>
        E4
    </author>
    <email/>
    <captioning/>
    <extendeddata>
        <data name="keepOriginal">
            0
        </data>
        <data name="keepTranscoded">
            0
        </data>
        <data name="realStartTime">
            1282677909
        </data>
        <data name="scheduledStartTime">
            1282678200
        </data>
        <data name="broadcastLength">
            1800
        </data>
        <data name="broadcastChannel">
            E4
        </data>
        <data name="paddingUsed">
            300000
        </data>
        <data name="transcodingSpec">
            -b 2.35M -a 128k --debug  --primary-format mp4 --podcast "-l 270 -b 600 -R 48 -B 64" --keep-files true
        </data>
        <data name="transcoding">
            succeeded
        </data>
        <data name="transcodingProfile">
            -b 2.35M -a 128k --debug  --primary-format mp4 --podcast "-l 270 -b 600 -R 48 -B 64" --keep-files true
        </data>
        <data name="transcoderDetails">
            ver 1.58.2.1, 2010-08-24  21:31:33 up 5 days, 11:24,  0 users,  load average: 3.08, 3.38, 2.67, OS20031 212.70.69.26
        </data>
        <data name="originalFilename">
            /var/lib/etvd/mpegts/E4/Friends (24-Aug-2010 20.30).emcast
        </data>
        <data name="originalRecordingTime">
            created 2010-08-24 , last modified 2010-08-24 : recording lasted 0s
        </data>
        <data name="primaryFormat">
            mp4
        </data>
        <data name="doXml">
            True
        </data>
        <data name="doFiles">
            True
        </data>
    </extendeddata>
    <categories>
        <category name="em:podcast">
            mp4
        </category>
    </categories>
</video>
</code>```

XML Document 2:

```<code><?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>
</code>```

Proposed XSD:

```<code><?xml version="1.0" encoding="utf-8"?>
<xs:schema id="UploadXSD"
    targetNamespace="UploadXSD"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/UploadXSD.xsd"
    xmlns:mstns="http://tempuri.org/UploadXSD.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="video">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="title" minOccurs="1" type="xs:string"></xs:element>
        <xs:element name="description" type="xs:string"></xs:element>
        <xs:element name="contributor" type="xs:string"></xs:element>
        <xs:element name="subject" type="xs:string"></xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>
</code>```

Is it possible to use c# to validate against both of the xml documents and NOT use a namespace? Because with the XML Document 1 (above) it is created by a third party system and it cannot generate the namespace...

Asked a few questions about xml in the last few days appreciate help am very new to this...

答:
As far as I'm aware, you don't need a namespace. I've never used one in any of my XSD schemas.

Here's Microsoft's documentation on the feature:
http://msdn.microsoft.com/en-us/library/aa258639%28SQL.80%29.aspx

Body:
Having a bit of trouble trying to get an xsd to match two documents:

XML Document 1:

<?xml version="1.0" encoding="UTF-8"?>
<video contenttype="asf" fileextension=".wmv" hascontent="no" lang="en-GB" length="1800" pid="3678738364972" sid="">
    <lastmodified timestamp="1282678200000">
        Tue, 24 Aug 2010 19:30:00 +0000
    </lastmodified>
    <links/>
    <keywords/>
    <slides/>
    <copyright>
        Copyright owned by original broadcaster
    </copyright>
    <title>
        Friends
    </title>
    <comment>
        The One Where the Monkey Gets Away: Rachel accidentally lets Ross's pet monkey escape, then learns that her former best friend is engaged to marry her ex-fiancé.  [AD,S]
    </comment>
    <author>
        E4
    </author>
    <email/>
    <captioning/>
    <extendeddata>
        <data name="keepOriginal">
            0
        </data>
        <data name="keepTranscoded">
            0
        </data>
        <data name="realStartTime">
            1282677909
        </data>
        <data name="scheduledStartTime">
            1282678200
        </data>
        <data name="broadcastLength">
            1800
        </data>
        <data name="broadcastChannel">
            E4
        </data>
        <data name="paddingUsed">
            300000
        </data>
        <data name="transcodingSpec">
            -b 2.35M -a 128k --debug  --primary-format mp4 --podcast "-l 270 -b 600 -R 48 -B 64" --keep-files true
        </data>
        <data name="transcoding">
            succeeded
        </data>
        <data name="transcodingProfile">
            -b 2.35M -a 128k --debug  --primary-format mp4 --podcast "-l 270 -b 600 -R 48 -B 64" --keep-files true
        </data>
        <data name="transcoderDetails">
            ver 1.58.2.1, 2010-08-24  21:31:33 up 5 days, 11:24,  0 users,  load average: 3.08, 3.38, 2.67, OS20031 212.70.69.26
        </data>
        <data name="originalFilename">
            /var/lib/etvd/mpegts/E4/Friends (24-Aug-2010 20.30).emcast
        </data>
        <data name="originalRecordingTime">
            created 2010-08-24 , last modified 2010-08-24 : recording lasted 0s
        </data>
        <data name="primaryFormat">
            mp4
        </data>
        <data name="doXml">
            True
        </data>
        <data name="doFiles">
            True
        </data>
    </extendeddata>
    <categories>
        <category name="em:podcast">
            mp4
        </category>
    </categories>
</video>

XML Document 2:

<?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>

Proposed XSD:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="UploadXSD"
    targetNamespace="UploadXSD"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/UploadXSD.xsd"
    xmlns:mstns="http://tempuri.org/UploadXSD.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="video">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="title" minOccurs="1" type="xs:string"></xs:element>
        <xs:element name="description" type="xs:string"></xs:element>
        <xs:element name="contributor" type="xs:string"></xs:element>
        <xs:element name="subject" type="xs:string"></xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>

Is it possible to use c# to validate against both of the xml documents and NOT use a namespace? Because with the XML Document 1 (above) it is created by a third party system and it cannot generate the namespace...

Asked a few questions about xml in the last few days appreciate help am very new to this...


问:
Rails 5 - testing the application mailer
I want to test the mailer in my application to make sure it is doing what I want it to do.

```<code>class LessonMailer < ApplicationMailer
   def send_mail(lesson)
      @lesson = lesson
      mail(to: lesson.student.email,
        subject: 'A lesson has been recorded by your tutor')
   end
end
</code>```

This is my test in the spec/mailers directory

```<code>require "rails_helper"

RSpec.describe LessonMailer, :type => :mailer do
   describe "lesson" do

     let( :student ){ FactoryGirl.create :user, role: 'student', givenname: 'name', sn: 'sname', email: 'test@sheffield.ac.uk' }
     let( :lesson  ){ FactoryGirl.create :lesson, student_id: 2 }
     let( :mail    ){ LessonMailer.send_mail( lesson ).deliver_now

     it "renders the headers" do
      expect(mail.subject).to eq("A lesson has been recorded")
      expect(mail.to).to eq(["to@example.ac.uk"])
      expect(mail.from).to eq(["no-reply@example.ac.uk"])
     end

    it "renders the body" do
     expect(mail.body.encoded).to match("A lesson form has been recorded")
    end
  end
end
</code>```

I want to test that the 'send_mail' method is working the way I want it to however, I am getting this error. How do I go about solving this problem ? Thank you.

```<code> NoMethodError:
   undefined method `email' for nil:NilClass
 # ./app/mailers/lesson_mailer.rb:4:in `send_mail'
</code>```

答:
So, with FactoryGirl, you just need to instantiate the different objects that you need. Reading your code, it seems clear that a lesson has a student and that students have an email. So go ahead and create everything you need and then call your method. You can do something like this:

```<code># Here's the student factory (for this use case, you'll probably want to make it more general)
FactoryGirl.define do
  factory :user do
    role 'student'
    givenname 'name'
    sn 'sname'
    email 'test@sheffield.ac.uk'
  end
end

# Here's your test
require "rails_helper"

RSpec.describe LessonMailer, :type => :mailer do
  describe "lesson" do
    let( :student ){ create :student, email: 'test_email@example.com' }
    let( :lesson  ){ create :lesson, student: student }
    let( :mail    ){ LessonMailer.send_mail( lesson ) }

    it ' ... ' do
      ...
    end
  end
end
</code>```

You'll need to let the test environment know that you want the emails to be delivered to the ActionMailer::Base.deliveries array. To do this, make sure that

```<code>config.action_mailer.delivery_method = :test
</code>```

is set in your config/environments/test.rb

One last thing, I'm not sure if you'll need it, but you might have to call the mailer with, .deliver_now.

Like this:

```<code>let( :mail ){ LessonMailer.send_mail( lesson ).deliver_now }
</code>```

... or it may not send. I can't remember off the top.

Let me know how it goes.

Body:
I want to test the mailer in my application to make sure it is doing what I want it to do.

class LessonMailer < ApplicationMailer
   def send_mail(lesson)
      @lesson = lesson
      mail(to: lesson.student.email,
        subject: 'A lesson has been recorded by your tutor')
   end
end

This is my test in the spec/mailers directory

require "rails_helper"

RSpec.describe LessonMailer, :type => :mailer do
   describe "lesson" do

     let( :student ){ FactoryGirl.create :user, role: 'student', givenname: 'name', sn: 'sname', email: 'test@sheffield.ac.uk' }
     let( :lesson  ){ FactoryGirl.create :lesson, student_id: 2 }
     let( :mail    ){ LessonMailer.send_mail( lesson ).deliver_now

     it "renders the headers" do
      expect(mail.subject).to eq("A lesson has been recorded")
      expect(mail.to).to eq(["to@example.ac.uk"])
      expect(mail.from).to eq(["no-reply@example.ac.uk"])
     end

    it "renders the body" do
     expect(mail.body.encoded).to match("A lesson form has been recorded")
    end
  end
end

I want to test that the 'send_mail' method is working the way I want it to however, I am getting this error. How do I go about solving this problem ? Thank you.

 NoMethodError:
   undefined method `email' for nil:NilClass
 # ./app/mailers/lesson_mailer.rb:4:in `send_mail'

Body:
So, with FactoryGirl, you just need to instantiate the different objects that you need. Reading your code, it seems clear that a lesson has a student and that students have an email. So go ahead and create everything you need and then call your method. You can do something like this:

# Here's the student factory (for this use case, you'll probably want to make it more general)
FactoryGirl.define do
  factory :user do
    role 'student'
    givenname 'name'
    sn 'sname'
    email 'test@sheffield.ac.uk'
  end
end

# Here's your test
require "rails_helper"

RSpec.describe LessonMailer, :type => :mailer do
  describe "lesson" do
    let( :student ){ create :student, email: 'test_email@example.com' }
    let( :lesson  ){ create :lesson, student: student }
    let( :mail    ){ LessonMailer.send_mail( lesson ) }

    it ' ... ' do
      ...
    end
  end
end

You'll need to let the test environment know that you want the emails to be delivered to the ActionMailer::Base.deliveries array. To do this, make sure that

config.action_mailer.delivery_method = :test

is set in your config/environments/test.rb

One last thing, I'm not sure if you'll need it, but you might have to call the mailer with, .deliver_now.

Like this:

let( :mail ){ LessonMailer.send_mail( lesson ).deliver_now }

... or it may not send. I can't remember off the top.

Let me know how it goes.


问:
why is my htaccess adding current page url to all links on the page
Am new to htaccess rewrite rules but with some few tutorials i've been able to write some few rules but the problem now is that the rules work well but every links on the page is preceded with the current page link therefore rendering all links on the page invalid. Below is a sample code

```<code>RewriteEngine on
RewriteRule ^school/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ school.php?country=$1&school=$2 [NC,L]
</code>```

For example if i access school page as school/spain/university the link to my index page which is supposed to be index would change to school/spain/universty/index

I've searched everywhere for a similar problem or solution  but i didn't see any.

答:
The best way to solve the problem is to use base link at the head of your page. </p>

<p> </p>

<p>This solves the problem perfectly, it doesn't matter if you're using relative link or absolute link. </p>

Body:
Am new to htaccess rewrite rules but with some few tutorials i've been able to write some few rules but the problem now is that the rules work well but every links on the page is preceded with the current page link therefore rendering all links on the page invalid. Below is a sample code

RewriteEngine on
RewriteRule ^school/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ school.php?country=$1&school=$2 [NC,L]

For example if i access school page as school/spain/university the link to my index page which is supposed to be index would change to school/spain/universty/index

I've searched everywhere for a similar problem or solution  but i didn't see any.

Body:
The best way to solve the problem is to use base link at the head of your page.

This solves the problem perfectly, it doesn't matter if you're using relative link or absolute link.


问:
Eclipse debugger runs wrong version of code
I copied an Eclipse Java project and tried to run the debugger on the copied version. The debugger used the code of the old project. What can I do in this situation?</p>

答: in my case, I have 2 project (A and B) that is referring different version of C. Say A is referring C version 1, and B is referring C version 2. When I am debugging A, C version 2 's source came up always, not C version 1. I ends up adjust the order in debug configuration by remove project B and re-add it. I made project A ahead of project B. That solves the problem.</p>


问:
Backbone view not found/visible in SCA
I've overridden the ItemDetails module and I've added a new view it. But now when I run my SCA Mont Blanc website locally the website fails to load (I get a white screen) and the following error in the browser console - fails to load my view I added.

Failed to load resource: the server responded with a status of 404 (Not Found) ItemDetails.PBT.View.js

What do I need to do to add a new view to a overridden module?

What I have done:

Create the view file in modules/mymodules/ItemDetailsOverrides@1.0.0/Javascript. The view (and filename) name is ItemDetails.PBT.View I have also created a simple template for the view in the templates folder.

Added my module override to distro.json in the modules dictionary. Note the original ItemDetails is still included in the file aswell

Include my new view in modules/mymodules/ItemDetailsOverrides@1.0.0/Javascript/ItemDetails.View.js both in the dependencies and in the function as a parameter.

In ns.package.json I have specified that I am overridding the modules/suitecommerce/ItemDetailsOverrides@2.1.0/Javascript/ItemDetails.View.js with modules/mymodules/ItemDetailsOverrides@1.0.0/Javascript/ItemDetails.View.js.

What else do I need to do?? Specific answers would be greatly appreciated.

答:
The 404 error could be caused by several reasons:

1- If you are overriding a view you can't require it since it doesn't exist anymore.

2- Is ItemDetailsOverrides part of suitecommerce modules or are you trying to override modules/suitecommerce/ItemDetails@2.1.0/Javascript/ItemDetails.View.js?

3- Did you add the view to the javascript dependencies in the distro.json?

4- If you are "extending" the original ItemDetails.View.js in your module there's no need to override it (Probably you will need to change the name to something like ItemDetails.View.Extended). You can work with the ItemDetails.View prototype and add/redefine properties and methods:

```<code>_.extend(ItemDetailsView.prototype, {
    title: 'My new item details view'
})
</code>```

Title: Backbone view not found/visible in SCA

Body:
The 404 error could be caused by several reasons:

1- If you are overriding a view you can't require it since it doesn't exist anymore.

2- Is ItemDetailsOverrides part of suitecommerce modules or are you trying to override modules/suitecommerce/ItemDetails@2.1.0/Javascript/ItemDetails.View.js?

3- Did you add the view to the javascript dependencies in the distro.json?

4- If you are "extending" the original ItemDetails.View.js in your module there's no need to override it (Probably you will need to change the name to something like ItemDetails.View.Extended). You can work with the ItemDetails.View prototype and add/redefine properties and methods:

_.extend(ItemDetailsView.prototype, {
    title: 'My new item details view'
})


问:
CKEditor - how to replace save functionality with custom js?
CKEditor 4.x makes it very easy to grab the contents of the textarea html:

```<code>var data = CKEDITOR.instances.editor1.getData();
</code>```

...but very difficult to intercept the Save event (or whatever happens when clicking their built-in save icon on the toolbar). By default, it does a form post. I simply want to prevent the form post and grab the contents, as in the js line above. After scouring their documentation and various stack posts -- and after trying different approaches -- it seems this basic functionality is difficult to achieve or closely guarded.

How is it done?

答:
I finally found the answer:</p>

```<code><script>
   var ckEditor = CKEDITOR.replace('editor1');

   ckEditor.on("instanceReady", function () {
      // overwrite the default save function
      ckEditor.addCommand("save", {
         modes: { wysiwyg: 1, source: 1 },
         exec: function () {
            var theData = ckEditor.getData(); // get the editor content
            console.log(theData);
         }
      })
   });
</script>
</code>```

Body:
CKEditor 4.x makes it very easy to grab the contents of the textarea html:

var data = CKEDITOR.instances.editor1.getData();

...but very difficult to intercept the Save event (or whatever happens when clicking their built-in save icon on the toolbar). By default, it does a form post. I simply want to prevent the form post and grab the contents, as in the js line above. After scouring their documentation and various stack posts -- and after trying different approaches -- it seems this basic functionality is difficult to achieve or closely guarded.

How is it done?

Body:
I finally found the answer:

<script>
   var ckEditor = CKEDITOR.replace('editor1');

   ckEditor.on("instanceReady", function () {
      // overwrite the default save function
      ckEditor.addCommand("save", {
         modes: { wysiwyg: 1, source: 1 },
         exec: function () {
            var theData = ckEditor.getData(); // get the editor content
            console.log(theData);
         }
      })
   });
</script>


问:
Match string to regex in bash
In the below code, either T1 should be set or T2 must follow the regex, else print "error", but it doesn't work.

And is there an better way to check if T2 has pattern string with underscore >:<space separated strings>; please note the colon and semicolon.

```<code>#!/bin/bash

T1="TEST"
T2="TST_1:one two three;"

if [[ -z ${T1} && ! ${T2} =~ .*":".*";" ]]; then
    echo "error"
    exit 1
fi
</code>```

答:
Here's what worked for me:

```<code>  re="^.+_.+:.+( .+)+;$"
  if [[ -z "$T1" && ! $T2 =~ $re ]]; then
     echo "Error"
     exit 1
  fi
</code>```

For that regex, the caret ("^") means the start of the line.  Then there's ".+" which is any character (the period) 1 or more times (the plus).  Then there's an underscore and another group of 1 or more characters followed by the colon.  After that, you have a group of 1 or more characters followed by at least one set of a space and some characters.  Then the semicolon and a dollar sign meaning that has to be the end of the line.

With your sample, it breaks down as follows:

```<code>^.+    - "TST" at the beginning of the line
_      - the underscore
.+     - "1"
:      - the colon
.+     - "one"
( .+)+ - inside the parentheses, there's a space and a .+
         meaning one or more characters.  So that's " two".
         But the plus after the right parenthesis means one
         or more of that group so it also applies to " three"
         as well as any other groups of letters that might
         follow, separated by spaces.
;$     - the trailing semicolon, at the very end of the line.
</code>```

This will allow for any set of characters at the start (as long as there's an underscore), the colon, and any number of groups of characters separated by a space.  And the trailing semicolon, of course.

btw, if you want to limit things to letters, numbers, and an underscore (so that "t#t_1:..." would fail), switch the periods for "\w" which is shorthand for [a-zA-Z0-9_].

If you want to fool around with regular expressions, a debugger like https://www.debuggex.com/?flavor=pcre can be useful.

Hope this helps!

Title: Match string to regex in bash

Body:
In the below code, either T1 should be set or T2 must follow the regex, else print "error", but it doesn't work.

And is there an better way to check if T2 has pattern :<space separated strings>; please note the colon and semicolon.

#!/bin/bash

T1="TEST"
T2="TST_1:one two three;"

if [[ -z ${T1} && ! ${T2} =~ .*":".*";" ]]; then
    echo "error"
    exit 1
fi

Body:
Here's what worked for me:

  re="^.+_.+:.+( .+)+;$"
  if [[ -z "$T1" && ! $T2 =~ $re ]]; then
     echo "Error"
     exit 1
  fi

For that regex, the caret ("^") means the start of the line.  Then there's ".+" which is any character (the period) 1 or more times (the plus).  Then there's an underscore and another group of 1 or more characters followed by the colon.  After that, you have a group of 1 or more characters followed by at least one set of a space and some characters.  Then the semicolon and a dollar sign meaning that has to be the end of the line.

With your sample, it breaks down as follows:

^.+    - "TST" at the beginning of the line
_      - the underscore
.+     - "1"
:      - the colon
.+     - "one"
( .+)+ - inside the parentheses, there's a space and a .+
         meaning one or more characters.  So that's " two".
         But the plus after the right parenthesis means one
         or more of that group so it also applies to " three"
         as well as any other groups of letters that might
         follow, separated by spaces.
;$     - the trailing semicolon, at the very end of the line.

This will allow for any set of characters at the start (as long as there's an underscore), the colon, and any number of groups of characters separated by a space.  And the trailing semicolon, of course.

btw, if you want to limit things to letters, numbers, and an underscore (so that "t#t_1:..." would fail), switch the periods for "\w" which is shorthand for [a-zA-Z0-9_].

If you want to fool around with regular expressions, a debugger like https://www.debuggex.com/?flavor=pcre can be useful.

Hope this helps!


问:
Get %AppData% path (or other environment variable) for Git hook on Windows (10)
Is it possible to get the %AppData% path within a git hook on my Windows 10 machine?

I am attempting to use it to call gulp.... so maybe even the environment variable %NODE_PATH% which I also have....but essentially I want to get the path of the environment variable.

I currently have:-

```<code>gulp="/c/Users/MYUSERNAME/AppData/Roaming/npm/gulp.cmd"
echo $gulp
</code>```

and then I can call gulp successfully..... but I'd like not to hardcode my username in the path....and rather have something like:-

```<code>gulp="%AppData%/gulp.cmd"
echo $gulp
</code>```

Any suggestions?

答:
This works on my Git Bash:

```<code>$ export gulp=`echo $APPDATA | sed -e 's/^C:/\/c/;s/\\\\/\//g;s/$/\\/npm\\/gulp\\.cmd/' `

$ gulp
No gulpfile found
</code>```

The sed transforms the Windows path into something in Bash format, with each regular expression separated by a semicolon:

Change "C:\" to "/c":

```<code>s/^C:/\/c/
</code>```

Change the remaining backslashes:

```<code>s/\\\\/\//g
</code>```

Append the gulp command:

```<code>s/$/\\/npm\\/gulp\\.cmd/
</code>```

The backticks evaluate the expression, and they requiring doubling up the backslashes used for escaping the regex special characters.

Body:
Is it possible to get the %AppData% path within a git hook on my Windows 10 machine?

I am attempting to use it to call gulp.... so maybe even the environment variable %NODE_PATH% which I also have....but essentially I want to get the path of the environment variable.

I currently have:-

gulp="/c/Users/MYUSERNAME/AppData/Roaming/npm/gulp.cmd"
echo $gulp

and then I can call gulp successfully..... but I'd like not to hardcode my username in the path....and rather have something like:-

gulp="%AppData%/gulp.cmd"
echo $gulp

Any suggestions?

Body:
This works on my Git Bash:

$ export gulp=`echo $APPDATA | sed -e 's/^C:/\/c/;s/\\\\/\//g;s/$/\\/npm\\/gulp\\.cmd/' `

$ gulp
No gulpfile found

The sed transforms the Windows path into something in Bash format, with each regular expression separated by a semicolon:

Change "C:\" to "/c":

s/^C:/\/c/

Change the remaining backslashes:

s/\\\\/\//g

Append the gulp command:

s/$/\\/npm\\/gulp\\.cmd/

The backticks evaluate the expression, and they requiring doubling up the backslashes used for escaping the regex special characters.


问:
Android : Get photo from gallery always returns bitmap not uri
I call:

```<code>Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.INTERNAL_CONTENT_URI);
        intent.setType("image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);
        intent.putExtra("outputX", 256);
        intent.putExtra("outputY", 256);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("return-data", true);

startActivityForResult(intent, code);
</code>```

then in my ActiviyResult():

```<code>if (requestCode == RESULT_LOAD_IMAGE && data != null) {

                final Bundle extras = data.getExtras();
                if (extras != null) {
                //Get image
                Bitmap profilePicBitmap = extras.getParcelable("data");
                  ...
</code>```

I try to get the uri by doing this:

```<code>data.getData()
</code>```

but it always returns null

The problem is I need the path of the bitmap on the device so I can upload it elsewhere...but I can't get the path of it without having to convert it to uri. To convert to uri you have to request permission to write external storage, see here: (http://stackoverflow.com/questions/12555420/how-to-get-a-uri-object-from-bitmap) and I'd like to avoid that.

答:
but it always returns null

That behavior will depend on the device and its apps.

I suspect that you will have better luck if you get rid of those undocumented extras. Presumably, rather than use an image-cropping library, you are trying to have the ACTION_PICK activity do the cropping. There are two problems with this:

There is no requirement for the ACTION_PICK activity to do any cropping, as those extras are not part of the Android SDK.

My guess is that since the cropped image does not exist as a file, they return it via the "data" extra (which is also outside the documented behavior of ACTION_PICK)

So, get rid of those extras. If you want to crop the image, use an image-cropping library.

Body:
I call:

Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.INTERNAL_CONTENT_URI);
        intent.setType("image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);
        intent.putExtra("outputX", 256);
        intent.putExtra("outputY", 256);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("return-data", true);

startActivityForResult(intent, code);

then in my ActiviyResult():

if (requestCode == RESULT_LOAD_IMAGE && data != null) {

                final Bundle extras = data.getExtras();
                if (extras != null) {
                //Get image
                Bitmap profilePicBitmap = extras.getParcelable("data");
                  ...

I try to get the uri by doing this:

data.getData()

but it always returns null

The problem is I need the path of the bitmap on the device so I can upload it elsewhere...but I can't get the path of it without having to convert it to uri. To convert to uri you have to request permission to write external storage, see here: (http://stackoverflow.com/questions/12555420/how-to-get-a-uri-object-from-bitmap) and I'd like to avoid that.


问:
Difference in Months between two dates in JavaScript
How would I work out the difference for two Date() objects in JavaScript, while only return the number of months in the difference?

Any help would be great :)

答:
If you do not consider the day of the month, this is by far the simpler solution

function monthDiff(dateFrom, dateTo) {
 return dateTo.getMonth() - dateFrom.getMonth() +
   (12 * (dateTo.getFullYear() - dateFrom.getFullYear()))
}

//examples
console.log(monthDiff(new Date(2000, 01), new Date(2000, 02))) // 1
console.log(monthDiff(new Date(1999, 02), new Date(2000, 02))) // 12 full year
console.log(monthDiff(new Date(2009, 11), new Date(2010, 0))) // 1```

Be aware that month index is 0-based. This means that January = 0 and December = 11.

Body:
If you do not consider the day of the month, this is by far the simpler solution

function monthDiff(dateFrom, dateTo) {
 return dateTo.getMonth() - dateFrom.getMonth() +
   (12 * (dateTo.getFullYear() - dateFrom.getFullYear()))
}

//examples
console.log(monthDiff(new Date(2000, 01), new Date(2000, 02))) // 1
console.log(monthDiff(new Date(1999, 02), new Date(2000, 02))) // 12 full year
console.log(monthDiff(new Date(2009, 11), new Date(2010, 0))) // 1

Be aware that month index is 0-based. This means that January = 0 and December = 11.


问:
android studio NDK , about cv:: method
First, I'm sorry I can not English well. I gave up googling, I was exhausted. Please give me tips.

I just finished NDK's h, cpp, Android.mk and Applicaiton.mk files and then I ran my application. It works well. But by adding one line Mat mat in cpp file, I got the error right away about cv::Mat~~

I immediately modified Mat to cv::Mat but I got other errors about cv::~~. I think that I have to write using namespace cv;. But this is Android Studio not C++. What should I do??

Android.mk

```<code>LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

OPENCV_LIB_TYPE:=STATIC
LOCAL_C_INCLUDES := C:\opencv-3.2.0-android-sdk\OpenCV-android-sdk\sdk\native\jni\include
LOCAL_MODULE := myCanny
LOCAL_SRC_FILES := myCanny.cpp

include $(BUILD_SHARED_LIBRARY)
</code>```

Application.mk

```<code>APP_ABI := all
APP_MODULED := myCanny
APP_STL := gnustl_shared
APP_CPPFLAGS += -std=c++11
</code>```

答:
why don't you just use the java port of openCV?
https://opencv-java-tutorials.readthedocs.io/en/latest/

If there is a reason you are using c++ code for image processing, let's talk.
 somenamespace::function() is the same if you set using namespace somenamespace and just call function(), so it's not necessary.
please share your cpp code to get more detais. maybe, you've forgot to #include "opencv2/imgcodecs.hpp" ?

Title: android studio NDK , about cv:: method

Body:
First, I'm sorry I can not English well. I gave up googling, I was exhausted. Please give me tips.

I just finished NDK's h, cpp, Android.mk and Applicaiton.mk files and then I ran my application. It works well. But by adding one line Mat mat in cpp file, I got the error right away about cv::Mat~~

I immediately modified Mat to cv::Mat but I got other errors about cv::~~. I think that I have to write using namespace cv;. But this is Android Studio not C++. What should I do??

Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

OPENCV_LIB_TYPE:=STATIC
LOCAL_C_INCLUDES := C:\opencv-3.2.0-android-sdk\OpenCV-android-sdk\sdk\native\jni\include
LOCAL_MODULE := myCanny
LOCAL_SRC_FILES := myCanny.cpp

include $(BUILD_SHARED_LIBRARY)

Application.mk

APP_ABI := all
APP_MODULED := myCanny
APP_STL := gnustl_shared
APP_CPPFLAGS += -std=c++11


问:
Python list of lists specific path combinations or permutations
I have a list of lists and am looking for something similar to combinations or permutations, but there are conditions that may result in good "Path" or "Dead_End".  If "Dead_End", it should index to the next choice in the list.
Example:

```<code>AList = [[1, 2, 3],
         [2, 0, 3],
         [3, 1, 0],
         [1, 0, 2]]

N = 0
Index = 0
#AList[N][Index]=1,  AList[2][2]=0
</code>```

I would like to start with the value AList[N][Index], which at the start is [0][0] and therefore equals 1 and assign that to N.  After N is assigned 1, we can never go back to that List and the Path = [1].

Then I would have AList[N][Index], which is AList[1][0] and that equals 2.  Assign that to N.  Path.append(N) and I would have Path = [1, 2].

AList[N][Index] would next equal 3, N = 3, and Path would become [1, 2, 3]

Now AList[N][Index] would equal 1.  This would be a Dead_Path and not a good solution because 1 is already in Path and we can't go back to it.  So I want to index over to the next choice in the list.  Index = Index + 1.  That would result in AList[N][Index] = 0.  Path = [1, 2, 3, 0]

That is a good Path and there are many good Paths and many Dead_Ends.  For example, another good Path would be Path = [1, 0, 2, 3].

Is this a multi-nested IF, For, While loop scenario or is there an itertools function to test out all of the Paths and Dead_Ends?  And the List of list could be more complicated and not uniform to create even more Dead_Ends, like:

```<code>BList = [[1, 4, 3],
         [2, 0, 3, 4],
         [3, 4, 0],
         [1, 2],
         [3, 2, 1, 0]]
</code>```

Edited:
I couldn't deal with all of the Dead_Ends.  All of the loops and indexing got me confused, so I think the best solution is that I use itertools and list all path combinations and allow revisiting back to previous node.  Then I would use set() function to eliminate the lists that revisited a node.  In the end, I'm left with Perfect_Paths hitting each node once.  I don't know if this is the fastest / cleanest, but it worked.  Code below:

```<code>Perfect_Path = list()
i = 0

All_Paths = list(itertools.product(*Alist))

for i in range(len(All_Paths)):
    if len(set(All_Paths[i])) == len(Alist):  #filter out paths that revisited a node, which means it would have same number repeated in list
        Perfect_Path.append(All_Paths[i])

print ("The perfect paths are ", Perfect_Path)
</code>```

Edit:  Well my code above works for a small Alist, but to itertools all combinations for a slightly larger list, say 10 data nodes all of a sudden becomes millions of paths.  And then I have to set() them to eliminate choices.  Back to the drawing board for me.

答:
Reading through the text of the question again and again I detected two  variants of rules for finding the right answer and will provide here both of them without asking which one is the one OP had in mind asking the question.

Let's start with the easy one. The path through the elements of the matrix can jump from one element to any other element and the only restriction for the path is that there are no same values in the path allowed. This makes it very easy to find all paths through the values of the matrix and it goes as follows:

Step1: make out of all of the matrix values a flat set with unique values

Step2: create all possible permutations of this set

Let's demonstrate with code that this variant works even on a quite large matrix:

```<code>theMatrix = [[1, 1, 3, 2, 1, 3, 3, 3, 2, 1, 1, 3],
             [1, 2, 1],
             [2, 3, 3, 1, 3, 3, 2, 1, 1, 1, 3, 3, 1, 3, 3],
             [3, 1, 3, 1, 2],
             [2, 3, 3, 1, 3, 3, 2, 1, 1, 1, 3],
             [1, 2],
             [1, 2, 1],
             [2, 3, 3, 1, 3, 3, 1, 1, 3, 3, 1, 3, 3],
             [3, 1, 3, 1, 2],
             [2, 3, 3, 1, 3, 3, 2, 1, 1, 1, 3],
             [1, 2],
             [2, 3, 3, 1, 3, 3, 1, 1, 3, 3, 1, 3, 3],
             [3, 1, 3, 1, 2],
             [2, 3, 3, 1, 3, 3, 2, 1, 1, 1, 3],
             [3, 2, 1, 3, 1]]
setOnlyDifferentMatrixValues = set()
for row in range(len(theMatrix)):
    for column in range(len(theMatrix[row])):
        setOnlyDifferentMatrixValues.add(theMatrix[row][column])
from itertools import permutations
allPossiblePaths = permutations(setOnlyDifferentMatrixValues)
print(list(allPossiblePaths))
</code>```

The code above outputs:

```<code>[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
</code>```

Now the more complex variant with more lines of code. The code is necessary, because there are more restrictions there and the path can go only through matrix elements which are neighbors (horizontal, vertical and diagonal). In this case not all paths have the same length and the same elements in them:

```<code>def getAllValidPathsFrom(myMatrix):
# def getDictRepresentationOf(myMatrix):
    dctOfMatrix = {}
    for row in range(len(myMatrix)):
        for column in range(len(myMatrix[row])):
            currPoint = (column, row)
            dctOfMatrix[currPoint] = myMatrix[row][column]

    lstIndicesOfAllMatrixPoints = list(dctOfMatrix.keys())
    setAllPossiblePaths = set()
    from itertools import permutations
    permutationsIndicesOfAllMatrixPoints = permutations(lstIndicesOfAllMatrixPoints)
    cutBranchAt = ()
    sizeOfCutBranch = 0
    for pathCandidate in permutationsIndicesOfAllMatrixPoints:
        # print(pathCandidate, type(pathCandidate))
        if sizeOfCutBranch > 0:
            # print( "sizeOfCutBranch > 0", cutBranchAt )
            cutBranchAt = tuple(cutBranchAt)
            while cutBranchAt == pathCandidate[0:sizeOfCutBranch]:
                try:
                    pathCandidate = next(permutationsIndicesOfAllMatrixPoints)
                except:
                    break
        lstPossiblePath = []
        prevIndexTuple = pathCandidate[0]
        lstPossiblePath.append(prevIndexTuple)
        for currIndexTuple in pathCandidate[1:]:
            if (abs(currIndexTuple[0]-prevIndexTuple[0]) > 1) or (abs(currIndexTuple[1]-prevIndexTuple[1]) > 1) :
                sizeOfCutBranch = len(lstPossiblePath)+1
                cutBranchAt = tuple(lstPossiblePath+[currIndexTuple])
                break # current path indices not allowed in path (no jumps)
            else:
                if dctOfMatrix[currIndexTuple] in [ dctOfMatrix[index] for index in lstPossiblePath ] :
                    sizeOfCutBranch = len(lstPossiblePath)+1
                    cutBranchAt = tuple(lstPossiblePath+[currIndexTuple])
                    break # only values different from all previous are allowed
                else:
                    sizeOfCutBranch = 0
                    cutBranchAt = ()
                    lstPossiblePath.append(currIndexTuple)
                    prevIndexTuple = currIndexTuple
        if len(lstPossiblePath) > 1 and tuple(lstPossiblePath) not in setAllPossiblePaths:
            setAllPossiblePaths.add(tuple(lstPossiblePath))

    return setAllPossiblePaths, dctOfMatrix
#:def getAllValidSkiingPathsFrom

theMatrix = [[3, 1, 3],
             [1, 1],
             [1, 2, 1, 3]]

lstAllPossiblePaths, dctOfMatrix = getAllValidPathsFrom(theMatrix)
setDifferentPossiblePaths = set(lstAllPossiblePaths)
setTpl = set()
for item in setDifferentPossiblePaths:
    lstTpl = []
    for element in item:
        lstTpl.append(dctOfMatrix[element])
    setTpl.add(tuple(lstTpl))
print(setTpl)
</code>```

The code above runs over a small matrix as the large one would kill it computationally. Because of special arrangement of values in the small matrix it is possible to demonstrate here that not all permutations are generated because of the more restrictive rules for building the path. Let's compare the outputs for the variant one and the variant two of the answer:

```<code>[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

{(1, 2), (1, 3), (2, 1, 3), (3, 1), (2, 1), (3, 1, 2)}
</code>```

Because in the second variant the path has to go through adjacent matrix elements not all permutations of the longest path are there and there are also shorter paths included.

Body:
I have a list of lists and am looking for something similar to combinations or permutations, but there are conditions that may result in good "Path" or "Dead_End".  If "Dead_End", it should index to the next choice in the list.
Example:

AList = [[1, 2, 3],
         [2, 0, 3],
         [3, 1, 0],
         [1, 0, 2]]

N = 0
Index = 0
#AList[N][Index]=1,  AList[2][2]=0

I would like to start with the value AList[N][Index], which at the start is [0][0] and therefore equals 1 and assign that to N.  After N is assigned 1, we can never go back to that List and the Path = [1].

Then I would have AList[N][Index], which is AList[1][0] and that equals 2.  Assign that to N.  Path.append(N) and I would have Path = [1, 2].

AList[N][Index] would next equal 3, N = 3, and Path would become [1, 2, 3]

Now AList[N][Index] would equal 1.  This would be a Dead_Path and not a good solution because 1 is already in Path and we can't go back to it.  So I want to index over to the next choice in the list.  Index = Index + 1.  That would result in AList[N][Index] = 0.  Path = [1, 2, 3, 0]

That is a good Path and there are many good Paths and many Dead_Ends.  For example, another good Path would be Path = [1, 0, 2, 3].

Is this a multi-nested IF, For, While loop scenario or is there an itertools function to test out all of the Paths and Dead_Ends?  And the List of list could be more complicated and not uniform to create even more Dead_Ends, like:

BList = [[1, 4, 3],
         [2, 0, 3, 4],
         [3, 4, 0],
         [1, 2],
         [3, 2, 1, 0]]

Edited:
I couldn't deal with all of the Dead_Ends.  All of the loops and indexing got me confused, so I think the best solution is that I use itertools and list all path combinations and allow revisiting back to previous node.  Then I would use set() function to eliminate the lists that revisited a node.  In the end, I'm left with Perfect_Paths hitting each node once.  I don't know if this is the fastest / cleanest, but it worked.  Code below:

Perfect_Path = list()
i = 0

All_Paths = list(itertools.product(*Alist))

for i in range(len(All_Paths)):
    if len(set(All_Paths[i])) == len(Alist):  #filter out paths that revisited a node, which means it would have same number repeated in list
        Perfect_Path.append(All_Paths[i])

print ("The perfect paths are ", Perfect_Path)

Edit:  Well my code above works for a small Alist, but to itertools all combinations for a slightly larger list, say 10 data nodes all of a sudden becomes millions of paths.  And then I have to set() them to eliminate choices.  Back to the drawing board for me.

Body:
Reading through the text of the question again and again I detected two  variants of rules for finding the right answer and will provide here both of them without asking which one is the one OP had in mind asking the question.

Let's start with the easy one. The path through the elements of the matrix can jump from one element to any other element and the only restriction for the path is that there are no same values in the path allowed. This makes it very easy to find all paths through the values of the matrix and it goes as follows:

Step1: make out of all of the matrix values a flat set with unique values

Step2: create all possible permutations of this set

Let's demonstrate with code that this variant works even on a quite large matrix:

theMatrix = [[1, 1, 3, 2, 1, 3, 3, 3, 2, 1, 1, 3],
             [1, 2, 1],
             [2, 3, 3, 1, 3, 3, 2, 1, 1, 1, 3, 3, 1, 3, 3],
             [3, 1, 3, 1, 2],
             [2, 3, 3, 1, 3, 3, 2, 1, 1, 1, 3],
             [1, 2],
             [1, 2, 1],
             [2, 3, 3, 1, 3, 3, 1, 1, 3, 3, 1, 3, 3],
             [3, 1, 3, 1, 2],
             [2, 3, 3, 1, 3, 3, 2, 1, 1, 1, 3],
             [1, 2],
             [2, 3, 3, 1, 3, 3, 1, 1, 3, 3, 1, 3, 3],
             [3, 1, 3, 1, 2],
             [2, 3, 3, 1, 3, 3, 2, 1, 1, 1, 3],
             [3, 2, 1, 3, 1]]
setOnlyDifferentMatrixValues = set()
for row in range(len(theMatrix)):
    for column in range(len(theMatrix[row])):
        setOnlyDifferentMatrixValues.add(theMatrix[row][column])
from itertools import permutations
allPossiblePaths = permutations(setOnlyDifferentMatrixValues)
print(list(allPossiblePaths))

The code above outputs:

[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

Now the more complex variant with more lines of code. The code is necessary, because there are more restrictions there and the path can go only through matrix elements which are neighbors (horizontal, vertical and diagonal). In this case not all paths have the same length and the same elements in them:

def getAllValidPathsFrom(myMatrix):
# def getDictRepresentationOf(myMatrix):
    dctOfMatrix = {}
    for row in range(len(myMatrix)):
        for column in range(len(myMatrix[row])):
            currPoint = (column, row)
            dctOfMatrix[currPoint] = myMatrix[row][column]

    lstIndicesOfAllMatrixPoints = list(dctOfMatrix.keys())
    setAllPossiblePaths = set()
    from itertools import permutations
    permutationsIndicesOfAllMatrixPoints = permutations(lstIndicesOfAllMatrixPoints)
    cutBranchAt = ()
    sizeOfCutBranch = 0
    for pathCandidate in permutationsIndicesOfAllMatrixPoints:
        # print(pathCandidate, type(pathCandidate))
        if sizeOfCutBranch > 0:
            # print( "sizeOfCutBranch > 0", cutBranchAt )
            cutBranchAt = tuple(cutBranchAt)
            while cutBranchAt == pathCandidate[0:sizeOfCutBranch]:
                try:
                    pathCandidate = next(permutationsIndicesOfAllMatrixPoints)
                except:
                    break
        lstPossiblePath = []
        prevIndexTuple = pathCandidate[0]
        lstPossiblePath.append(prevIndexTuple)
        for currIndexTuple in pathCandidate[1:]:
            if (abs(currIndexTuple[0]-prevIndexTuple[0]) > 1) or (abs(currIndexTuple[1]-prevIndexTuple[1]) > 1) :
                sizeOfCutBranch = len(lstPossiblePath)+1
                cutBranchAt = tuple(lstPossiblePath+[currIndexTuple])
                break # current path indices not allowed in path (no jumps)
            else:
                if dctOfMatrix[currIndexTuple] in [ dctOfMatrix[index] for index in lstPossiblePath ] :
                    sizeOfCutBranch = len(lstPossiblePath)+1
                    cutBranchAt = tuple(lstPossiblePath+[currIndexTuple])
                    break # only values different from all previous are allowed
                else:
                    sizeOfCutBranch = 0
                    cutBranchAt = ()
                    lstPossiblePath.append(currIndexTuple)
                    prevIndexTuple = currIndexTuple
        if len(lstPossiblePath) > 1 and tuple(lstPossiblePath) not in setAllPossiblePaths:
            setAllPossiblePaths.add(tuple(lstPossiblePath))

    return setAllPossiblePaths, dctOfMatrix
#:def getAllValidSkiingPathsFrom

theMatrix = [[3, 1, 3],
             [1, 1],
             [1, 2, 1, 3]]

lstAllPossiblePaths, dctOfMatrix = getAllValidPathsFrom(theMatrix)
setDifferentPossiblePaths = set(lstAllPossiblePaths)
setTpl = set()
for item in setDifferentPossiblePaths:
    lstTpl = []
    for element in item:
        lstTpl.append(dctOfMatrix[element])
    setTpl.add(tuple(lstTpl))
print(setTpl)

The code above runs over a small matrix as the large one would kill it computationally. Because of special arrangement of values in the small matrix it is possible to demonstrate here that not all permutations are generated because of the more restrictive rules for building the path. Let's compare the outputs for the variant one and the variant two of the answer:

[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

{(1, 2), (1, 3), (2, 1, 3), (3, 1), (2, 1), (3, 1, 2)}

Because in the second variant the path has to go through adjacent matrix elements not all permutations of the longest path are there and there are also shorter paths included.


问:
Array in Ruby on rails, undefined method `minimum'
```<code>@click = Missing.select{|d| d.click < 10000}

find = @click.minimum(:id)
@data = Missing.where(id: find)
dataSize = @data.size
@renderData = @data[dataSize - 1]
render :json => @renderData
</code>```

Errors:

```<code>undefined method `minimum' for #<Array:0x00000004acd678>

Error code : find = @click.minimum(:id)
</code>```

I have no idea why it is wrong.

render :json = @click is working.
 find = Missing.minimum(:id) is working.

答:
@click is an array, not an association.

Why don't you use activerecord query to get your find?

```<code>find = Missing.where('click < 10000').minimum(:id)
</code>```

Body:
@click = Missing.select{|d| d.click < 10000}

find = @click.minimum(:id)
@data = Missing.where(id: find)
dataSize = @data.size
@renderData = @data[dataSize - 1]
render :json => @renderData

Errors:

undefined method `minimum' for #<Array:0x00000004acd678>

Error code : find = @click.minimum(:id)

I have no idea why it is wrong.

render :json = @click is working.
 find = Missing.minimum(:id) is working.

Body:
@click is an array, not an association.

Why don't you use activerecord query to get your find?

find = Missing.where('click < 10000').minimum(:id)


问:
How to make <input type="date"> display the date in localized format in Chrome?
I'm using the HTML5 <input type="date">, which in Chrome renders a rich input control displaying the date in the format MM/DD/YYYY. The problem is that my application expects input in a localized format server-side, which means MM.DD.YYYY.

Is there any way I can change the way Chrome renders and takes input from date controls?

答: Good idea to post to the data base in YYYY-MM-DD format, but offer to HTML-5 user (independently of browser) either DD-MM-YYYY or MM-DD-YYYY. Need to allow script writer to decide when coding the <INPUT..>.


问:
Tensorflow. Conditionally trainable variables and stochastic depth neural networks
I have come across with a problem when started implementing stochastic depth regularization approch using Tensorflow. The paper (https://arxiv.org/pdf/1603.09382.pdf) states that the model can converge faster if we drop randomly some residual units during training. Current  Torch implementation works perfectly. In Tensoflow, I can put conditions on residual unit branches, so that during forward step the activations for it will be cancelled, but the weights still will be updated during backward step. There is no way to tell that these weights (in the residual branch which we cancelled) are no longer trainable and they should not be included in optimization for current session run.

I have created the issue on github, where I covered how this problem can be solved in naive way, of course there is something under-hood that will prevent applying an easy fix, otherwise it is really strange why the tf.Variable's trainable parameter does not allow boolean Tensor as a value. If someone has clue for this question, I would really appreciate if you restore my faith in Tensoflow :)

答:
The trainable parameter is used to control whether a graph to train that variable is built or not. Using a conditional stopgradient (a tf.cond with tf.identity in one branch and tf.stopgradient on the other) will deal with stopping the gradient from that variable.

However, if its value was not used during a forward step the gradient computed is guaranteed to be 0, and hence the update will be a no-op.


问:
MySQL GROUP BY w/ ORDER BY not having desired result
I have a query that attempts to retrieve IDs of people, but only if those people have more than one address. I'm also checking that the last time I called them was at least 30 days ago. Finally, I'm trying to order the results, because I want to pull up results with the oldest last_called datetime:

```<code>SELECT
  p.id,
  COUNT(*) AS cnt
FROM
  people p
  LEFT JOIN addresses a
    ON p.id = a.id
WHERE p.last_called <= DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY p.id
HAVING COUNT(*) > 1
ORDER BY p.last_called ASC
LIMIT 25
</code>```

Right now, the results are not excluding people with only one address. I haven't even got to the point where I know if the sort order is correct, but right now I'd just like to know why it is that my query isn't pulling up results where there is at least 2 addresses for the person.

答:
If you don't want to include people with no address then I would recommend using INNER JOIN instead of LEFT JOIN and DISTINCT to get distinct address ids
(just in case if you have duplicate mappings), e.g.:

```<code>SELECT
  p.id,
  COUNT(DISTINCT(a.id)) AS cnt
FROM
  people p
  JOIN addresses a
    ON p.id= a.peopleid
WHERE p.last_called <= DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY p.id
HAVING COUNT(DISTINCT(a.id)) > 1
</code>```

As far as Ordering is concerned, MySQL evaluates GROUP BY before ordering the results and hence, you need to wrap the query inside another query to get the ordered results.

Update

Instead of joining on aid, you need to join on peopleId of an address record to get the people record.

Body:
I have a query that attempts to retrieve IDs of people, but only if those people have more than one address. I'm also checking that the last time I called them was at least 30 days ago. Finally, I'm trying to order the results, because I want to pull up results with the oldest last_called datetime:

SELECT
  p.id,
  COUNT(*) AS cnt
FROM
  people p
  LEFT JOIN addresses a
    ON p.id = a.id
WHERE p.last_called <= DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY p.id
HAVING COUNT(*) > 1
ORDER BY p.last_called ASC
LIMIT 25

Right now, the results are not excluding people with only one address. I haven't even got to the point where I know if the sort order is correct, but right now I'd just like to know why it is that my query isn't pulling up results where there is at least 2 addresses for the person.

Body:
If you don't want to include people with no address then I would recommend using INNER JOIN instead of LEFT JOIN and DISTINCT to get distinct address ids
(just in case if you have duplicate mappings), e.g.:

SELECT
  p.id,
  COUNT(DISTINCT(a.id)) AS cnt
FROM
  people p
  JOIN addresses a
    ON p.id= a.peopleid
WHERE p.last_called <= DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY p.id
HAVING COUNT(DISTINCT(a.id)) > 1

As far as Ordering is concerned, MySQL evaluates GROUP BY before ordering the results and hence, you need to wrap the query inside another query to get the ordered results.

Update

Instead of joining on aid, you need to join on peopleId of an address record to get the people record.


问:
How to use tlb file in C?
tlb file(using regasm) is made from a dll(using c# code), and i can use this in c++ using #import. and everything is working fine.
Is there a way, i can use this in C language? I just found that #import is c++ specific. So, can someone please tell me how can i use in my C program?

my main intention is to use COM DLL developed in C# in my C program.

Thanks & Rgds,
~calvin

答: Neither C nor C++ have an #import preprocessor directive.</p>

Title: How to use tlb file in C?


问:
Visual Studio 2017 - Open in Visual Studio from Explorer - Permission Error
I am using VS 2017 Enterprise.

I have it setup to open/run in Administrator mode which is working for SLN files.

However I'm trying out the new "Open in Visual Studio" feature by right clicking on a folder in Explorer. I'm receiving the following permission error. It's happening for every folder I try.

VS Code has no problem however.

Is there something more I need to enable?

答:
This works for me if not for you then refer to (https://marketplace.visualstudio.com/items?itemName=GregTrevellick.OpeninVisualStudio2017Enterprise):

1. open notepad.exe and paste this into it:

```<code>Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\shell\VSCode\command]
@="\"C:\\Program Files (x86)\\Microsoft VS Code\\Code.exe\" \"%1\""
</code>```

here is my registry file exported just incase you need it (you shouldnt):

```<code>Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\shell\VSCode\command]
@=hex(2):22,00,43,00,3a,00,5c,00,50,00,72,00,6f,00,67,00,72,00,61,00,6d,00,20,\
  00,46,00,69,00,6c,00,65,00,73,00,20,00,28,00,78,00,38,00,36,00,29,00,5c,00,\
  4d,00,69,00,63,00,72,00,6f,00,73,00,6f,00,66,00,74,00,20,00,56,00,53,00,20,\
  00,43,00,6f,00,64,00,65,00,5c,00,43,00,6f,00,64,00,65,00,2e,00,65,00,78,00,\
  65,00,22,00,20,00,22,00,25,00,31,00,22,00,00,00
</code>```

2. save as VSElevated.reg

3. go to where you saved the .reg file and double click, yes to everything and ok.

4. This is how your Registry should look like afterwards:

The reason i think is the %1 is missing in your launch command. This should solve it.

Body:
This works for me if not for you then refer to (https://marketplace.visualstudio.com/items?itemName=GregTrevellick.OpeninVisualStudio2017Enterprise):

1. open notepad.exe and paste this into it:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\shell\VSCode\command]
@="\"C:\\Program Files (x86)\\Microsoft VS Code\\Code.exe\" \"%1\""

here is my registry file exported just incase you need it (you shouldnt):

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\shell\VSCode\command]
@=hex(2):22,00,43,00,3a,00,5c,00,50,00,72,00,6f,00,67,00,72,00,61,00,6d,00,20,\
  00,46,00,69,00,6c,00,65,00,73,00,20,00,28,00,78,00,38,00,36,00,29,00,5c,00,\
  4d,00,69,00,63,00,72,00,6f,00,73,00,6f,00,66,00,74,00,20,00,56,00,53,00,20,\
  00,43,00,6f,00,64,00,65,00,5c,00,43,00,6f,00,64,00,65,00,2e,00,65,00,78,00,\
  65,00,22,00,20,00,22,00,25,00,31,00,22,00,00,00

2. save as VSElevated.reg

3. go to where you saved the .reg file and double click, yes to everything and ok.

4. This is how your Registry should look like afterwards:

The reason i think is the %1 is missing in your launch command. This should solve it.


问:
NOT EXIST clause
I am trying to find Products that have never been ordered. My 2 tables look like this.

```<code>CREATE TABLE Orders
(OrderNum    NUMBER(10)      NOT NULL,
 OrderDate   DATE            NOT NULL,
 Cust        NUMBER(10),
 Rep         NUMBER(10),
 Mfr         CHAR(3)         NOT NULL,
 Product     CHAR(5)         NOT NULL,
 Qty         NUMBER(5)       NOT NULL,
 Amount      NUMBER(9,2)     NOT NULL,
 CONSTRAINT OrdersPK
      PRIMARY KEY (OrderNum));

CREATE TABLE Products
(Mfr         CHAR(3)         NOT NULL,
 Product     CHAR(5)         NOT NULL,
 Description VARCHAR2(20)    NOT NULL,
 Price       NUMBER(9,2)     NOT NULL,
 QtyOnHand   NUMBER(5),
 CONSTRAINT ProductsPK
      PRIMARY KEY (Mfr, Product));
</code>```

The code I currently have looks like this.

```<code>SELECT Mfr, Product
FROM Products
WHERE NOT EXISTS (SELECT Products.Mfr
                  FROM Orders, Products
                  WHERE Orders.Mfr = Products.Mfr);
</code>```

Although I am not getting any errors there are also no results showing up.

**EDIT: There are 26 Products and 19 of them have been ordered. I am expecting to get 7 Results but I am getting 0.

答:
An alternative is to use the set operation operator EXCEPT - as you want "the set of Products that don't exist in Orders":

```<code>SELECT
    Mfr,
    Product
FROM
    Products

EXCEPT

SELECT
    DISTINCT
    Mfr,
    Product
FROM
    Orders
</code>```

You can then use this as a subquery to get full product information.

```<code>SELECT
    *
FROM
    Products
    INNER JOIN (

        SELECT
            Mfr,
            Product
        FROM
            Products

        EXCEPT

        SELECT
            DISTINCT
            Mfr,
            Product
        FROM
            Orders
   ) AS ProductsWithNoOrders ON
        Products.Mfr = ProductsWithNoOrders.Mfr AND
        Products.Product = ProductsWithNoOrders.Product
</code>```

Title: NOT EXIST clause

Body:
I am trying to find Products that have never been ordered. My 2 tables look like this.

CREATE TABLE Orders
(OrderNum    NUMBER(10)      NOT NULL,
 OrderDate   DATE            NOT NULL,
 Cust        NUMBER(10),
 Rep         NUMBER(10),
 Mfr         CHAR(3)         NOT NULL,
 Product     CHAR(5)         NOT NULL,
 Qty         NUMBER(5)       NOT NULL,
 Amount      NUMBER(9,2)     NOT NULL,
 CONSTRAINT OrdersPK
      PRIMARY KEY (OrderNum));

CREATE TABLE Products
(Mfr         CHAR(3)         NOT NULL,
 Product     CHAR(5)         NOT NULL,
 Description VARCHAR2(20)    NOT NULL,
 Price       NUMBER(9,2)     NOT NULL,
 QtyOnHand   NUMBER(5),
 CONSTRAINT ProductsPK
      PRIMARY KEY (Mfr, Product));

The code I currently have looks like this.

SELECT Mfr, Product
FROM Products
WHERE NOT EXISTS (SELECT Products.Mfr
                  FROM Orders, Products
                  WHERE Orders.Mfr = Products.Mfr);

Although I am not getting any errors there are also no results showing up.

**EDIT: There are 26 Products and 19 of them have been ordered. I am expecting to get 7 Results but I am getting 0.

Body:
An alternative is to use the set operation operator EXCEPT - as you want "the set of Products that don't exist in Orders":

SELECT
    Mfr,
    Product
FROM
    Products

EXCEPT

SELECT
    DISTINCT
    Mfr,
    Product
FROM
    Orders

You can then use this as a subquery to get full product information.

SELECT
    *
FROM
    Products
    INNER JOIN (

        SELECT
            Mfr,
            Product
        FROM
            Products

        EXCEPT

        SELECT
            DISTINCT
            Mfr,
            Product
        FROM
            Orders
   ) AS ProductsWithNoOrders ON
        Products.Mfr = ProductsWithNoOrders.Mfr AND
        Products.Product = ProductsWithNoOrders.Product


问:
all group members but the current row
I've got a grouped data frame, like so:

```<code>df <- data.frame(group = rep(1:4, each=3),
                 lets = rep(LETTERS[1:4], times=3))
</code>```

For each row I would now like to identify all lets within the same group other than the lets of the row itself. Using dplyr I can get all lets thus:

```<code>df %>%
  group_by(group) %>%
  mutate(all_lets_in_group = paste(lets, collapse=','))
</code>```

But how do I exclude the lets of the current row from what I feed into paste()?

答:
Not sure about a dplyr solution, but you can use lapply.

```<code>df$all_lets_in_group <- lapply(1:nrow(df), function(x)
    paste(with(df, lets[group == group[x] & lets != lets[x]]), collapse = ','))
</code>```

Title: all group members but the current row

Body:
I've got a grouped data frame, like so:

df <- data.frame(group = rep(1:4, each=3),
                 lets = rep(LETTERS[1:4], times=3))

For each row I would now like to identify all lets within the same group other than the lets of the row itself. Using dplyr I can get all lets thus:

df %>%
  group_by(group) %>%
  mutate(all_lets_in_group = paste(lets, collapse=','))

But how do I exclude the lets of the current row from what I feed into paste()?

Body:
Not sure about a dplyr solution, but you can use lapply.

df$all_lets_in_group <- lapply(1:nrow(df), function(x)
    paste(with(df, lets[group == group[x] & lets != lets[x]]), collapse = ','))