问:
Issue in connecting to Oracle DB from AWS DMS
I want to run a  DMS task to copy data from on premises Oracle DB to Mysql on AWS.
I have already got firewall access and am able to telnet to the oracle DB server from AWS ec2 instances. Also, I can login into the DB using the same username/pwd, connection string from sql developer
But when I test my endpoint on DMS , then it fails with below error.

FYI, the DMS instance falls in the same VPC for which I have got the firewall clearance.

```<code>Test Endpoint failed: Application-Status: 1020912, Application-Message: ORA-12545:
Connect failed because target host or object does not exist OCI connection failure.,
 Application-Detailed-Message: ORA-12545: Connect failed because target host or object does not exist
 OCI connection failure. ORA-12545: Connect failed because target host or object does not exist OCI connection
 failure. Command get_owner_list failed when creating the stream component. requested object was not found
 in the repository. Failed getting stream handle requested object was not found in the repository.
 create_stream_handle failed requested object was not found in the repository.
 Getting DB object ('A4NOXXXXXXXXXK2N2U') info from repository failed requested object was not found in
 the repository. Command get_owner_list failed when creating the stream component. requested object was not
found in the repository. Failed getting stream handle requested object was not found in the repository.
 create_stream_handle failed
</code>```

I checked at both network and DB end an there seems to be no issue. Please suggest.

答:
I had a similar problem the other time, I assumed that the creation of DMS and Oracle instances using the same VPC would guarantee the connection between them. I also assumed that the addition of entry rules to open ports between the DMS and Oracle instances would also work, but the connection between them fails and I found two ways:

First: creating a DMS instance without a public IP address, the destination connection passes the validation. It worked the first time

Second: by opening the entry to allow all IP addresses, the connection between the instances will be successful.

Good Look!

Body:
I want to run a  DMS task to copy data from on premises Oracle DB to Mysql on AWS.
I have already got firewall access and am able to telnet to the oracle DB server from AWS ec2 instances. Also, I can login into the DB using the same username/pwd, connection string from sql developer
But when I test my endpoint on DMS , then it fails with below error.

FYI, the DMS instance falls in the same VPC for which I have got the firewall clearance.

Test Endpoint failed: Application-Status: 1020912, Application-Message: ORA-12545:
Connect failed because target host or object does not exist OCI connection failure.,
 Application-Detailed-Message: ORA-12545: Connect failed because target host or object does not exist
 OCI connection failure. ORA-12545: Connect failed because target host or object does not exist OCI connection
 failure. Command get_owner_list failed when creating the stream component. requested object was not found
 in the repository. Failed getting stream handle requested object was not found in the repository.
 create_stream_handle failed requested object was not found in the repository.
 Getting DB object ('A4NOXXXXXXXXXK2N2U') info from repository failed requested object was not found in
 the repository. Command get_owner_list failed when creating the stream component. requested object was not
found in the repository. Failed getting stream handle requested object was not found in the repository.
 create_stream_handle failed

I checked at both network and DB end an there seems to be no issue. Please suggest.


来源: stackexchange

问:
How to exec bash script w/o exiting shell
I want to execute a bash script in the current shell, not a subshell/subprocess. I believe using exec allows you to do that.
But if I run:

```<code>exec ./my_script.sh
</code>```

the shell will exit and it will say "process completed". Is there a way to execute a script in the same shell somehow w/o exiting the process.

note the only thing my_script.sh does is:

```<code>export foo=bar
</code>```

but if there was some error in my script, it didn't appear in the console.

答:
As @Snakienn has said, you can / should use the "." builtin command to "source" the file containing commands; e.g.

```<code> . ./my_script.sh
</code>```

What this does is to temporarily change where the shell is reading commands from.  Commands and other shell input are read from the file as if they were being read from the terminal.  When the shell gets to the end-of-file, it switches back to taking input from the console.

This is called "sourcing". (Not "execing".)   And indeed the shell accepts source as an alternative name for the . command.

The exec command does something completely different.  As the bash manual entry says:

```<code> exec [-cl] [-a name] [command [arguments]]
</code>```

If command is specified, it replaces the shell.  No new process is created.  The arguments become the arguments to command.

The concept and terminology of exec comes from early UNIX (i.e Unix V6 or earlier) where the syscalls for running a child command were fork and exec.  The procedure was:

fork the current process creating a clone of current process (the child)

in the child process exec the new command

in the parent process, wait for the child process to complete

ContentLicense: CC BY-SA 4.0

Body:
I want to execute a bash script in the current shell, not a subshell/subprocess. I believe using exec allows you to do that.
But if I run:

exec ./my_script.sh

the shell will exit and it will say "process completed". Is there a way to execute a script in the same shell somehow w/o exiting the process.

note the only thing my_script.sh does is:

export foo=bar

but if there was some error in my script, it didn't appear in the console.

Body:
As @Snakienn has said, you can / should use the "." builtin command to "source" the file containing commands; e.g.

 . ./my_script.sh

What this does is to temporarily change where the shell is reading commands from.  Commands and other shell input are read from the file as if they were being read from the terminal.  When the shell gets to the end-of-file, it switches back to taking input from the console.

This is called "sourcing". (Not "execing".)   And indeed the shell accepts source as an alternative name for the . command.

The exec command does something completely different.  As the bash manual entry says:

 exec [-cl] [-a name] [command [arguments]]

If command is specified, it replaces the shell.  No new process is created.  The arguments become the arguments to command.

The concept and terminology of exec comes from early UNIX (i.e Unix V6 or earlier) where the syscalls for running a child command were fork and exec.  The procedure was:

fork the current process creating a clone of current process (the child)

in the child process exec the new command

in the parent process, wait for the child process to complete


问:
How to do video annotations using javascript?
My question is how to do video annotations like youtube, but in the file html with my own video, using javascript. The annotations wolud like be links and also text only. And can put the annotation anywhere in the video.
Thanks </p>

答:
Searched all night and found this one. Check this demo. Let me know if this is helpful.

window['ann'] = [{'at':100,'msg':'Wow!'},{'at':230,'msg':'What!'}];

var currentFrame = $('#currentFrame');
var video = VideoFrame({
    id : 'video',
    frameRate: 29.97,
    callback : function(frame) {
    ann.forEach(function(ele){
    if (frame == ele['at']) {
      currentFrame.html(ele['msg']);
    }
    });
    }
});

$('#play-pause').click(function(){
    ChangeButtonText();
});

function ChangeButtonText(){
  if(video.video.paused){
        video.video.play();
        video.listen('frame');
        $("#play-pause").html('Pause');
    }else{
        video.video.pause();
        video.stopListen();
        $("#play-pause").html('Play');
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://rawgit.com/allensarkisyan/VideoFrame/master/VideoFrame.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  <div class="frame">
  <h3 style="color:white;position:absolute;left:50%;top:10%; z-index:100;" id="currentFrame">Annotation board</h3>
  </div>

<video height="180" width="100%" id="video">
  <source src="http://www.w3schools.com/html/mov_bbb.mp4"></source>
</video>

  <button style="color:red;position:absolute;left:3%;top10%;" id="play-pause">Play</button></code>```

ContentLicense: CC BY-SA 3.0

Body:
Searched all night and found this one. Check this demo. Let me know if this is helpful.

window['ann'] = [{'at':100,'msg':'Wow!'},{'at':230,'msg':'<a href="https://www.stackoverflow.com" >What!</a>'}];

var currentFrame = $('#currentFrame');
var video = VideoFrame({
    id : 'video',
    frameRate: 29.97,
    callback : function(frame) {
    ann.forEach(function(ele){
    if (frame == ele['at']) {
      currentFrame.html(ele['msg']);
    }
    });
    }
});

$('#play-pause').click(function(){
    ChangeButtonText();
});

function ChangeButtonText(){
  if(video.video.paused){
        video.video.play();
        video.listen('frame');
        $("#play-pause").html('Pause');
    }else{
        video.video.pause();
        video.stopListen();
        $("#play-pause").html('Play');
    }
  }

<script src="https://rawgit.com/allensarkisyan/VideoFrame/master/VideoFrame.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  <div class="frame">
  <h3 style="color:white;position:absolute;left:50%;top:10%; z-index:100;" id="currentFrame">Annotation board</h3>
  </div>

<video height="180" width="100%" id="video">
  <source src="http://www.w3schools.com/html/mov_bbb.mp4"></source>
</video>

  <button style="color:red;position:absolute;left:3%;top10%;" id="play-pause">Play</button>


问:
A recursive function to extract the files from a nested JSON like object
I have a data which consists of directory name and its files . Given a specific directory name in the argument say , I need to find all the files it encloses .
my data :

```<code>var fileData = {
      dir : 'app',
      files : [
        'index.html',
        {
          dir : 'js',
          files: [
            'main.js',
            'app.js',
            'misc.js',
            {
              dir : 'vendor',
              files : [
                'jquery.js',
                'underscore.js'
              ]
            }
          ]
        },
        {
          dir : 'css',
          files : [
            'reset.css',
            'main.css'
          ]
        }
      ]
    };
</code>```

I have a function listfiles where I am passing the directory name

```<code>listFiles(fileData, 'js')
</code>```

Expected output :

```<code>['main.js','app.js','misc.js','jquery.js','underscore.js']
</code>```

In my code i am able to get the answer in the console but could not return the value .

```<code>listFiles = (data, dirName) => {
          var filesArray = [];
          matchedDir = (data,dirName) => {
            data['files'].map(el => {
                if(typeof(el) === 'object'){
                  return matchedDir(el,dirName)
                }
                else{filesArray.push(el)}
              })
              console.log(filesArray)
            }
          if(Object.values(data).includes(dirName)) {
            return matchedDir(data,dirName)
          }
          else{
            data['files'].map(el => {
              if(typeof(el) === 'object'){
                return this.listFiles(el,dirName)
              }
            })
          }
        return filesArray
}
</code>```

答:
Create the result array on the initial call of the function, and pass that array along on every recursive call:

const getAllFilesFromDirectory = ({ dir, files }, dirToFind, result = [], parentMatch = false) => {
  const addItemsThisDirectory = parentMatch || dir === dirToFind;
  files.forEach((fileOrDir) => {
    if (typeof fileOrDir === 'string') {
      if (addItemsThisDirectory) {
        result.push(fileOrDir);
      }
    } else {
      getAllFilesFromDirectory(fileOrDir, dirToFind, result, addItemsThisDirectory);
    }
  });
  return result;
};

var fileData = {
  dir: 'app',
  files: [
    'index.html',
    {
      dir: 'js',
      files: [
        'main.js',
        'app.js',
        'misc.js',
        {
          dir: 'vendor',
          files: [
            'jquery.js',
            'underscore.js'
          ]
        }
      ]
    },
    {
      dir: 'css',
      files: [
        'reset.css',
        'main.css'
      ]
    }
  ]
};
console.log(getAllFilesFromDirectory(fileData, 'js'));```

Body:
I have a data which consists of directory name and its files . Given a specific directory name in the argument say , I need to find all the files it encloses .
my data :

var fileData = {
      dir : 'app',
      files : [
        'index.html',
        {
          dir : 'js',
          files: [
            'main.js',
            'app.js',
            'misc.js',
            {
              dir : 'vendor',
              files : [
                'jquery.js',
                'underscore.js'
              ]
            }
          ]
        },
        {
          dir : 'css',
          files : [
            'reset.css',
            'main.css'
          ]
        }
      ]
    };

I have a function listfiles where I am passing the directory name

listFiles(fileData, 'js')

Expected output :

['main.js','app.js','misc.js','jquery.js','underscore.js']

In my code i am able to get the answer in the console but could not return the value .

listFiles = (data, dirName) => {
          var filesArray = [];
          matchedDir = (data,dirName) => {
            data['files'].map(el => {
                if(typeof(el) === 'object'){
                  return matchedDir(el,dirName)
                }
                else{filesArray.push(el)}
              })
              console.log(filesArray)
            }
          if(Object.values(data).includes(dirName)) {
            return matchedDir(data,dirName)
          }
          else{
            data['files'].map(el => {
              if(typeof(el) === 'object'){
                return this.listFiles(el,dirName)
              }
            })
          }
        return filesArray
}


问:
Default argument vs std::optional as an argument vs Function Overloading
Let's say I'm implementing a function func.

I have a use case where func will be invoked with two parameters.

I have another use case where func will be invoked with just one parameter but a default value of the missing second parameter will be used within the function.

I can think of 3 possible ways of implementing this functionality:

Default Argument

```<code>void func(int a, long b = c);
</code>```

func will be invoked like this:

```<code>func(a);
func(a, b);
</code>```

Function Overloading

```<code>void func(int a);
void func(int a, long b);
</code>```

func will be invoked like this:

```<code>func(a);
func(a, b);
</code>```

Using Optional as a function argument

```<code>void func(int a, optional<long> b);
</code>```

func will be invoked like this:

```<code>func(a, optional<long> ());
func(a, b);
</code>```

I want to know what's the best way of implementing the desired functionality. Any suggestions are welcome.

答:
There are two questions to ask yourself when considering this:

Does the optional argument have a logical default?

Is the function implemented the same when the optional argument is given and when it's not?

If the second argument has a logical default and the function does the same thing no matter what, then a default argument works well.  For example:

```<code>std::vector<std::string> split_string(const std::string& str, char sep = ' ');
</code>```

By default, this splits a string on spaces, but the separator can be given to change that.  It makes little sense to split this into two overloads or use a std::optional here.

If the second argument doesn't have a logical default but the function is still mostly the same if it isn't given, then std::optional makes more sense.  For example:

```<code>void extract(const std::filesystem::path& archive_file,
             const std::filesystem::path& output_dir,
             std::optional<std::regex> exclude_filter = {});
</code>```

Here we're extracting files from an archive file and writing the extracted files to disk, optionally excluding files that match some pattern.  The function definition would be fundamentally the same with or without the filter; it's just one extra line difference:

```<code>if (exclude_filter && std::regex_match(file, *exclude_filter) continue;
</code>```

It doesn't make much sense to duplicate the definition, so overloading doesn't really make sense.  At the same time, there's no "don't match anything" regex, so there's not a logical default filter that could be applied.  std::optional is a perfect fit here.

Note that I did still use a default argument.  Defaulting your std::optional to be empty can make your calls much nicer.

Lastly, if the function implementation is fundamentally different between the one-arg and two-arg versions, then use an overload.  For example:

```<code>void hide(window& win) {
    win.set_visible(false);
}

template <typename rep, typename period>
void hide(window& win, const std::chrono::duration<rep, period>& fade_time) {
    auto wait_time = equal_intervals(fade_time, win.opacity());
    while (win.oapcity() > 0) {
        win.set_opacity(win.opacity() - 1);
        std::this_thread::sleep_for(wait_time);
    }
}
</code>```

Here we're hiding a window with an optional fade out time.  While the functions logically do the same thing, they're implemented totally differently.  Being the same function doesn't make a lot of sense.  Even though 0 would be a logical default fade time, it still doesn't make sense to use a default argument here since you would just end up with a big if block:

```<code>if (fade_time == 0) {
    // body of the first overload
} else {
    // body of the second overload
}
</code>```

Body:
Let's say I'm implementing a function func.

I have a use case where func will be invoked with two parameters.

I have another use case where func will be invoked with just one parameter but a default value of the missing second parameter will be used within the function.

I can think of 3 possible ways of implementing this functionality:

Default Argument

void func(int a, long b = c);

func will be invoked like this:

func(a);
func(a, b);

Function Overloading

void func(int a);
void func(int a, long b);

func will be invoked like this:

func(a);
func(a, b);

Using Optional as a function argument

void func(int a, optional<long> b);

func will be invoked like this:

func(a, optional<long> ());
func(a, b);

I want to know what's the best way of implementing the desired functionality. Any suggestions are welcome.

Body:
There are two questions to ask yourself when considering this:

Does the optional argument have a logical default?

Is the function implemented the same when the optional argument is given and when it's not?

If the second argument has a logical default and the function does the same thing no matter what, then a default argument works well.  For example:

std::vector<std::string> split_string(const std::string& str, char sep = ' ');

By default, this splits a string on spaces, but the separator can be given to change that.  It makes little sense to split this into two overloads or use a std::optional here.

If the second argument doesn't have a logical default but the function is still mostly the same if it isn't given, then std::optional makes more sense.  For example:

void extract(const std::filesystem::path& archive_file,
             const std::filesystem::path& output_dir,
             std::optional<std::regex> exclude_filter = {});

Here we're extracting files from an archive file and writing the extracted files to disk, optionally excluding files that match some pattern.  The function definition would be fundamentally the same with or without the filter; it's just one extra line difference:

if (exclude_filter && std::regex_match(file, *exclude_filter) continue;

It doesn't make much sense to duplicate the definition, so overloading doesn't really make sense.  At the same time, there's no "don't match anything" regex, so there's not a logical default filter that could be applied.  std::optional is a perfect fit here.

Note that I did still use a default argument.  Defaulting your std::optional to be empty can make your calls much nicer.

Lastly, if the function implementation is fundamentally different between the one-arg and two-arg versions, then use an overload.  For example:

void hide(window& win) {
    win.set_visible(false);
}

template <typename rep, typename period>
void hide(window& win, const std::chrono::duration<rep, period>& fade_time) {
    auto wait_time = equal_intervals(fade_time, win.opacity());
    while (win.oapcity() > 0) {
        win.set_opacity(win.opacity() - 1);
        std::this_thread::sleep_for(wait_time);
    }
}

Here we're hiding a window with an optional fade out time.  While the functions logically do the same thing, they're implemented totally differently.  Being the same function doesn't make a lot of sense.  Even though 0 would be a logical default fade time, it still doesn't make sense to use a default argument here since you would just end up with a big if block:

if (fade_time == 0) {
    // body of the first overload
} else {
    // body of the second overload
}


问:
Change class for last two rows in a while loop
I have a while loop that displays result from a MySQL query. I know how to change the output for the last row or an odd row but how can I change the output for the last two results?

For example I have a list of results in a 2x2 matrix with border-bottom: 1px on each result but I would like to display the bottom two without the border?

答:
If you can use css3, it´s easy (I´ll use a list for the example):

```<code>li:nth-last-child(-n+2)
</code>```

selects the last two li's.

If you want to do it in php, you can count the number of results, add a counter in your loop and add a class to the last two items.

Body:
If you can use css3, it´s easy (I´ll use a list for the example):

li:nth-last-child(-n+2)

selects the last two li's.

If you want to do it in php, you can count the number of results, add a counter in your loop and add a class to the last two items.


问:
How can I create a dynamic while loop?
```<code>when(cShotCount) {
  in 0..4 -> { // If the total shot count is between 0 and 4
   levelTextView ? .text = "Level: " + 0 // Display level
   editor2?.putInt("levelCount", 0) // Set level
   editor2?.apply()
   mChart.setProgress(((cShotCount?.toFloat()!! - 0) / 5) * 100, true) // Display progress
   mChart.progressColor(Color.BLUE) // Set progress bar color
  }
</code>```

My problem follows:

My "game" has 50 levels. Each level is a range, i.e. 0..4, 5..18, 19..41, etc. Obviously, I don't want to copy/paste the above code 50 times, and then manually change the level display, level count, progress indicator and progress bar color (4 variables).

I thought about creating a list of objects that contain "starting value of range", "ending value of range", "corresponding level value", "value of progress bar", but I'm not sure how I would implement them into the loop. Any ideas?

答:
You can create a data class for each level, and put all your levels in a list. Then make a function that does the leveling stuff - you don't want to put all your code in a single loop:

```<code>data class Level(
    val shotRange: IntRange,
    val level: Int,
    val color: Color
)

val levels = listOf(
    Level(0..4, 0, Color.BLUE)
    // Add all levels
)

fun setLevel(cShotCount: Int) {
    val level = levels.find { cShotCount in it.shotRange }
        ?: throw IllegalArgumentException("Shot count out of level range")
    levelTextView.text = "Level: ${level.level}" // Display level
    editor2.putInt("levelCount", 0) // Set level
    editor2.apply()
    mChart.setProgress(cShotCount.toFloat() / (level.shotRange.endInclusive + 1) * 100, true) // Display progress
    mChart.progressColor(level.color) // Set progress bar color
}
</code>```

Then in your loop you can then invoke the setLevel function to set the level:

```<code>var cShotCount = 0
while (true) {
    // Do stuff
    setLevel(cShotCount)
}
</code>```

You may optimize the level searching by putting the levels in a better data structure to optimize searching for the level.
If you have a foreseeable amount of shot counts, you could make an Array<Level> indexed by the shotcount to get a fast O(1) lookup. Or you could use a tree, do binary searches, etc.

Title: How can I create a dynamic while loop?

Body:
when(cShotCount) {
  in 0..4 -> { // If the total shot count is between 0 and 4
   levelTextView ? .text = "Level: " + 0 // Display level
   editor2?.putInt("levelCount", 0) // Set level
   editor2?.apply()
   mChart.setProgress(((cShotCount?.toFloat()!! - 0) / 5) * 100, true) // Display progress
   mChart.progressColor(Color.BLUE) // Set progress bar color
  }

My problem follows:

My "game" has 50 levels. Each level is a range, i.e. 0..4, 5..18, 19..41, etc. Obviously, I don't want to copy/paste the above code 50 times, and then manually change the level display, level count, progress indicator and progress bar color (4 variables).

I thought about creating a list of objects that contain "starting value of range", "ending value of range", "corresponding level value", "value of progress bar", but I'm not sure how I would implement them into the loop. Any ideas?

Body:
You can create a data class for each level, and put all your levels in a list. Then make a function that does the leveling stuff - you don't want to put all your code in a single loop:

data class Level(
    val shotRange: IntRange,
    val level: Int,
    val color: Color
)

val levels = listOf(
    Level(0..4, 0, Color.BLUE)
    // Add all levels
)

fun setLevel(cShotCount: Int) {
    val level = levels.find { cShotCount in it.shotRange }
        ?: throw IllegalArgumentException("Shot count out of level range")
    levelTextView.text = "Level: ${level.level}" // Display level
    editor2.putInt("levelCount", 0) // Set level
    editor2.apply()
    mChart.setProgress(cShotCount.toFloat() / (level.shotRange.endInclusive + 1) * 100, true) // Display progress
    mChart.progressColor(level.color) // Set progress bar color
}

Then in your loop you can then invoke the setLevel function to set the level:

var cShotCount = 0
while (true) {
    // Do stuff
    setLevel(cShotCount)
}

You may optimize the level searching by putting the levels in a better data structure to optimize searching for the level.
If you have a foreseeable amount of shot counts, you could make an Array<Level> indexed by the shotcount to get a fast O(1) lookup. Or you could use a tree, do binary searches, etc.


问:
Split String by Two Characters Ignore Whitespace Before, In Between or After any of the Characters
I have an input string for example

```<code>var input = "'Test string','abc'";
</code>```

I want to split it by exactly two characters that is ', ignoring white spaces before, in between or after the delimiters. For example based on the input I'm expecting the following output.

```<code>index0='Test string'
index1='abc'
</code>```

I want to retain that output even if my input looks like any of these.

```<code>var input = "'Test string','abc'";
var input = "'Test string ','abc'";
var input = "'Test string' ,'abc'";
var input = "'Test string', 'abc'";
var input = "'Test string   '   ,   'abc'";
</code>```

As long as there are two characters ', (single quote and comma) regardless that they have spaces before, in between or after, I want to split a string based on those two char delimiters. Splitting should only by two chars. If an input has only ' or , retain the input as is. Only split the input by ', not by any of the two chars. Please help. Here's my code.

```<code>   static void Main(string[] args)
    {
        var input = "'Test string','abc'";
        var results = Regex.Split(input, @"[ ',]+");
        foreach (var item in results)
            Console.WriteLine(item);
        Console.ReadLine();

    }
</code>```

答:
If the input is predictable and never contains an escaped quotation mark, you can do this:

```<code>input.Split('\'').Where((x, i) => i % 2 == 1).Select(p => p.Trim());
</code>```

See it in use here: https://dotnetfiddle.net/AqookJ

```<code>input.Split('\'')
</code>```

Splits the input by '

```<code>.Where((x, i) => i % 2 == 1)
</code>```

Selects every second item of the split, which is everything inside of quotes in this context. For efficiency this can be changed to (x, i) => (i & 1) == 1

```<code>.Select(p => p.Trim())
</code>```

Will remove whitespace from the beginning and end of every item in the collection.

If however there are quotation marks inside of the target strings you can use this following method:

```<code>public static IEnumerable<string> Split(string inpt)
{
    IEnumerable<string> res = Regex.Split(inpt, @"('\s*,\s*'|^\s*'|'\s*$)").Where((x, i) => i % 2 == 0).Select(p => p.Trim()).Skip(1);
    return res.Take(res.Count() - 1);
}
</code>```

This will split the input by '\s*,\s*', and also by ^\s*' and '\s*$.

It will then discard the first and last items of the collection, which will be the first and last quotation marks.

See it in action here: https://dotnetfiddle.net/sQ6Y2x

Body:
I have an input string for example

var input = "'Test string','abc'";

I want to split it by exactly two characters that is ', ignoring white spaces before, in between or after the delimiters. For example based on the input I'm expecting the following output.

index0='Test string'
index1='abc'

I want to retain that output even if my input looks like any of these.

var input = "'Test string','abc'";
var input = "'Test string ','abc'";
var input = "'Test string' ,'abc'";
var input = "'Test string', 'abc'";
var input = "'Test string   '   ,   'abc'";

As long as there are two characters ', (single quote and comma) regardless that they have spaces before, in between or after, I want to split a string based on those two char delimiters. Splitting should only by two chars. If an input has only ' or , retain the input as is. Only split the input by ', not by any of the two chars. Please help. Here's my code.

   static void Main(string[] args)
    {
        var input = "'Test string','abc'";
        var results = Regex.Split(input, @"[ ',]+");
        foreach (var item in results)
            Console.WriteLine(item);
        Console.ReadLine();

    }

Body:
If the input is predictable and never contains an escaped quotation mark, you can do this:

input.Split('\'').Where((x, i) => i % 2 == 1).Select(p => p.Trim());

See it in use here: https://dotnetfiddle.net/AqookJ

input.Split('\'')

Splits the input by '

.Where((x, i) => i % 2 == 1)

Selects every second item of the split, which is everything inside of quotes in this context. For efficiency this can be changed to (x, i) => (i & 1) == 1

.Select(p => p.Trim())

Will remove whitespace from the beginning and end of every item in the collection.

If however there are quotation marks inside of the target strings you can use this following method:

public static IEnumerable<string> Split(string inpt)
{
    IEnumerable<string> res = Regex.Split(inpt, @"('\s*,\s*'|^\s*'|'\s*$)").Where((x, i) => i % 2 == 0).Select(p => p.Trim()).Skip(1);
    return res.Take(res.Count() - 1);
}

This will split the input by '\s*,\s*', and also by ^\s*' and '\s*$.

It will then discard the first and last items of the collection, which will be the first and last quotation marks.

See it in action here: https://dotnetfiddle.net/sQ6Y2x


问:
RegEx for matching URLs and failing non-URLs
I am trying to extract separated urls from srcset of an image.

This is for extracting and downloading all the files present in the row.
I am not hard coding it because row can differ from time to time.

txt = "images/1x/1083bce6__color_272x92dp.png 1x, images/2x/b3716cd2_color_272x92dp.png 2x"

reg = re.compile(r"((?:[^\s,]+))(?:.*?,)?").finditer

for i in list(reg(txt)):
   print(i.group(1))

```

<p>I expect the result to be two urls</p>

```images/1x/1083bce6__color_272x92dp.png
images/2x/b3716cd2_color_272x92dp.png
```

But I get three with extra being

2x

答:
Here, we would add a quantifier to a simple char class in an expression such as:

```<code>[^\s]{4,}
</code>```

to get our desired URLs.

Demo

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"[^\s]{4,}"

test_str = "images/1x/1083bce6__color_272x92dp.png 1x, images/2x/b3716cd2_color_272x92dp.png 2x"

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

Body:
I am trying to extract separated urls from srcset of an image.

This is for extracting and downloading all the files present in the row.
I am not hard coding it because row can differ from time to time.

txt = "images/1x/1083bce6__color_272x92dp.png 1x, images/2x/b3716cd2_color_272x92dp.png 2x"

reg = re.compile(r"((?:[^\s,]+))(?:.*?,)?").finditer

for i in list(reg(txt)):
   print(i.group(1))

I expect the result to be two urls

images/1x/1083bce6__color_272x92dp.png
images/2x/b3716cd2_color_272x92dp.png

But I get three with extra being

2x

Body:
Here, we would add a quantifier to a simple char class in an expression such as:

[^\s]{4,}

to get our desired URLs.

Demo

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"[^\s]{4,}"

test_str = "images/1x/1083bce6__color_272x92dp.png 1x, images/2x/b3716cd2_color_272x92dp.png 2x"

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:


问:
Nested Loop React Native
I'm trying to do a nested loop in react native render, but i got unexpected error token. Can anyone help?

here are my codes:

```<code><ScrollView style={{backgroundColor: 'rgba(255, 0, 0, 0.1)'}}>
                {

                    items.map((val,key) => {
                        return <View key={key}>
                            <Separator style={{backgroundColor: 'rgba(255, 0, 0, 0.1)'}}>
                                <Text>{key+1} - {val.title}</Text>
                            </Separator>
                            {
                                items[key].videos.map((value,index) => {
                                    return <ListItem noIndent key={index} style={{backgroundColor: 'rgba(255, 0, 0, 0.1)'}} onPress={() => this.setState({video_url: items[key].videos[index].video_url})}>
                                        <Body>
                                            <Text style={{paddingLeft: 25}}>{index+1} {value.title}</Text>
                                        </Body>
                                    </ListItem>
                                })
                                items[key].videos.map((value,index) => {
                                    return <ListItem noIndent key={index} style={{backgroundColor: 'rgba(255, 0, 0, 0.1)'}} >
                                        <Body>
                                            <Text style={{paddingLeft: 25}}>{index+1} {value.title}</Text>
                                        </Body>
                                    </ListItem>
                                })
                            }
                        </View>
                    })
                }
                </ScrollView>
</code>```

this is my error
error image

答:
```<code>keyExtractor = (item, index) => index.toString()

const ListItem = (props) => {
   return
      <View>
        {props.items.videos.map(row => {
          return <View>row.title</View>;
        })}
      </View>

}

render () {
  return (
    <FlatList
      keyExtractor={this.keyExtractor}
      data={items}
      renderItem={items=> {
       return <ListItem {...items} />;
    />
  )
</code>```

can you test this..

Title: Nested Loop React Native

Body:
I'm trying to do a nested loop in react native render, but i got unexpected error token. Can anyone help?

here are my codes:

<ScrollView style={{backgroundColor: 'rgba(255, 0, 0, 0.1)'}}>
                {

                    items.map((val,key) => {
                        return <View key={key}>
                            <Separator style={{backgroundColor: 'rgba(255, 0, 0, 0.1)'}}>
                                <Text>{key+1} - {val.title}</Text>
                            </Separator>
                            {
                                items[key].videos.map((value,index) => {
                                    return <ListItem noIndent key={index} style={{backgroundColor: 'rgba(255, 0, 0, 0.1)'}} onPress={() => this.setState({video_url: items[key].videos[index].video_url})}>

                                            <Text style={{paddingLeft: 25}}>{index+1} {value.title}</Text>

                                    </ListItem>
                                })
                                items[key].videos.map((value,index) => {
                                    return <ListItem noIndent key={index} style={{backgroundColor: 'rgba(255, 0, 0, 0.1)'}} >

                                            <Text style={{paddingLeft: 25}}>{index+1} {value.title}</Text>

                                    </ListItem>
                                })
                            }
                        </View>
                    })
                }
                </ScrollView>

this is my error
error image

Body:
keyExtractor = (item, index) => index.toString()

const ListItem = (props) => {
   return
      <View>
        {props.items.videos.map(row => {
          return <View>row.title</View>;
        })}
      </View>

}

render () {
  return (
    <FlatList
      keyExtractor={this.keyExtractor}
      data={items}
      renderItem={items=> {
       return <ListItem {...items} />;
    />
  )

can you test this..


问:
WPF application get crashed on pressing right mouse button
I am actually trying to making an Jarvis AI program in c# wpf but i am getting exception in the codes. Actually the problem is when ever in press the right mouse button on my running application, the application gets stuck and crashed can any one can help me in solving this. </p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace jarvis
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

    }
}
</code>```

答:
```<code>      private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
      {
        e.handled = true;  //in your case, prevent right click crash.
        this.DragMove();
      }
</code>```

Body:
I am actually trying to making an Jarvis AI program in c# wpf but i am getting exception in the codes. Actually the problem is when ever in press the right mouse button on my running application, the application gets stuck and crashed can any one can help me in solving this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace jarvis
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

    }
}


问:
Error on Auth section in AWS SAM template
To enable AWS_IAM auth and CORS, I made my sam template as follows.

However, I got an error saying

Failed to create the changeset: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: Transform AWS::Serverless-2016-10-31 failed with: Invalid Serverless Application Specification document. Number of errors found: 1. Resource with id [ListFunction] is invalid. Event with id [ListFunctionCors] is invalid. Unable to set Authorizer [NONE] on API method [options] for path [/list] because the related API does not define any Authorizers.

What is wrong here?

```<code>AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  ListApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Auth:
        DefaultAuthorizer: AWS_IAM
      Cors:
        AllowMethods: "'*'"
        AllowHeaders: "'*'"
        AllowOrigin: "'*'"
  ListFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: app_src/
      Handler: app.lambda_handler
      Runtime: python3.7
      Events:
        ListFunction:
          Type: Api
          Properties:
            RestApiId: !Ref ListApi
            Path: /list
            Method: GET
        ListFunctionCors:
          Type: Api
          Properties:
            RestApiId: !Ref ListApi
            Path: /list
            Method: OPTIONS
            Auth:
              Authorizer: 'NONE'
</code>```

答:
Just ran into this same problem, and figured it out. Per https://github.com/awslabs/serverless-application-model/issues/781, that function event should be:

```<code>ListFunctionCors:
          Type: Api
          Properties:
            RestApiId: !Ref ListApi
            Path: /list
            Method: OPTIONS
            Auth:
              Authorizer: null
</code>```

It's Authorizer: null, not Authorizer: 'NONE'.

Hope this helps!

Body:
To enable AWS_IAM auth and CORS, I made my sam template as follows.

However, I got an error saying

Failed to create the changeset: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: Transform AWS::Serverless-2016-10-31 failed with: Invalid Serverless Application Specification document. Number of errors found: 1. Resource with id [ListFunction] is invalid. Event with id [ListFunctionCors] is invalid. Unable to set Authorizer [NONE] on API method [options] for path [/list] because the related API does not define any Authorizers.

What is wrong here?

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  ListApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Auth:
        DefaultAuthorizer: AWS_IAM
      Cors:
        AllowMethods: "'*'"
        AllowHeaders: "'*'"
        AllowOrigin: "'*'"
  ListFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: app_src/
      Handler: app.lambda_handler
      Runtime: python3.7
      Events:
        ListFunction:
          Type: Api
          Properties:
            RestApiId: !Ref ListApi
            Path: /list
            Method: GET
        ListFunctionCors:
          Type: Api
          Properties:
            RestApiId: !Ref ListApi
            Path: /list
            Method: OPTIONS
            Auth:
              Authorizer: 'NONE'

Body:
Just ran into this same problem, and figured it out. Per https://github.com/awslabs/serverless-application-model/issues/781, that function event should be:

ListFunctionCors:
          Type: Api
          Properties:
            RestApiId: !Ref ListApi
            Path: /list
            Method: OPTIONS
            Auth:
              Authorizer: null

It's Authorizer: null, not Authorizer: 'NONE'.

Hope this helps!


问:
Can't make the vert.x + kotlin + gradle hot redeploy works
I just start looking into vert.x and downloaded an example restful project from https://github.com/vert-x3/vertx-examples/tree/master/kotlin-examples/web. According to the readme, it should be able to auto-reploy when there's any file change, but it doesn't seem to work. No matter how many times I changed the main class file, it still cannot be reflected. What I've done was:

Run the "gradlew run"

```<code>C:\vertx-examples-master\kotlin-examples\web>gradlew run
:compileKotlin UP-TO-DATE
:compileJava UP-TO-DATE
:copyMainKotlinClasses UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:run
Jan 08, 2018 7:16:04 PM io.vertx.core.impl.launcher.commands.Watcher
INFO: Watched paths: [C:\vertx-examples-master\kotlin-examples\web\.\out]
Jan 08, 2018 7:16:04 PM io.vertx.core.impl.launcher.commands.Watcher
INFO: Starting the vert.x application in redeploy mode
Starting vert.x application...
58d1ec56-6d4c-4209-9fba-71cd6f54101c-redeploy
Jan 08, 2018 7:16:05 PM
io.vertx.core.impl.launcher.commands.VertxIsolatedDeployer
INFO: Succeeded in deploying verticle
</code>```

Change source file and the launcher was able to detect the changes and said it re-deployed the Verticle

```<code>Jan 08, 2018 7:16:46 PM io.vertx.core.impl.launcher.commands.Watcher
INFO: Redeploying!
Stopping vert.x application '58d1ec56-6d4c-4209-9fba-71cd6f54101c-redeploy'
Application '58d1ec56-6d4c-4209-9fba-71cd6f54101c-redeploy' terminated with
status 0
'.' is not recognized as an internal or external command,
operable program or batch file.
Jan 08, 2018 7:16:47 PM io.vertx.core.impl.launcher.commands.Watcher
INFO: User command terminated with status 1
Starting vert.x application...
58d1ec56-6d4c-4209-9fba-71cd6f54101c-redeploy
Jan 08, 2018 7:16:47 PM io.vertx.core.impl.launcher.commands.Watcher
INFO: Redeployment done in 966 ms.
Jan 08, 2018 7:16:48 PM
io.vertx.core.impl.launcher.commands.VertxIsolatedDeployer
INFO: Succeeded in deploying verticle
</code>```

But indeed it's still running the old code

My question is anything I need to do in order to make it work properly. I spent a day and browse for solution but still can't get through it.

Thanks a lot.

答:
I have the same problem but with the help of this file to be exact. I end with this batch file that help me to redeploy (tested on windows).

My project was named: testws and my main verticle was named: MainVerticle be sure to replace with yours owns.

redeploy.bat

@echo off

SET LAUNCHER="io.vertx.core.Launcher"
SET VERTICLE="juan.testws.MainVerticle"
SET CMD="gradlew classes"

call gradlew copyDependencies
call gradlew classes

java -cp  "build\dependencies\*;build\classes\kotlin\main" %LAUNCHER% run^
 %VERTICLE% --redeploy="src\main\**\*" --on-redeploy=%CMD% --launcher-class=%LAUNCHER%

```

<p>and a gradle task added to</p>

<p><strong>build.gradle</strong> </p>

```...  // rest of the file
task copyDependencies(type: Copy) {
  from configurations.default
  into 'build\\dependencies'
}
```

Almost the same version works on java, only replace "kotlin" by "java" on the file.

Body:
I just start looking into vert.x and downloaded an example restful project from https://github.com/vert-x3/vertx-examples/tree/master/kotlin-examples/web. According to the readme, it should be able to auto-reploy when there's any file change, but it doesn't seem to work. No matter how many times I changed the main class file, it still cannot be reflected. What I've done was:

Run the "gradlew run"

C:\vertx-examples-master\kotlin-examples\web>gradlew run
:compileKotlin UP-TO-DATE
:compileJava UP-TO-DATE
:copyMainKotlinClasses UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:run
Jan 08, 2018 7:16:04 PM io.vertx.core.impl.launcher.commands.Watcher
INFO: Watched paths: [C:\vertx-examples-master\kotlin-examples\web\.\out]
Jan 08, 2018 7:16:04 PM io.vertx.core.impl.launcher.commands.Watcher
INFO: Starting the vert.x application in redeploy mode
Starting vert.x application...
58d1ec56-6d4c-4209-9fba-71cd6f54101c-redeploy
Jan 08, 2018 7:16:05 PM
io.vertx.core.impl.launcher.commands.VertxIsolatedDeployer
INFO: Succeeded in deploying verticle

Change source file and the launcher was able to detect the changes and said it re-deployed the Verticle

Jan 08, 2018 7:16:46 PM io.vertx.core.impl.launcher.commands.Watcher
INFO: Redeploying!
Stopping vert.x application '58d1ec56-6d4c-4209-9fba-71cd6f54101c-redeploy'
Application '58d1ec56-6d4c-4209-9fba-71cd6f54101c-redeploy' terminated with
status 0
'.' is not recognized as an internal or external command,
operable program or batch file.
Jan 08, 2018 7:16:47 PM io.vertx.core.impl.launcher.commands.Watcher
INFO: User command terminated with status 1
Starting vert.x application...
58d1ec56-6d4c-4209-9fba-71cd6f54101c-redeploy
Jan 08, 2018 7:16:47 PM io.vertx.core.impl.launcher.commands.Watcher
INFO: Redeployment done in 966 ms.
Jan 08, 2018 7:16:48 PM
io.vertx.core.impl.launcher.commands.VertxIsolatedDeployer
INFO: Succeeded in deploying verticle

But indeed it's still running the old code

My question is anything I need to do in order to make it work properly. I spent a day and browse for solution but still can't get through it.

Thanks a lot.

Body:
I have the same problem but with the help of this file to be exact. I end with this batch file that help me to redeploy (tested on windows).

My project was named: testws and my main verticle was named: MainVerticle be sure to replace with yours owns.

redeploy.bat

@echo off

SET LAUNCHER="io.vertx.core.Launcher"
SET VERTICLE="juan.testws.MainVerticle"
SET CMD="gradlew classes"

call gradlew copyDependencies
call gradlew classes

java -cp  "build\dependencies\*;build\classes\kotlin\main" %LAUNCHER% run^
 %VERTICLE% --redeploy="src\main\**\*" --on-redeploy=%CMD% --launcher-class=%LAUNCHER%

and a gradle task added to

build.gradle

...  // rest of the file
task copyDependencies(type: Copy) {
  from configurations.default
  into 'build\\dependencies'
}

Almost the same version works on java, only replace "kotlin" by "java" on the file.


问:
How to make a HTTP POST request when the data parameter includes an ampersand?
I am attempting to access data on lobbying expenditures from the LobbyView API. Per the documentation on their website, I am using a POST request to collect lobbying data for AT&T Inc and Apple Inc. When I run the following code for Apple Inc, the API returns Apple's lobbying data as expected.

```<code>import requests, json
query = {"legal_name": "Apple Inc"}
results = requests.post('https://www.lobbyview.org/public/api/reports', data = json.dumps(query))
print(results.json())
</code>```

But, when I run the same code for AT&T Inc, the API returns nothing.

```<code>import requests, json
query = {"legal_name": "AT&T Inc"}
results = requests.post('https://www.lobbyview.org/public/api/reports', data = json.dumps(query))
print(results.json())
</code>```

I believe the problem is that AT&T Inc includes an ampersand (&) in its name.
How should I adjust my code so that I can make a POST request when the data parameter includes an ampersand (&) (e.g. "AT&T Inc")?

答:
Your request is correct.

You can check with curl

```<code>curl -X POST https://www.lobbyview.org/public/api/reports -d '{"legal_name":"AT&T Inc"}'
</code>```

returns empty record, but

```<code>curl -X POST https://www.lobbyview.org/public/api/reports -d '{"client_name":"AT&T Services, Inc."}'
</code>```

returns lot of data. So the problem is not ampersand sign, most probably there is no data for AT&T Inc.

Body:
I am attempting to access data on lobbying expenditures from the LobbyView API. Per the documentation on their website, I am using a POST request to collect lobbying data for AT&T Inc and Apple Inc. When I run the following code for Apple Inc, the API returns Apple's lobbying data as expected.

import requests, json
query = {"legal_name": "Apple Inc"}
results = requests.post('https://www.lobbyview.org/public/api/reports', data = json.dumps(query))
print(results.json())

But, when I run the same code for AT&T Inc, the API returns nothing.

import requests, json
query = {"legal_name": "AT&T Inc"}
results = requests.post('https://www.lobbyview.org/public/api/reports', data = json.dumps(query))
print(results.json())

I believe the problem is that AT&T Inc includes an ampersand (&) in its name.
How should I adjust my code so that I can make a POST request when the data parameter includes an ampersand (&) (e.g. "AT&T Inc")?

Body:
Your request is correct.

You can check with curl

curl -X POST https://www.lobbyview.org/public/api/reports -d '{"legal_name":"AT&T Inc"}'

returns empty record, but

curl -X POST https://www.lobbyview.org/public/api/reports -d '{"client_name":"AT&T Services, Inc."}'

returns lot of data. So the problem is not ampersand sign, most probably there is no data for AT&T Inc.


问:
f = open() / works in command line but not as CGI script [python]
```<code>    #! /usr/bin/env python

import htmlSplitter, htmlGlue

headerContent, mainContent, sideSetup, sideContent, footerContent = htmlSplitter.split("../htdocs/bcc/register.html")

mainContent = "<h1>This is another Test</h1>"
sideContent = "<h2>Jonathan's here!</h2>"

htmlDoc = htmlGlue.glue(headerContent, mainContent, sideSetup, sideContent, footerContent)

f = open("../bcc/doctest.html", "w")
f.write(htmlDoc)
f.close()

print("Location:../bcc/doctest.html")
print
</code>```

this script works perfectly when I run it from the command line. However, when I run it as a CGI script, it gives me a "premature end of script headers" error. I've debugged and it's fine if I comment out the segment that opens and writes "doctest.html" (so I know that the other two modules I've included are not causing the problem). Any idea why that part of the code doesn't work as a CGI script? Is there something I should be substituting instead?

NOTE: I've done a chmod a+rw on 'doctest.html' to make sure that the script has permissions to edit.

Thanks!

答: Maybe just a copy/paste-error, but your shebang seems to be indented. unindent it, and try to start the script via command line on the server, using ./yourscript (not python yourscript, as this is how it probably gets executed by the webserver)

Body:
    #! /usr/bin/env python

import htmlSplitter, htmlGlue

headerContent, mainContent, sideSetup, sideContent, footerContent = htmlSplitter.split("../htdocs/bcc/register.html")

mainContent = "
This is another Test
"
sideContent = "
Jonathan's here!
"

htmlDoc = htmlGlue.glue(headerContent, mainContent, sideSetup, sideContent, footerContent)

f = open("../bcc/doctest.html", "w")
f.write(htmlDoc)
f.close()

print("Location:../bcc/doctest.html")
print

this script works perfectly when I run it from the command line. However, when I run it as a CGI script, it gives me a "premature end of script headers" error. I've debugged and it's fine if I comment out the segment that opens and writes "doctest.html" (so I know that the other two modules I've included are not causing the problem). Any idea why that part of the code doesn't work as a CGI script? Is there something I should be substituting instead?

NOTE: I've done a chmod a+rw on 'doctest.html' to make sure that the script has permissions to edit.

Thanks!


问:
What is the Pythonic way to make an immutable class?
I'm currently working with some data structures in Python, and I would like them to be hashable (so they can be stored in dictionaries and sets). So far I've seen three main ways to do this:

① Make a normal class and give it a __hash__ method.

```<code>class DataStructure:
    def __init__(self, member):
        self.member = member
    def __hash__(self):
        return hash(self.member)
    def __eq__(self, other):
        return isinstance(other, DataStructure) and self.member == other.member
</code>```

But this is just "trusting" the end user to never mutate member. If they do mutate it while it's stored in a set or dictionary, Bad Things result.

② Use collections.namedtuple.

```<code>DataStructure = collections.namedtuple('DataStructure', ('member',))
</code>```

But a namedtuple can't have member functions, and it would be really nice to have member functions.

③ Use __slots__ and override __setattr__, as shown here.

```<code>class DataStructure:
    __slots__ = ['member']
    def __init__(self, member):
        super(DataStructure, self).__setattr__('member', member)
    def __setattr__(self, key, value):
        raise ValueError('Mutating this object is Not Allowed')
    # also define __hash__ and __eq__ here
</code>```

But this doesn't seem to be intended usage, and also makes inheritance more complicated. Above all it doesn't feel "Pythonic".

So: what is the preferred way of making an immutable class in Python? Wanting a custom data structure to be hashable doesn't seem like such a strange desire—that's why __hash__ exists, after all. And I'd prefer to actually make the class immutable rather than telling users "you're free to assign to these members, but if you do, your sets and dictionaries could crash and burn"—Python generally tries not to let people make those mistakes in the first place (which is why set and frozenset are distinct).

答:
Prepend a '_' in front of a variable that you want to be "read-only". It can still be changed from inside the class, but IDE's won't predict it and will throw warnings if you try and change them from outside the class.

__slots__ = ('_member',)
```

Body:
I'm currently working with some data structures in Python, and I would like them to be hashable (so they can be stored in dictionaries and sets). So far I've seen three main ways to do this:

① Make a normal class and give it a __hash__ method.

class DataStructure:
    def __init__(self, member):
        self.member = member
    def __hash__(self):
        return hash(self.member)
    def __eq__(self, other):
        return isinstance(other, DataStructure) and self.member == other.member

But this is just "trusting" the end user to never mutate member. If they do mutate it while it's stored in a set or dictionary, Bad Things result.

② Use collections.namedtuple.

DataStructure = collections.namedtuple('DataStructure', ('member',))

But a namedtuple can't have member functions, and it would be really nice to have member functions.

③ Use __slots__ and override __setattr__, as shown here.

class DataStructure:
    __slots__ = ['member']
    def __init__(self, member):
        super(DataStructure, self).__setattr__('member', member)
    def __setattr__(self, key, value):
        raise ValueError('Mutating this object is Not Allowed')
    # also define __hash__ and __eq__ here

But this doesn't seem to be intended usage, and also makes inheritance more complicated. Above all it doesn't feel "Pythonic".

So: what is the preferred way of making an immutable class in Python? Wanting a custom data structure to be hashable doesn't seem like such a strange desire—that's why __hash__ exists, after all. And I'd prefer to actually make the class immutable rather than telling users "you're free to assign to these members, but if you do, your sets and dictionaries could crash and burn"—Python generally tries not to let people make those mistakes in the first place (which is why set and frozenset are distinct).


问:
How to clone a single specific file from Bitbucket
I have a bitbucket repo with huge sources, but need to edit only one file.
Its taking more time and size to clone to local.
Can some one say the git command to clone a specific file from bitbucket</p>

答:
Considering a BitBucket server now (since 2018) has inline editing, you could consider modifying that file directly through the browser.

That way, no clone is necessary.


问:
undefined - params passed to `App.js` from splash screen
A splashscreen was added to react native (0.59) app with react navigation (3.9) on android emulator to retrieve local value and pass it back to App.js for routing purpose. Here is the component SplashScreen:

```<code>import React, { Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import helper from "../../lib/helper";

class SplashScreen extends React.Component {
    ......

    async componentDidMount() {
        const data = await this.performTimeConsumingTask();
        this.props.navigation.navigate('App', {params  : data});  //<<<===pass the params to App
        }

    render() {
        return (
          <View style={styles.viewStyles}>
            <Text style={styles.textStyles}>
              Blitz Reading
            </Text>
          </View>
        );
      }
    }

    const styles = {
      .......
    }

    export default SplashScreen;
</code>```

A local data is retrieved after splash screen is mounted. Then the retrieved data is passed back to App.js as params. Here is the App.js:

```<code>import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
.....
import SplashScreen from "./src/components/splashscreen/SplashScreen";

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
  android:
    'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

//socket.io
const socket = io(GLOBAL.BASE_URL, {
  //const socket = io(GLOBAL.BASE_URL, {
    transports: ['websocket'],
    jsonp: false
  });
console.log("socket id in App.js : ", socket.id);

socket.on('disconnect', (reason) => {
  // ...
  if (reason === 'io server disconnect') {

    socket.connect();
  }
  // else the socket will automatically try to reconnect
});

const ChatWithSocket = (props) => (<Chat {...props} socket={socket} />)

//create the navigator
const EventStack = createStackNavigator(
  {
    Event:  Event,
    NewEvent: NewEvent,
    Chat: {
      screen: ChatWithSocket,

    },
    Signup: Signup,
    Verif1: Verif1,

  },  {
    initialRouteName: 'Verif1',
  }
);

const UserStack = createStackNavigator(
  {
    NewUser: NewUser,
    EditUser: EditUser,
  }, {
      initialRouteName: "NewUser",
  }

);

const bottomTabNav = createBottomTabNavigator(
    {
      Event: {screen: EventStack},
      User: {screen: UserStack},
    },
    {
        defaultNavigationOptions: ({ navigation }) => ({
          tabBarIcon: ({ focused, tintColor }) => {
            const { routeName } = navigation.state;
            console.log("In App.js, props is : ", this.props);  //<<==Value?
            let iconName;
            if (routeName === 'Event') {
              iconName = `ios-information-circle${focused ? '' : '-outline'}`;
            } else if (routeName === 'NewUser') {
              iconName = `ios-options${focused ? '' : '-outline'}`;
            }

            return <Text>Hello the world!</Text>
          },
        }),
        tabBarOptions: {
          activeTintColor: 'tomato',
          inactiveTintColor: 'gray',
        },
      }
    );

const InitialNavigator = createSwitchNavigator({
  Splash: SplashScreen,
  App: bottomTabNav,
});

const AppContainer = createAppContainer(InitialNavigator);

export default AppContainer;
</code>```

But the output of this.props is undefined :

```<code>05-30 19:01:55.893  8312  8366 I ReactNativeJS: 'In App.js, props is : ', undefined
05-30 19:01:55.894  8312  8366 I ReactNativeJS: 'In App.js, props is : ', undefined
05-30 19:01:56.016  8312  8366 I ReactNativeJS: 'In App.js, props is : ', undefined
05-30 19:01:56.017  8312  8366 I ReactNativeJS: 'In App.js, props is : ', undefined
</code>```

I also tried navigation.state.params and it is undefined as well. How to access the params passed to App.js?

答:
Cause you navigate and pass parameters to tab navigators, you have to retrieve that from its parent router

defaultNavigationOptions: ({ navigation }) => ({
  tabBarIcon: ({ focused, tintColor }) => {
    ...
    const yourParams = navigation.dangerouslyGetParent().getParam('yourParamHere')
    ...
  },
}),```

Body:
A splashscreen was added to react native (0.59) app with react navigation (3.9) on android emulator to retrieve local value and pass it back to App.js for routing purpose. Here is the component SplashScreen:

import React, { Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import helper from "../../lib/helper";

class SplashScreen extends React.Component {
    ......

    async componentDidMount() {
        const data = await this.performTimeConsumingTask();
        this.props.navigation.navigate('App', {params  : data});  //<<<===pass the params to App
        }

    render() {
        return (
          <View style={styles.viewStyles}>
            <Text style={styles.textStyles}>
              Blitz Reading
            </Text>
          </View>
        );
      }
    }

    const styles = {
      .......
    }

    export default SplashScreen;

A local data is retrieved after splash screen is mounted. Then the retrieved data is passed back to App.js as params. Here is the App.js:

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
.....
import SplashScreen from "./src/components/splashscreen/SplashScreen";

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
  android:
    'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

//socket.io
const socket = io(GLOBAL.BASE_URL, {
  //const socket = io(GLOBAL.BASE_URL, {
    transports: ['websocket'],
    jsonp: false
  });
console.log("socket id in App.js : ", socket.id);

socket.on('disconnect', (reason) => {
  // ...
  if (reason === 'io server disconnect') {

    socket.connect();
  }
  // else the socket will automatically try to reconnect
});

const ChatWithSocket = (props) => (<Chat {...props} socket={socket} />)

//create the navigator
const EventStack = createStackNavigator(
  {
    Event:  Event,
    NewEvent: NewEvent,
    Chat: {
      screen: ChatWithSocket,

    },
    Signup: Signup,
    Verif1: Verif1,

  },  {
    initialRouteName: 'Verif1',
  }
);

const UserStack = createStackNavigator(
  {
    NewUser: NewUser,
    EditUser: EditUser,
  }, {
      initialRouteName: "NewUser",
  }

);

const bottomTabNav = createBottomTabNavigator(
    {
      Event: {screen: EventStack},
      User: {screen: UserStack},
    },
    {
        defaultNavigationOptions: ({ navigation }) => ({
          tabBarIcon: ({ focused, tintColor }) => {
            const { routeName } = navigation.state;
            console.log("In App.js, props is : ", this.props);  //<<==Value?
            let iconName;
            if (routeName === 'Event') {
              iconName = `ios-information-circle${focused ? '' : '-outline'}`;
            } else if (routeName === 'NewUser') {
              iconName = `ios-options${focused ? '' : '-outline'}`;
            }

            return <Text>Hello the world!</Text>
          },
        }),
        tabBarOptions: {
          activeTintColor: 'tomato',
          inactiveTintColor: 'gray',
        },
      }
    );

const InitialNavigator = createSwitchNavigator({
  Splash: SplashScreen,
  App: bottomTabNav,
});

const AppContainer = createAppContainer(InitialNavigator);

export default AppContainer;

But the output of this.props is undefined :

05-30 19:01:55.893  8312  8366 I ReactNativeJS: 'In App.js, props is : ', undefined
05-30 19:01:55.894  8312  8366 I ReactNativeJS: 'In App.js, props is : ', undefined
05-30 19:01:56.016  8312  8366 I ReactNativeJS: 'In App.js, props is : ', undefined
05-30 19:01:56.017  8312  8366 I ReactNativeJS: 'In App.js, props is : ', undefined

I also tried navigation.state.params and it is undefined as well. How to access the params passed to App.js?


答:
Or regex with this pattern for optional white space (?<=')\s*,\s*

Example

```<code>var inputs = new []{ "'Test string','abc'",
                     "'Test string ','abc'",
                     "'Test string' ,'abc'",
                     "'Test string', 'abc'",
                     "'Test string   '   ,   'abc'",
                     "Test string','abc','John's test'" };

foreach (var input in inputs)
{
   var results = Regex.Split(input, @"(?<=')\s*,\s*");
   foreach (var result in results)
      Console.WriteLine(result);
}
</code>```

Output

```<code>'Test string'
'abc'
'Test string '
'abc'
'Test string'
'abc'
'Test string'
'abc'
'Test string   '
'abc'
Test string'
'abc'
'John's test'
</code>```

Visualized

Full Demo here

Title: Split String by Two Characters Ignore Whitespace Before, In Between or After any of the Characters

Body:
Or regex with this pattern for optional white space (?<=')\s*,\s*

Example

var inputs = new []{ "'Test string','abc'",
                     "'Test string ','abc'",
                     "'Test string' ,'abc'",
                     "'Test string', 'abc'",
                     "'Test string   '   ,   'abc'",
                     "Test string','abc','John's test'" };

foreach (var input in inputs)
{
   var results = Regex.Split(input, @"(?<=')\s*,\s*");
   foreach (var result in results)
      Console.WriteLine(result);
}

Output

'Test string'
'abc'
'Test string '
'abc'
'Test string'
'abc'
'Test string'
'abc'
'Test string   '
'abc'
Test string'
'abc'
'John's test'

Visualized

Full Demo here


问:
Rails - Turn 2-dimensional array into list and back
I have an array like this:

```<code>[["09:00",4,15],["09:00",4,15]]
</code>```

And I want to output this in a text area like this:

```<code>"09:00",4,15
"09:00",4,15
</code>```

The user can edit it and then I want to convert it back into an array with sub-arrays.

For the first step I could do an each and remove the [] with gsub but this does not seem to be the best way. And then to turn it back into an array I would need even more code.

It's kind of a CSV output but I am not working with any files here.

答:
Given

```<code>arr = [["09:00",4,15],["09:00",4,15]]
</code>```

You can use the CSV module from the standard library:

```<code>require 'csv'

lines = CSV.generate {|csv| arr.each(&csv.method(:<<))}
# => "09:00,4,15\n09:00,4,15\n"

CSV.parse(lines, converters: :integer)
# => [["09:00", 4, 15], ["09:00", 4, 15]]
</code>```

Body:
I have an array like this:

[["09:00",4,15],["09:00",4,15]]

And I want to output this in a text area like this:

"09:00",4,15
"09:00",4,15

The user can edit it and then I want to convert it back into an array with sub-arrays.

For the first step I could do an each and remove the [] with gsub but this does not seem to be the best way. And then to turn it back into an array I would need even more code.

It's kind of a CSV output but I am not working with any files here.

Body:
Given

arr = [["09:00",4,15],["09:00",4,15]]

You can use the CSV module from the standard library:

require 'csv'

lines = CSV.generate {|csv| arr.each(&csv.method(:<<))}
# => "09:00,4,15\n09:00,4,15\n"

CSV.parse(lines, converters: :integer)
# => [["09:00", 4, 15], ["09:00", 4, 15]]


问:
AWS cloudwatch alarm using CLI for EMR
How to write a cloudwatch alarm for EMR using CLI command??

My requirement is to terminate cluster which are idle for more than 2hours. I need to do this using aws CLI command.

答:
From Monitor Metrics with CloudWatch - Amazon EMR:

The IsIdle metric tracks whether a cluster is live, but not currently running tasks. You can set an alarm to fire when the cluster has been idle for a given period of time, such as thirty minutes.

Therefore, you can configure an alarm on this metric. However, the alarm itself is not able to terminate an Amazon EMR cluster. You would need an additional component, such as an AWS Lambda function, to actually terminate the cluster.

The components would be:

An Amazon CloudWatch IsIdle metric (automatically provided)

An Alarm on the metric that triggers when the cluster is idle for longer than the desired period

Configure the Alarm to send a message to an Amazon SNS topic

Create an AWS Lambda function and subscribe the function to the SNS topic

Code the Lambda function to terminate the Amazon EMR cluster

There is a more complex version of this auto-shutdown process documented at: Optimize Amazon EMR costs with idle checks and automatic resource termination using advanced Amazon CloudWatch metrics and AWS Lambda | AWS Big Data Blog

Title: AWS cloudwatch alarm using CLI for EMR


问:
How is the return value of the js object property assigned to the reference address?
```<code>var o1 = {};
var o2 = { bar: 'hello' };

o1.foo = o2; // in console  {bar: "hello"}
var o3 = o2;// in console  undefined
</code>```

Why is {bar: "hello"} being printed?
Why is undefined being printed?

答:
That doesn't happen - the code creates a new property of o1 named foo, and assigns it the value of o2, which is an object - so the property o1.foo is an object consisting of o2.

var o1 = {};
var o2 = {
  bar: 'hello'
};

o1.foo = o2;

console.log(o1);```

The reason you see { bar: "hello" } in the console when you copy/paste the code is because the final return value from the code is { bar: "hello" } (from o1.foo = o2). o1 is still an object containing foo, but the { bar: "hello" } shown in the console is just the return value from the code.

Body:
var o1 = {};
var o2 = { bar: 'hello' };

o1.foo = o2; // in console  {bar: "hello"}
var o3 = o2;// in console  undefined

Why is {bar: "hello"} being printed?
Why is undefined being printed?

Body:
That doesn't happen - the code creates a new property of o1 named foo, and assigns it the value of o2, which is an object - so the property o1.foo is an object consisting of o2.

var o1 = {};
var o2 = {
  bar: 'hello'
};

o1.foo = o2;

console.log(o1);

The reason you see { bar: "hello" } in the console when you copy/paste the code is because the final return value from the code is { bar: "hello" } (from o1.foo = o2). o1 is still an object containing foo, but the { bar: "hello" } shown in the console is just the return value from the code.


问:
Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {$$typeof, render})

Error handling and alerts in React

When I bring the <Alert /> to the main app component just below the  tag, as soon as the component mounts it throws this error.

While I remove the <Alert /> from the main app component, it works fine.
This is how the browser renders properly before I brought the <Alert /> to the main app component,
 click here.

Here is the snippet of code that works earlier:

```<code>class App extends Component {
render() {
    return (
        <Provider store={store}>
            <AlertProvider template={AlertTemplate} {...alertOptions}>
                <Fragment>
                    <Header />
                    <div className="container">
                        <Dashboard />
                    </div>
                </Fragment>
            </AlertProvider>
        </Provider>
    )
}
</code>```

}

I expect to get the proper alert message snippets in the browser. However, nothing gets rendered in the browser after I tried to use the third party package called react-alert from this Github repository.

Below is the snippet of the code that failed with an error in the console.

```<code>class App extends Component {
render() {
    return (
        <Provider store={store}>
            <AlertProvider template={AlertTemplate} {...alertOptions}>
                <Fragment>
                    <Header />
                    <Alerts />
                    <div className="container">
                        <Dashboard />
                    </div>
                </Fragment>
            </AlertProvider>
        </Provider>
    )
}
</code>```

Here is my Alerts.js component:

```<code>import React, { Component, Fragment } from 'react';
import { withAlert } from 'react-alert';
export class Alerts extends Component {
    componentDidMount() {
        this.props.alert.show('It Works');
    }
    render() {
        return <Fragment />;
    }
}
export default withAlert(Alerts);
</code>```

The given error has seen in the console: Error in the console

答:
Please check the documentation properly. In your code there is

```<code>export default withAlert(Alerts);
</code>```

But in documentation , to use with HOC you should write

```<code>export default withAlert()(Alerts)
</code>```

Body:
Error handling and alerts in React

When I bring the <Alert /> to the main app component just below the  tag, as soon as the component mounts it throws this error.

While I remove the <Alert /> from the main app component, it works fine.
This is how the browser renders properly before I brought the <Alert /> to the main app component,
 click here.

Here is the snippet of code that works earlier:

class App extends Component {
render() {
    return (
        <Provider store={store}>
            <AlertProvider template={AlertTemplate} {...alertOptions}>
                <Fragment>

                        <Dashboard />

                </Fragment>
            </AlertProvider>
        </Provider>
    )
}

}

I expect to get the proper alert message snippets in the browser. However, nothing gets rendered in the browser after I tried to use the third party package called react-alert from this Github repository.

Below is the snippet of the code that failed with an error in the console.

class App extends Component {
render() {
    return (
        <Provider store={store}>
            <AlertProvider template={AlertTemplate} {...alertOptions}>
                <Fragment>

                    <Alerts />

                        <Dashboard />

                </Fragment>
            </AlertProvider>
        </Provider>
    )
}

Here is my Alerts.js component:

import React, { Component, Fragment } from 'react';
import { withAlert } from 'react-alert';
export class Alerts extends Component {
    componentDidMount() {
        this.props.alert.show('It Works');
    }
    render() {
        return <Fragment />;
    }
}
export default withAlert(Alerts);

The given error has seen in the console: Error in the console

Body:
Please check the documentation properly. In your code there is

export default withAlert(Alerts);

But in documentation , to use with HOC you should write

export default withAlert()(Alerts)


问:
In Javascript, Today(31/5) add 1 month will get 1/7
Today I just found that if I add 1 month on today's date, it returns 1/7.

Can anyone give help on this? Thank you very much.

Notice: I didn't assign the date to today because today is 31/5, and some of you guys is still on 30/5

var today = new Date(); // today is 31/5 in my timezone
console.log(today);
today.setMonth(today.getMonth() + 1);
console.log(today);```

答:
This is a weird way how dates work in JavaScript. According to documentation in MDN:

The current day of month will have an impact on the behaviour of this
  method. Conceptually it will add the number of days given by the
  current day of the month to the 1st day of the new month specified as
  the parameter, to return the new date. For example, if the current
  value is 31st August 2016, calling setMonth with a value of 1 will
  return 2nd March 2016. This is because in 2016 February had 29 days.

In your case when you add a month to 31st of May you get 31st of June. This is not a valid date, and JavaScript translates it to 1st of July


问:
Homescreen (App.js) structure for react-navigation
I'm trying to implement the react-navigation package to make one screen link to another. I'm getting an error "undefined is not an object (evaluating '_this2.props.navigation.navigate') - React Native"

I'm fairly sure this error is because I have nothing in the App.js part of my project.

I have a file called screen.js that has two classes (one for each screen), and an onpress function that calls the this.props.navigator to change screens.

Screen.js

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  TextInput,
  View,
  TouchableHighlight,
  PanResponder,
  AppRegistry,
  Image,
  Alert,
} from 'react-native';
import { Card, Button, Icon } from 'react-native-elements';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import { Constants, MapView } from 'expo';

class HomeScreen extends Component {
  static navigationOptions = {
    title: 'Home',
  };

  constructor() {
    super();
    this.state = {...};
  }

  _handleButtonPress = () => {
    Alert.alert('Button pressed!', 'You did it!');
  };

  componentWillMount() {
    this.panResponderRef = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onMoveShouldSetPanResponder: () => true,
      onPanResponderGrant: this.doNothing,
      onPanResponderMove: this._handlePanResponderMove,
      onPanResponderRelease: this._handlePanResponderEnd,
      onPanResponderTerminate: this.doNothing,
    });
  }

  //onPanResponderRelease and onPanResponderTerminate Handler
  _handlePanResponderEnd = (event, gestureState) => {
    const { navigate } = this.props.navigation;
    let tIndex = this.state.index;
    if (this.state.dy > 100)
      navigate('Second', { index: tIndex, getFunc: this.getName.bind(this) });
    else if (this.state.dx > 150) this.setState({ index: tIndex + 1 });
    else if (this.state.dx < -150 && tIndex > 0)
      this.setState({ index: tIndex - 1 });
  };

  render() {

    const { navigate } = this.props.navigation;

    return (
      <View style={styles.container}>
            <TouchableHighlight
              style={styles.TouchableHighlight}

              onPress={() => this.props.navigator.push({id:'SecondScreen'})}>

              <View style={styles.author}>
                <Text style={styles.author}>Shelter 1</Text>
              </View>
            </TouchableHighlight>
      </View>
    );
  }
}

class SecondScreen extends React.Component {
  static navigationOptions = {
    title: 'Second',
  };
  constructor(props) {
    super(props);
    this.state = {
      index: this.props.navigation.state.params.index,
      getFunc: this.props.navigation.state.params.getFunc,
      name: 'not set'
    };
  }
  componentWillMount() {
    let tName = this.state.getFunc(this.state.index);
    this.setState({ name: tName });
  }

  render() {
    const { navigate } = this.props.navigation;

    return (
      <View style={styles.container}>

        </View>

        <Button title="Go to Home page" onPress={() => navigate('Home')} />
      </View>
    );
  }
}

const NavigationApp = createStackNavigator({
  Home: { screen: HomeScreen },
  Second: { screen: SecondScreen },
});

export default createAppContainer(NavigationApp);
});```
</div>
</div>
</p>

<p>App.js</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import NavApp from "screen";

export default NavApp;</code>```

I am getting an error "undefined is not an object (evaluating '_this2.props.navigator.push')"

答:
You could try this</p>

```<code>this.props.navigation.push('SecondScreen')
</code>```

Body:
I'm trying to implement the react-navigation package to make one screen link to another. I'm getting an error "undefined is not an object (evaluating '_this2.props.navigation.navigate') - React Native"

I'm fairly sure this error is because I have nothing in the App.js part of my project.

I have a file called screen.js that has two classes (one for each screen), and an onpress function that calls the this.props.navigator to change screens.

Screen.js

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  TextInput,
  View,
  TouchableHighlight,
  PanResponder,
  AppRegistry,
  Image,
  Alert,
} from 'react-native';
import { Card, Button, Icon } from 'react-native-elements';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import { Constants, MapView } from 'expo';

class HomeScreen extends Component {
  static navigationOptions = {
    title: 'Home',
  };

  constructor() {
    super();
    this.state = {...};
  }

  _handleButtonPress = () => {
    Alert.alert('Button pressed!', 'You did it!');
  };

  componentWillMount() {
    this.panResponderRef = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onMoveShouldSetPanResponder: () => true,
      onPanResponderGrant: this.doNothing,
      onPanResponderMove: this._handlePanResponderMove,
      onPanResponderRelease: this._handlePanResponderEnd,
      onPanResponderTerminate: this.doNothing,
    });
  }

  //onPanResponderRelease and onPanResponderTerminate Handler
  _handlePanResponderEnd = (event, gestureState) => {
    const { navigate } = this.props.navigation;
    let tIndex = this.state.index;
    if (this.state.dy > 100)
      navigate('Second', { index: tIndex, getFunc: this.getName.bind(this) });
    else if (this.state.dx > 150) this.setState({ index: tIndex + 1 });
    else if (this.state.dx < -150 && tIndex > 0)
      this.setState({ index: tIndex - 1 });
  };

  render() {

    const { navigate } = this.props.navigation;

    return (
      <View style={styles.container}>
            <TouchableHighlight
              style={styles.TouchableHighlight}

              onPress={() => this.props.navigator.push({id:'SecondScreen'})}>

              <View style={styles.author}>
                <Text style={styles.author}>Shelter 1</Text>
              </View>
            </TouchableHighlight>
      </View>
    );
  }
}

class SecondScreen extends React.Component {
  static navigationOptions = {
    title: 'Second',
  };
  constructor(props) {
    super(props);
    this.state = {
      index: this.props.navigation.state.params.index,
      getFunc: this.props.navigation.state.params.getFunc,
      name: 'not set'
    };
  }
  componentWillMount() {
    let tName = this.state.getFunc(this.state.index);
    this.setState({ name: tName });
  }

  render() {
    const { navigate } = this.props.navigation;

    return (
      <View style={styles.container}>

        </View>

        <Button title="Go to Home page" onPress={() => navigate('Home')} />
      </View>
    );
  }
}

const NavigationApp = createStackNavigator({
  Home: { screen: HomeScreen },
  Second: { screen: SecondScreen },
});

export default createAppContainer(NavigationApp);
});

App.js

import NavApp from "screen";

export default NavApp;

I am getting an error "undefined is not an object (evaluating '_this2.props.navigator.push')"

Body:
You could try this

this.props.navigation.push('SecondScreen')


问:
How to find start(min) and end(max) date in xml file?
I have an XML file. I should find for same field2 start(min) date and End(max) date from field3. Maybe xsl have some function to find it.Because I try do it trying to find min month and min day and max month, max day.
XML:

```<code><document>
    <line id="0">
        <field id="2">X111</field>
        <field id="3">2011-03-31</field>
    </line>
    <line id="1">
        <field id="2">X111</field>
        <field id="3">2011-04-04</field>
    </line>
    <line id="2">
        <field id="2">X111</field>
        <field id="3">2011-04-02</field>
    </line>
    <line id="3">
        <field id="2">X222</field>
        <field id="3">2011-04-04</field>
    </line>
    <line id="4">
        <field id="2">X222</field>
        <field id="3">2011-04-01</field>
    </line>
    <line id="4">
        <field id="2">X333</field>
        <field id="3">2011-04-01</field>
    </line>
</document>
</code>```

Output:

```<code><document>
<Message>
    <ID>X111</ID>
    <dateStart>2011-03-31</dateStart>
    <dateEnd>2011-04-04</dateEnd>
</Message>
<Message>
    <ID>X222</ID>
    <dateStart>2011-04-01</dateStart>
    <dateEnd>2011-04-04</dateEnd>
</Message>
<Message>
    <ID>X333</ID>
    <dateStart>2011-04-01</dateStart>
    <dateEnd>2011-04-01</dateEnd>
</Message>
</document>
</code>```

Please help to solve it. I'm working with stylesheet version="1.0".

答:
I upvoted @mousio's answer, but I'd prefer to see the first of each line type handled in its own template. So, in the spirit of TMTOWTDI, here's how I would have done it:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes" />
    <xsl:key name="byField2" match="line" use="field[@id=2]" />
    <xsl:template match="/">
        <document>
            <xsl:apply-templates select="document/line" />
        </document>
    </xsl:template>
    <xsl:template match="line[count(.|key('byField2', field[@id=2])[1])=1]">
        <Message>
            <ID><xsl:value-of select="field[@id=2]" /></ID>
            <xsl:apply-templates select="key('byField2', field[@id=2])" mode="m">
                <xsl:sort select="field[@id=3]" />
            </xsl:apply-templates>
        </Message>
    </xsl:template>
    <xsl:template match="line" mode="m">
        <xsl:if test="position()=1">
            <dateStart><xsl:value-of select="field[@id=3]" /></dateStart>
        </xsl:if>
        <xsl:if test="position()=last()">
            <dateEnd><xsl:value-of select="field[@id=3]" /></dateEnd>
        </xsl:if>
    </xsl:template>
    <xsl:template match="line" />
</xsl:stylesheet>
</code>```

I think this is easier to read (and probably more efficient on large documents, since it doesn't abuse //).

Body:
I have an XML file. I should find for same field2 start(min) date and End(max) date from field3. Maybe xsl have some function to find it.Because I try do it trying to find min month and min day and max month, max day.
XML:

<document>
    <line id="0">
        <field id="2">X111</field>
        <field id="3">2011-03-31</field>
    </line>
    <line id="1">
        <field id="2">X111</field>
        <field id="3">2011-04-04</field>
    </line>
    <line id="2">
        <field id="2">X111</field>
        <field id="3">2011-04-02</field>
    </line>
    <line id="3">
        <field id="2">X222</field>
        <field id="3">2011-04-04</field>
    </line>
    <line id="4">
        <field id="2">X222</field>
        <field id="3">2011-04-01</field>
    </line>
    <line id="4">
        <field id="2">X333</field>
        <field id="3">2011-04-01</field>
    </line>
</document>

Output:

<document>
<Message>
    <ID>X111</ID>
    <dateStart>2011-03-31</dateStart>
    <dateEnd>2011-04-04</dateEnd>
</Message>
<Message>
    <ID>X222</ID>
    <dateStart>2011-04-01</dateStart>
    <dateEnd>2011-04-04</dateEnd>
</Message>
<Message>
    <ID>X333</ID>
    <dateStart>2011-04-01</dateStart>
    <dateEnd>2011-04-01</dateEnd>
</Message>
</document>

Please help to solve it. I'm working with stylesheet version="1.0".

Body:
I upvoted @mousio's answer, but I'd prefer to see the first of each line type handled in its own template. So, in the spirit of TMTOWTDI, here's how I would have done it:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes" />
    <xsl:key name="byField2" match="line" use="field[@id=2]" />
    <xsl:template match="/">
        <document>
            <xsl:apply-templates select="document/line" />
        </document>
    </xsl:template>
    <xsl:template match="line[count(.|key('byField2', field[@id=2])[1])=1]">
        <Message>
            <ID><xsl:value-of select="field[@id=2]" /></ID>
            <xsl:apply-templates select="key('byField2', field[@id=2])" mode="m">
                <xsl:sort select="field[@id=3]" />
            </xsl:apply-templates>
        </Message>
    </xsl:template>
    <xsl:template match="line" mode="m">
        <xsl:if test="position()=1">
            <dateStart><xsl:value-of select="field[@id=3]" /></dateStart>
        </xsl:if>
        <xsl:if test="position()=last()">
            <dateEnd><xsl:value-of select="field[@id=3]" /></dateEnd>
        </xsl:if>
    </xsl:template>
    <xsl:template match="line" />
</xsl:stylesheet>

I think this is easier to read (and probably more efficient on large documents, since it doesn't abuse //).


问:
Get install location from registry key value data
I basically want to know if its possible for me to get a path from the registry and use it in a Batch file.

Basically what I have is some code I've gather from this site

```<code>@echo off
reg query "HKLM\SOFTWARE\Wow6432Node\Rockstar Games\Grand Theft Auto V" /v     "InstallFolder"
</code>```

That line returns

```<code>HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Rockstar Games\Grand Theft Auto V
InstallFolder    REG_SZ    D:\Rockstar Games\Grand Theft Auto V
</code>```

All I want to do here is add the path of GTA to the batch file so I can then launch the executable (PlayGTAV.exe) through the batch file. The reason I'm not using the path i already know is because I want this batch file to work on some friends computers too.

答:
@ECHO OFF
SETLOCAL
FOR /f "delims=" %%a IN ('reg query "HKLM\SOFTWARE\Embarcadero\Interbase\Servers" ^|find " REG_SZ "') DO (
 SET "target=%%a"
)
SET "target=%target:*REG_SZ    =%"
ECHO "%target%"

GOTO :EOF
```

This should demonstrate how - I've obviously used a different key.

The ^|find... finds the appropriate line containing the REG_SZ (the caret is used to tell cmd that the piping is of the reg query command, not part of the for) and the for /f "delims=" selects the entire line for application to %%a.

From there, it's simply a matter of applying substringing to the ordinary environment variable target (since substringing of the metavariable %%a is not allowed) - replace any characters before and including the first occurrence of REG_SZ+4spaces with nothing (the string between the = and terminal %

Body:
I basically want to know if its possible for me to get a path from the registry and use it in a Batch file.

Basically what I have is some code I've gather from this site

@echo off
reg query "HKLM\SOFTWARE\Wow6432Node\Rockstar Games\Grand Theft Auto V" /v     "InstallFolder"

That line returns

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Rockstar Games\Grand Theft Auto V
InstallFolder    REG_SZ    D:\Rockstar Games\Grand Theft Auto V

All I want to do here is add the path of GTA to the batch file so I can then launch the executable (PlayGTAV.exe) through the batch file. The reason I'm not using the path i already know is because I want this batch file to work on some friends computers too.

Body:
@ECHO OFF
SETLOCAL
FOR /f "delims=" %%a IN ('reg query "HKLM\SOFTWARE\Embarcadero\Interbase\Servers" ^|find " REG_SZ "') DO (
 SET "target=%%a"
)
SET "target=%target:*REG_SZ    =%"
ECHO "%target%"

GOTO :EOF

This should demonstrate how - I've obviously used a different key.

The ^|find... finds the appropriate line containing the REG_SZ (the caret is used to tell cmd that the piping is of the reg query command, not part of the for) and the for /f "delims=" selects the entire line for application to %%a.

From there, it's simply a matter of applying substringing to the ordinary environment variable target (since substringing of the metavariable %%a is not allowed) - replace any characters before and including the first occurrence of REG_SZ+4spaces with nothing (the string between the = and terminal %


问:
Spark sql can't find table in hive in HDP
I use HDP3.1 and I added Spark2, Hive and Other services which are needed. I turned of the ACID feature in Hive. The spark job can't find the table in hive. But the table exists in Hive. The exception likes:
org.apache.spark.sql.AnalysisException: Table or view not found
    There is hive-site.xml in Spark's conf folder. It is automaticly created by HDP. But it isn't same as the file in hive's conf folder. And from the log, the spark can get the thrift URI of hive correctly.
    I use spark sql and created one hive table in spark-shell. I found the table was created in the fold which is specified by spark.sql.warehouse.dir. I changed its value to the value of hive.metastore.warehouse.dir. But the problem is still there.
    I also enabled hive support when creating spark session.</p>

```<code>val ss = SparkSession.builder().appName("统计").enableHiveSupport().getOrCreate()
</code>```

答: You can use hivewarehouse connector and use llap in hive conf</p>

Body:
I use HDP3.1 and I added Spark2, Hive and Other services which are needed. I turned of the ACID feature in Hive. The spark job can't find the table in hive. But the table exists in Hive. The exception likes:
org.apache.spark.sql.AnalysisException: Table or view not found
    There is hive-site.xml in Spark's conf folder. It is automaticly created by HDP. But it isn't same as the file in hive's conf folder. And from the log, the spark can get the thrift URI of hive correctly.
    I use spark sql and created one hive table in spark-shell. I found the table was created in the fold which is specified by spark.sql.warehouse.dir. I changed its value to the value of hive.metastore.warehouse.dir. But the problem is still there.
    I also enabled hive support when creating spark session.

val ss = SparkSession.builder().appName("统计").enableHiveSupport().getOrCreate()