问:
Java - String can be split with regex but regex match returns false
I am trying to split the following string with the following as example:
Team A 2-3 Team B
It is a string with the team's names on 2 sides and the score between them in the middle. I need to obtain the team's names and scores respectively. This is my code so far for this part:

```<code>    String homeTeam;
    String awayTeam;
    int homeGoal = 0;
    int awayGoal = 0;
    String input = "Team A 2-3 Team B";
    Scanner s = new Scanner(input).useDelimiter("-");
    String[] teamNames = input.split(" (\\d+)-(\\d+) ");
    homeTeam = teamNames[0];
    awayTeam = teamNames[1];
    for(int i = 0; i < teamNames.length; i++) {
    System.out.println(teamNames[i]);
    }
    s.findInLine("(\\d+)-(\\d+)");
    MatchResult result = s.match();
    for (int i=1; i<=result.groupCount(); i++)
    System.out.println(result.group(i));
    s.close();
</code>```

The output for this:

```<code>Team A
Team B
2
3
</code>```

as it should be.

However, since there is another case where the match has yet to be played Team A  Team B. The 2 team names in this case are separated by 2 spaces. The regex used above no longer works so I have 2 cases. This is my overall code:

```<code>        String homeTeam;
        String awayTeam;
        int homeGoal = 0;
        int awayGoal = 0;
        String input = "Team A 2-3 Team B";
        Scanner s = new Scanner(input).useDelimiter("-");

    boolean b = Pattern.matches(" (\\d+)-(\\d+) ", input);
    if (b){
        String[] teamNames = input.split(" (\\d+)-(\\d+) ");
        homeTeam = teamNames[0];
        awayTeam = teamNames[1];
        for(int i = 0; i < teamNames.length; i++) {
            System.out.println(teamNames[i]);
        }
        s.findInLine("(\\d+)-(\\d+)");
        MatchResult result = s.match();
        for (int i=1; i<=result.groupCount(); i++)
            System.out.println(result.group(i));
        s.close();
    } else {
        String[] teamNames = input.split("  ");
        homeTeam = teamNames[0];
        awayTeam = teamNames[1];
        for(int i = 0; i < teamNames.length; i++) {
            System.out.println(teamNames[i]);
        }
    }
    System.out.println(b);
</code>```

The problem that I am getting is that b is returning false even for the string

```<code>Team A 2-3 Team B
</code>```

And so only the else case is returned with this code.

I tested both parts individually with strings that match their own pattern and they worked fine but not when I combine then like this.

答:
Code

See regex in use here

```<code>([\w ]*?)\s+(?:(\d+)-(\d+))?\s+([\w ]*)
</code>```

Code

See code in use here

```<code>import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        final String regex = "([\\w ]*?)\\s+(?:(\\d+)-(\\d+))?\\s+([\\w ]*)";
        final String[] strings = {"Team A 2-3 Team B", "Team A  Team B"};

        final Pattern pattern = Pattern.compile(regex);

        for (String string : strings) {
            Matcher matcher = pattern.matcher(string);
            if(matcher.find()) {
                System.out.println("Home team: " + matcher.group(1));
                if(matcher.group(2) != null) {
                    System.out.println("Home goal: " + matcher.group(2));
                    System.out.println("Away goal: " + matcher.group(3));
                }
                System.out.println("Away team: " + matcher.group(4));
                System.out.println("\n");
            }
        }
    }
}
</code>```

Explanation

([\w ]*?) Capture any character in the set (word characters or space) any number of times, but as few as possible, into capture group 1

\s+ Match one or more whitespace characters

(?:(\d+)-(\d+))? Match the following zero or one time

(\d+) Capture one or more digits into capture group 2

- Match the hyphen character - literally

(\d+) Capture one or more digits into capture group 3

\s+ Match one or more whitespace characters

([\w ]*) Capture any character in the set (word characters or space) any number of times into capture group 4

Body:
I am trying to split the following string with the following as example:
Team A 2-3 Team B
It is a string with the team's names on 2 sides and the score between them in the middle. I need to obtain the team's names and scores respectively. This is my code so far for this part:

    String homeTeam;
    String awayTeam;
    int homeGoal = 0;
    int awayGoal = 0;
    String input = "Team A 2-3 Team B";
    Scanner s = new Scanner(input).useDelimiter("-");
    String[] teamNames = input.split(" (\\d+)-(\\d+) ");
    homeTeam = teamNames[0];
    awayTeam = teamNames[1];
    for(int i = 0; i < teamNames.length; i++) {
    System.out.println(teamNames[i]);
    }
    s.findInLine("(\\d+)-(\\d+)");
    MatchResult result = s.match();
    for (int i=1; i<=result.groupCount(); i++)
    System.out.println(result.group(i));
    s.close();

The output for this:

Team A
Team B
2
3

as it should be.

However, since there is another case where the match has yet to be played Team A  Team B. The 2 team names in this case are separated by 2 spaces. The regex used above no longer works so I have 2 cases. This is my overall code:

        String homeTeam;
        String awayTeam;
        int homeGoal = 0;
        int awayGoal = 0;
        String input = "Team A 2-3 Team B";
        Scanner s = new Scanner(input).useDelimiter("-");

    boolean b = Pattern.matches(" (\\d+)-(\\d+) ", input);
    if (b){
        String[] teamNames = input.split(" (\\d+)-(\\d+) ");
        homeTeam = teamNames[0];
        awayTeam = teamNames[1];
        for(int i = 0; i < teamNames.length; i++) {
            System.out.println(teamNames[i]);
        }
        s.findInLine("(\\d+)-(\\d+)");
        MatchResult result = s.match();
        for (int i=1; i<=result.groupCount(); i++)
            System.out.println(result.group(i));
        s.close();
    } else {
        String[] teamNames = input.split("  ");
        homeTeam = teamNames[0];
        awayTeam = teamNames[1];
        for(int i = 0; i < teamNames.length; i++) {
            System.out.println(teamNames[i]);
        }
    }
    System.out.println(b);

The problem that I am getting is that b is returning false even for the string

Team A 2-3 Team B

And so only the else case is returned with this code.

I tested both parts individually with strings that match their own pattern and they worked fine but not when I combine then like this.

Body:
Code

See regex in use here

([\w ]*?)\s+(?:(\d+)-(\d+))?\s+([\w ]*)

Code

See code in use here

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        final String regex = "([\\w ]*?)\\s+(?:(\\d+)-(\\d+))?\\s+([\\w ]*)";
        final String[] strings = {"Team A 2-3 Team B", "Team A  Team B"};

        final Pattern pattern = Pattern.compile(regex);

        for (String string : strings) {
            Matcher matcher = pattern.matcher(string);
            if(matcher.find()) {
                System.out.println("Home team: " + matcher.group(1));
                if(matcher.group(2) != null) {
                    System.out.println("Home goal: " + matcher.group(2));
                    System.out.println("Away goal: " + matcher.group(3));
                }
                System.out.println("Away team: " + matcher.group(4));
                System.out.println("\n");
            }
        }
    }
}

Explanation

([\w ]*?) Capture any character in the set (word characters or space) any number of times, but as few as possible, into capture group 1

\s+ Match one or more whitespace characters

(?:(\d+)-(\d+))? Match the following zero or one time

(\d+) Capture one or more digits into capture group 2

- Match the hyphen character - literally

(\d+) Capture one or more digits into capture group 3

\s+ Match one or more whitespace characters

([\w ]*) Capture any character in the set (word characters or space) any number of times into capture group 4


来源: stackexchange

问:
C string arrays

Possible Duplicates:

  string literal in c

  Assigning strings to arrays of characters

I got the following code:

```<code>char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";
</code>```

It won't compile saying Incompatible types in assignment. What am I doing wrong?

答:
```<code>char result[3][10] = {
  "horse",
  "pig",
  "chicken",
}
</code>```

or

```<code>char result[3][10];

strcpy_s(result[0], 10, "horse");
strcpy_s(result[1], 10, "pig");
strcpy_s(result[2], 10, "chicken");
</code>```

ContentLicense: CC BY-SA 2.5

Title: C string arrays

Body:
Possible Duplicates:

  string literal in c

  Assigning strings to arrays of characters

I got the following code:

char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";

It won't compile saying Incompatible types in assignment. What am I doing wrong?

Body:
char result[3][10] = {
  "horse",
  "pig",
  "chicken",
}

or

char result[3][10];

strcpy_s(result[0], 10, "horse");
strcpy_s(result[1], 10, "pig");
strcpy_s(result[2], 10, "chicken");


问:
create slider to change android volume?
Can someone give me an sample code for changing volume through a slider?
I searched and a lot of tutorials requied me to create a whole new class. Is there an easier way?

Thanks!

答:
Six years later, this slightly altered version works for me in Android Studio 3.1. The IDE said I had to declare AudioManager final:</p>

```<code>        /* volume slider*/
final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
SeekBar volControl = (SeekBar)findViewById(R.id.volControl);
volControl.setMax(maxVolume);
volControl.setProgress(curVolume);
volControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
    @Override
    public void onStopTrackingTouch(SeekBar arg0) {
    }

    @Override
    public void onStartTrackingTouch(SeekBar arg0) {
    }

    @Override
    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
    }
});

//end Volume slider
</code>```

ContentLicense: CC BY-SA 3.0

Title: create slider to change android volume?

Body:
Six years later, this slightly altered version works for me in Android Studio 3.1. The IDE said I had to declare AudioManager final:

        /* volume slider*/
final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
SeekBar volControl = (SeekBar)findViewById(R.id.volControl);
volControl.setMax(maxVolume);
volControl.setProgress(curVolume);
volControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
    @Override
    public void onStopTrackingTouch(SeekBar arg0) {
    }

    @Override
    public void onStartTrackingTouch(SeekBar arg0) {
    }

    @Override
    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
    }
});

//end Volume slider


问:
ASP.NET MVC Scaffolding View - Missing Model Property
This is my first time with MVC so please excuse me if I am getting the terminology wrong.  I am working on a PluralSight course.

My understanding is scaffolding goes to the model and creates a view when selecting Add View.

Here's my model

```<code>    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace OdeToFood.Models
    {
        public class RestaurantReview
        {
            public int Id { get; set; }
            public int Rating { get; set; }
            public string Body { get; set; }
            public string ReviewerName { get; internal set; }
            public int RestaurantId { get; set; }

        }
  }
</code>```

I go to my controller action and click Add View.  My view is missing ReviewerName when it is built.  I add ReviewerName manually to my Create view.  The ReviewerName appears to not be recognized by the Model Binder when data is added to the database.

I am unsure where to go from here.  Thanks for you help!

答:
When you mark the property setter as internal, the scaffolding ignores it. Simply remove that from the property and you should be set (pun intended):</p>

```<code>public string ReviewerName { get; set; }
</code>```

Body:
This is my first time with MVC so please excuse me if I am getting the terminology wrong.  I am working on a PluralSight course.

My understanding is scaffolding goes to the model and creates a view when selecting Add View.

Here's my model

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace OdeToFood.Models
    {
        public class RestaurantReview
        {
            public int Id { get; set; }
            public int Rating { get; set; }
            public string Body { get; set; }
            public string ReviewerName { get; internal set; }
            public int RestaurantId { get; set; }

        }
  }

I go to my controller action and click Add View.  My view is missing ReviewerName when it is built.  I add ReviewerName manually to my Create view.  The ReviewerName appears to not be recognized by the Model Binder when data is added to the database.

I am unsure where to go from here.  Thanks for you help!

Body:
When you mark the property setter as internal, the scaffolding ignores it. Simply remove that from the property and you should be set (pun intended):

public string ReviewerName { get; set; }


问:
Is it possible continue a paused async function? (2)
I've made some changes in the previous code, running more tests, and I've run into the same problem again (Is it possible continue a stopped async function?). So this question is related.

Furthermore, the previous solution does not work.

var stop = false;
var pause = false;
var elParrafo = document.getElementById('miParrafo');

function sendPause() {
  pause = true;
}

function sendContinue() {
  pause = false;
}

function sendStop() {
  stop = true;
}

function longWork(ms, char) {
  return new Promise(function(resolve, reject) {
    elParrafo.innerHTML += char;
    setTimeout(resolve, ms);
  });
}

async function doIt() {
  for (var i = 0; i < 666; i++) {
    if (!stop) {
      if (!pause) {
        await longWork(50," > ");
      }
    } else {
      break;
    }
  }
}

doIt();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="" action="index.html" method="post">
  <input type="button" value="Pause" onclick="sendPause()">
  <input type="button" value="Continue" onclick="sendContinue()">
  <input type="button" value="Stop" onclick="sendStop()">
</form>
<p id="miParrafo"></p></code>```

答:
Here is a simple solution that uses setInterval:

var task = (function(){
  var timer;
  var taskImplementation;
  var max;
  var ms;
  var timesRun = 0;
  var isPaused = false;
  const runTask = function(){
    if(!isPaused && timesRun<max){
      taskImplementation();
      timesRun++;
    }else{
      clearInterval(timer);
    }
  };
  const reset = function() {
    timesRun=0;
    isPaused=false;
  };
  const start = function(){
    if(timer){
      stop();
    }
    reset();
    timer = setInterval(runTask,ms);
  };
  const stop = function(){
    reset();
    clearInterval(timer);
  };
  const pause = function(){
    clearTimeout(timer);
  };
  const cont = function(){
    timer = setInterval(runTask,ms);
  };
  return function(doWhat){
    taskImplementation = doWhat;
    return function(interval){
      ms = interval;
      return function(howManyTimes){
        max = howManyTimes;
        return {
          start:start,
          stop:stop,
          pause:pause,
          continue:cont
        }
      }
    }
  }
})();
var doWhat = (function(elParrafo){
  return function(){
    elParrafo.innerHTML += " > ";
  }
})(document.getElementById('miParrafo'));
var interval =200;//how long to wait between task execution
var howManyTimes = 666;//how many times to repeat task
window.setParrafoTask = task(doWhat)(interval)(howManyTimes);```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <form class="" action="index.html" method="post">
        <input type="button" value="Start" onclick="setParrafoTask.start()">
        <input type="button" value="Pause" onclick="setParrafoTask.pause()">
        <input type="button" value="Continue" onclick="setParrafoTask.continue()">
        <input type="button" value="Stop" onclick="setParrafoTask.stop()">
      </form>
      <p id="miParrafo"></p></code>```

Body:
I've made some changes in the previous code, running more tests, and I've run into the same problem again (Is it possible continue a stopped async function?). So this question is related.

Furthermore, the previous solution does not work.

var stop = false;
var pause = false;
var elParrafo = document.getElementById('miParrafo');

function sendPause() {
  pause = true;
}

function sendContinue() {
  pause = false;
}

function sendStop() {
  stop = true;
}

function longWork(ms, char) {
  return new Promise(function(resolve, reject) {
    elParrafo.innerHTML += char;
    setTimeout(resolve, ms);
  });
}

async function doIt() {
  for (var i = 0; i < 666; i++) {
    if (!stop) {
      if (!pause) {
        await longWork(50," > ");
      }
    } else {
      break;
    }
  }
}

doIt();

<form class="" action="index.html" method="post">
  <input type="button" value="Pause" onclick="sendPause()">
  <input type="button" value="Continue" onclick="sendContinue()">
  <input type="button" value="Stop" onclick="sendStop()">
</form>

Body:
Here is a simple solution that uses setInterval:

var task = (function(){
  var timer;
  var taskImplementation;
  var max;
  var ms;
  var timesRun = 0;
  var isPaused = false;
  const runTask = function(){
    if(!isPaused && timesRun<max){
      taskImplementation();
      timesRun++;
    }else{
      clearInterval(timer);
    }
  };
  const reset = function() {
    timesRun=0;
    isPaused=false;
  };
  const start = function(){
    if(timer){
      stop();
    }
    reset();
    timer = setInterval(runTask,ms);
  };
  const stop = function(){
    reset();
    clearInterval(timer);
  };
  const pause = function(){
    clearTimeout(timer);
  };
  const cont = function(){
    timer = setInterval(runTask,ms);
  };
  return function(doWhat){
    taskImplementation = doWhat;
    return function(interval){
      ms = interval;
      return function(howManyTimes){
        max = howManyTimes;
        return {
          start:start,
          stop:stop,
          pause:pause,
          continue:cont
        }
      }
    }
  }
})();
var doWhat = (function(elParrafo){
  return function(){
    elParrafo.innerHTML += " > ";
  }
})(document.getElementById('miParrafo'));
var interval =200;//how long to wait between task execution
var howManyTimes = 666;//how many times to repeat task
window.setParrafoTask = task(doWhat)(interval)(howManyTimes);

    <form class="" action="index.html" method="post">
        <input type="button" value="Start" onclick="setParrafoTask.start()">
        <input type="button" value="Pause" onclick="setParrafoTask.pause()">
        <input type="button" value="Continue" onclick="setParrafoTask.continue()">
        <input type="button" value="Stop" onclick="setParrafoTask.stop()">
      </form>
      <p id="miParrafo"></p>


问:
Problem trying to detour function with assembly
Just for the fun of it, I am trying to make a simple detouring library that will detour member functions by modifying the vtable of the class to create a detour. I am getting some odd behaviour. Here is the entire program (I am using MSVC++ 2010):

```<code>fixed
</code>```

It's jmping to the address of the new function correctly, but it crashes after that. When I watch it in ollydbg to see why it's crashing, something very strange happens. It will walk right over some instructions without doing anything. Where I see a push xxx in the debugger, the stack will not be modified. Where I see a retn 4 the thing will just keep going, into the space between functions, filled with int 3s. Does anyone have any idea why this is happening?

EDIT: Nevermind, I found the answer.

答: Found the problem. Turns out you have to subtract 5 from the address to calculate it correctly, since it's the relative address not from the end of the instruction but from the beginning.</p>

Body:
Just for the fun of it, I am trying to make a simple detouring library that will detour member functions by modifying the vtable of the class to create a detour. I am getting some odd behaviour. Here is the entire program (I am using MSVC++ 2010):

fixed

It's jmping to the address of the new function correctly, but it crashes after that. When I watch it in ollydbg to see why it's crashing, something very strange happens. It will walk right over some instructions without doing anything. Where I see a push xxx in the debugger, the stack will not be modified. Where I see a retn 4 the thing will just keep going, into the space between functions, filled with int 3s. Does anyone have any idea why this is happening?

EDIT: Nevermind, I found the answer.


答:
If the scores in the middle of the string may not be present, you can modify your expression to indicate so:</p>

```<code>    boolean b = Pattern.matches(" ((\\d+)-(\\d+))? ", input);
    ...
    String[] teamNames = input.split(" ((\\d+)-(\\d+))? ");
</code>```

Title: Java - String can be split with regex but regex match returns false

Body:
If the scores in the middle of the string may not be present, you can modify your expression to indicate so:

    boolean b = Pattern.matches(" ((\\d+)-(\\d+))? ", input);
    ...
    String[] teamNames = input.split(" ((\\d+)-(\\d+))? ");


问:
Using identical list comprehensions on two separate lists

This feels like a simple question, but I haven't been able to figure it out and I haven't been able to find the answer anywhere.

In one line, how can I use two identical list comprehensions on two different lists, and return the results as two seperate lists?

I am trying to do this:

```<code>listx = [x for x in listx if x != None]
listy = [y for y in listy if y != None]
</code>```

Is there a way to do this in one line? Perhaps using map() or a list comprehension?

答:
As simple as:</p>

```<code>listx, listy = [x for x in listx if x != None], [y for y in listy if y != None]
</code>```

Body:
This feels like a simple question, but I haven't been able to figure it out and I haven't been able to find the answer anywhere.

In one line, how can I use two identical list comprehensions on two different lists, and return the results as two seperate lists?

I am trying to do this:

listx = [x for x in listx if x != None]
listy = [y for y in listy if y != None]

Is there a way to do this in one line? Perhaps using map() or a list comprehension?

Body:
As simple as:

listx, listy = [x for x in listx if x != None], [y for y in listy if y != None]


问:
JSON structure PHP - strange
Im working with Google tag Manager API(v2), and trying to add some new lines to my existing JSON array. I first had some trouble adding data to my JSON object because the data was shown on the last row and not inside the object itself.

Now ive changed my code but the data does not look like its inside the object itself but im a little bit closer now. This is how my JSON object looks like now:

JSON:

```<code>{
    "Account2": [{
        "accountId": "17467*****",
        "containerId": "745****",
    }, 3, 3, 4, {
        "accountId": "17467*****",
        "containerId": "751****",
    }, 1, 1, 2],
    "Account 1": [{
        "accountId": "17661*****",
        "containerId": "748****",
    }, 2, 1, 1],
    "GTMdocx": [{
        "accountId": "21200*****",
        "containerId": "803****",
    }, 0, 0, 1],
    "Account3": [{
        "accountId": "21281*****",
        "containerId": "803****",
    }, 0, 0, 0]
}
</code>```

As you can see the object is structured like this:

1) Accountname

2) Inside Accountname we have accountId and containerId

3) at last of one Accountname object we have some numbers(count), the problem is that it looks like this:

What i would want the JSON-object to look like is like this:

```<code>{
    "Account2": [{
        "accountId": "17467*****",
        "containerId": "745****",
        "tags": "3",
        "triggers": "3",
        "variables": "4"

    }, {
        "accountId": "17467*****",
        "containerId": "751****",
        "tags": "3",
        "triggers": "3",
        "variables": "4"
    }],
    "Account 1": [{
        "accountId": "17661*****",
        "containerId": "748****",
        "tags": "2",
        "triggers": "1",
        "variables": "1"
    }],
    "GTMdocx": [{
        "accountId": "21200*****",
        "containerId": "803****",
        "tags": "0",
        "triggers": "0",
        "variables": "1"
    }],
    "Account3": [{
        "accountId": "21281*****",
        "containerId": "803****",
        "tags": "0",
        "triggers": "0",
        "variables": "0"
    }]
}
</code>```

You can see the numbers got a key and then value inside the object.

This is my PHP-code:

```<code>static public function listAllContainers() {

    try { //Because some containers might not have live-version
        $containers[] = array();
        foreach (self::listAccounts()->account as $accountKey => $account) {
            foreach (self::listAccountsContainers($account["path"]) as $account_container) {
                $containers[$account['name']][] = $account_container;

                $container_version = self::listAccountsContainersVersion($account_container['path']);
                $containers[$account['name']][] = count($container_version['tag']);
                $containers[$account['name']][] = count($container_version['trigger']);
                $containers[$account['name']][] = count($container_version['variable']);

            }
        }
        $filtered_array = (object)array_filter((array)$containers); // Removes empty object
        return $filtered_array;
    } catch (\Exception $e) {
        return $e->getCode();
    }
}
</code>```

Hope you understand my problem. Not so much experience with Arrays/JSON so maybe my explanation is not so good.
Thanks!

UPDATE:

Using $containers[$account['name']]['tag'] = count($container_version['tag']); gives me this JSON: (PS: ive removed some from the json so it wont be long, this makes the json invalid)

```<code>{
Account2: {
0: {
accountId: "174675****",
containerId: "745****",
},
1: {
accountId: "174675****59",
containerId: "751****83",
},
tag: 1,
trigger: 1,
variable: 2
},
Account 1: {
0: {
accountId: "1766***525",
containerId: "748***53",
},
tag: 2,
trigger: 1,
variable: 1
},
</code>```

Now each "Account" can have multiple "containers"(accountId,containerId), using this method does not store the data inside the object itself.

答:
I put together another solution without modifying the original $account_container.

I've added the new data in a new array $account_container_extra and merged that together with $account_container when appending it to the $container array.

Maybe that will work better for you or give you some other ideas.

```<code>static public function listAllContainers() {

    try { //Because some containers might not have live-version
        $containers[] = array();
        foreach (self::listAccounts()->account as $accountKey => $account) {
            foreach (self::listAccountsContainers($account["path"]) as $account_container) {
                $container_version = self::listAccountsContainersVersion($account_container['path']);

                $account_container_extra = [
                    'tag' => count($container_version['tag']),
                    'trigger' => count($container_version['trigger']),
                    'variable' => count($container_version['variable'])
                ];

                $containers[$account['name']][] = array_merge($account_container, $account_container_extra);
            }
        }
        $filtered_array = (object)array_filter((array)$containers); // Removes empty object
        return $filtered_array;
    } catch (\Exception $e) {
        return $e->getCode();
    }
}
</code>```

Title: JSON structure PHP - strange

Body:
Im working with Google tag Manager API(v2), and trying to add some new lines to my existing JSON array. I first had some trouble adding data to my JSON object because the data was shown on the last row and not inside the object itself.

Now ive changed my code but the data does not look like its inside the object itself but im a little bit closer now. This is how my JSON object looks like now:

JSON:

{
    "Account2": [{
        "accountId": "17467*****",
        "containerId": "745****",
    }, 3, 3, 4, {
        "accountId": "17467*****",
        "containerId": "751****",
    }, 1, 1, 2],
    "Account 1": [{
        "accountId": "17661*****",
        "containerId": "748****",
    }, 2, 1, 1],
    "GTMdocx": [{
        "accountId": "21200*****",
        "containerId": "803****",
    }, 0, 0, 1],
    "Account3": [{
        "accountId": "21281*****",
        "containerId": "803****",
    }, 0, 0, 0]
}

As you can see the object is structured like this:

1) Accountname

2) Inside Accountname we have accountId and containerId

3) at last of one Accountname object we have some numbers(count), the problem is that it looks like this:

What i would want the JSON-object to look like is like this:

{
    "Account2": [{
        "accountId": "17467*****",
        "containerId": "745****",
        "tags": "3",
        "triggers": "3",
        "variables": "4"

    }, {
        "accountId": "17467*****",
        "containerId": "751****",
        "tags": "3",
        "triggers": "3",
        "variables": "4"
    }],
    "Account 1": [{
        "accountId": "17661*****",
        "containerId": "748****",
        "tags": "2",
        "triggers": "1",
        "variables": "1"
    }],
    "GTMdocx": [{
        "accountId": "21200*****",
        "containerId": "803****",
        "tags": "0",
        "triggers": "0",
        "variables": "1"
    }],
    "Account3": [{
        "accountId": "21281*****",
        "containerId": "803****",
        "tags": "0",
        "triggers": "0",
        "variables": "0"
    }]
}

You can see the numbers got a key and then value inside the object.

This is my PHP-code:

static public function listAllContainers() {

    try { //Because some containers might not have live-version
        $containers[] = array();
        foreach (self::listAccounts()->account as $accountKey => $account) {
            foreach (self::listAccountsContainers($account["path"]) as $account_container) {
                $containers[$account['name']][] = $account_container;

                $container_version = self::listAccountsContainersVersion($account_container['path']);
                $containers[$account['name']][] = count($container_version['tag']);
                $containers[$account['name']][] = count($container_version['trigger']);
                $containers[$account['name']][] = count($container_version['variable']);

            }
        }
        $filtered_array = (object)array_filter((array)$containers); // Removes empty object
        return $filtered_array;
    } catch (\Exception $e) {
        return $e->getCode();
    }
}

Hope you understand my problem. Not so much experience with Arrays/JSON so maybe my explanation is not so good.
Thanks!

UPDATE:

Using $containers[$account['name']]['tag'] = count($container_version['tag']); gives me this JSON: (PS: ive removed some from the json so it wont be long, this makes the json invalid)

{
Account2: {
0: {
accountId: "174675****",
containerId: "745****",
},
1: {
accountId: "174675****59",
containerId: "751****83",
},
tag: 1,
trigger: 1,
variable: 2
},
Account 1: {
0: {
accountId: "1766***525",
containerId: "748***53",
},
tag: 2,
trigger: 1,
variable: 1
},

Now each "Account" can have multiple "containers"(accountId,containerId), using this method does not store the data inside the object itself.

Body:
I put together another solution without modifying the original $account_container.

I've added the new data in a new array $account_container_extra and merged that together with $account_container when appending it to the $container array.

Maybe that will work better for you or give you some other ideas.

static public function listAllContainers() {

    try { //Because some containers might not have live-version
        $containers[] = array();
        foreach (self::listAccounts()->account as $accountKey => $account) {
            foreach (self::listAccountsContainers($account["path"]) as $account_container) {
                $container_version = self::listAccountsContainersVersion($account_container['path']);

                $account_container_extra = [
                    'tag' => count($container_version['tag']),
                    'trigger' => count($container_version['trigger']),
                    'variable' => count($container_version['variable'])
                ];

                $containers[$account['name']][] = array_merge($account_container, $account_container_extra);
            }
        }
        $filtered_array = (object)array_filter((array)$containers); // Removes empty object
        return $filtered_array;
    } catch (\Exception $e) {
        return $e->getCode();
    }
}


问:
Memcpy a str[ ] to str*
I'm trying to create a xoring function ( I want to XOR 2 strings and return the result).

For that, I need to copy the content a an array (str[ ]) to a string (str* ).

```<code>char* xor(char* str1, char* str2)
{
    char temp[strlen(str1)];
    char* result = NULL;
    int i;

    for(i=0; i<=strlen(str1); i++)
    {
        temp[i] = str1[i] ^ str2[i];
    }
    memcpy(result,temp,sizeof(temp)+1);
    return result;
}
</code>```

I'm getting a seg fault for my memcpy.

Am I missing something ? Can you help me ?

答:
You should declare the array as minimum length of 2 strings+1. Otherwise you might access array index out of bound while accessing str1 and str2.

```<code>for(i=0; i< min( strlen(str1) , strlen(str2) ) ; i++)
    {
        temp[i] = str1[i] ^ str2[i];
    }
temp[i]='\0';
</code>```

You were accessing one element more index than you should. This is where you get the segmentation fault.

Also you didn't allocate anything in result. Solution would be something like

```<code>result = malloc(sizeof(temp));
</code>```

memcpy() tries to copy to the memory which is not pointing to any valid determinate portion of memory resulting in undefined behavior.

Snippet code

```<code>size_t min(size_t x, size_t y){
    return x<y?x:y;
}
char* xor(char* str1, char* str2)
{
    char temp[min(strlen(str1),strlen(str2))+1];
    char* result = malloc(sizeof temp);
    if( result == NULL){
        fprintf(stderr, "%s\n", "Error in malloc");
        exit(1);
    }
    size_t i;

    for( i = 0; i <= strlen(str1); i++)
        temp[i] = str1[i] ^ str2[i];
    temp[i] = '\0';
    memcpy(result,temp,sizeof(temp));
    return result;
}
</code>```

To Summarize the problem was -

Accessing array index out of bound.

Passing an uninitialized pointer to memcpy.

Also leaving a scope for undefined behavior when the string lengths for the two strings differ.

Now the question is what is the purpose of this process..we may run into nonprintable characters and so on, which are of not much use, from the usual string operation's perspective.

One more thing

Your heading of the question was Memcpy a str[ ] to str*. Now what you meant was Memcpy a char[ ] to char*.

The thing is char* holds address of some memory. So when we would copy where will we copy? The memory address pointed by that char*. And your case that was simply was an indeterminate uninitialized value. You were copying there - that is UB.

Title: Memcpy a str[ ] to str*

Body:
I'm trying to create a xoring function ( I want to XOR 2 strings and return the result).

For that, I need to copy the content a an array (str[ ]) to a string (str* ).

char* xor(char* str1, char* str2)
{
    char temp[strlen(str1)];
    char* result = NULL;
    int i;

    for(i=0; i<=strlen(str1); i++)
    {
        temp[i] = str1[i] ^ str2[i];
    }
    memcpy(result,temp,sizeof(temp)+1);
    return result;
}

I'm getting a seg fault for my memcpy.

Am I missing something ? Can you help me ?

Body:
You should declare the array as minimum length of 2 strings+1. Otherwise you might access array index out of bound while accessing str1 and str2.

for(i=0; i< min( strlen(str1) , strlen(str2) ) ; i++)
    {
        temp[i] = str1[i] ^ str2[i];
    }
temp[i]='\0';

You were accessing one element more index than you should. This is where you get the segmentation fault.

Also you didn't allocate anything in result. Solution would be something like

result = malloc(sizeof(temp));

memcpy() tries to copy to the memory which is not pointing to any valid determinate portion of memory resulting in undefined behavior.

Snippet code

size_t min(size_t x, size_t y){
    return x<y?x:y;
}
char* xor(char* str1, char* str2)
{
    char temp[min(strlen(str1),strlen(str2))+1];
    char* result = malloc(sizeof temp);
    if( result == NULL){
        fprintf(stderr, "%s\n", "Error in malloc");
        exit(1);
    }
    size_t i;

    for( i = 0; i <= strlen(str1); i++)
        temp[i] = str1[i] ^ str2[i];
    temp[i] = '\0';
    memcpy(result,temp,sizeof(temp));
    return result;
}

To Summarize the problem was -

Accessing array index out of bound.

Passing an uninitialized pointer to memcpy.

Also leaving a scope for undefined behavior when the string lengths for the two strings differ.

Now the question is what is the purpose of this process..we may run into nonprintable characters and so on, which are of not much use, from the usual string operation's perspective.

One more thing

Your heading of the question was Memcpy a str[ ] to str*. Now what you meant was Memcpy a char[ ] to char*.

The thing is char* holds address of some memory. So when we would copy where will we copy? The memory address pointed by that char*. And your case that was simply was an indeterminate uninitialized value. You were copying there - that is UB.


问:
How to generate all possible pairs with permutations from list in Python?
How do I generate all possible pairs permutations from a list in Python?

Example:

```<code>input = [3, 8, 2]
output = ['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']
</code>```

答:
You can use itertools.permutations:

```<code>import itertools
input = [3, 8, 2]
final_list = ["{}-{}".format(*i) for i in itertools.permutations(input, 2)]
</code>```

Output:

```<code>['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']
</code>```

However, if you want all operations up-to and including the length of the list, you can try this:

```<code>final_list = list(itertools.chain(*[['-'.join(["{}"]*b).format(*i) for i in itertools.permutations(input, b)] for b in range(2, len(input)+1)]))
</code>```

Output:

```<code>['3-8', '3-2', '8-3', '8-2', '2-3', '2-8', '3-8-2', '3-2-8', '8-3-2', '8-2-3', '2-3-8', '2-8-3']
</code>```

Edit: for all possible operands:

```<code>import re
def tokenize(s):
   converter = {"-":lambda x, y:x-y, '+':lambda x, y:x+y}
   total = 0
   stack = re.findall('\d+|[\-\+]', s)
   operator = None
   for i in stack:
      if i.isdigit():
         if not operator:
            total += int(i)
         else:
            total = converter[operator](total, int(i))
            operator = None
      else:
          operator = i
   return total

new_list = set(list(itertools.chain(*list(itertools.chain(*[[[''.join([''.join('{}'+i) for i in b]+['{}']).format(*c) for b in itertools.permutations(['-', '+'], len(c)-1)] for c in itertools.permutations(input, x)] for x in range(2, len(input)+1)])))))
final_list = {tokenize(a):a for a in new_list}
new_final_list = [b for a, b in final_list.items()]
</code>```

Output:

```<code>['3-2', '8-3', '8-2', '8-3+2', '8-2+3', '8+2', '8+3', '2-8', '3-8', '3+2-8', '2-3']
</code>```

Body:
How do I generate all possible pairs permutations from a list in Python?

Example:

input = [3, 8, 2]
output = ['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']

Body:
You can use itertools.permutations:

import itertools
input = [3, 8, 2]
final_list = ["{}-{}".format(*i) for i in itertools.permutations(input, 2)]

Output:

['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']

However, if you want all operations up-to and including the length of the list, you can try this:

final_list = list(itertools.chain(*[['-'.join(["{}"]*b).format(*i) for i in itertools.permutations(input, b)] for b in range(2, len(input)+1)]))

Output:

['3-8', '3-2', '8-3', '8-2', '2-3', '2-8', '3-8-2', '3-2-8', '8-3-2', '8-2-3', '2-3-8', '2-8-3']

Edit: for all possible operands:

import re
def tokenize(s):
   converter = {"-":lambda x, y:x-y, '+':lambda x, y:x+y}
   total = 0
   stack = re.findall('\d+|[\-\+]', s)
   operator = None
   for i in stack:
      if i.isdigit():
         if not operator:
            total += int(i)
         else:
            total = converter[operator](total, int(i))
            operator = None
      else:
          operator = i
   return total

new_list = set(list(itertools.chain(*list(itertools.chain(*[[[''.join([''.join('{}'+i) for i in b]+['{}']).format(*c) for b in itertools.permutations(['-', '+'], len(c)-1)] for c in itertools.permutations(input, x)] for x in range(2, len(input)+1)])))))
final_list = {tokenize(a):a for a in new_list}
new_final_list = [b for a, b in final_list.items()]

Output:

['3-2', '8-3', '8-2', '8-3+2', '8-2+3', '8+2', '8+3', '2-8', '3-8', '3+2-8', '2-3']


答:
just feed your list to itertools.permutations and format accordingly in a list comprehension directly passing the tuple to format using the * operator.

```<code>import itertools

result = ["{}-{}".format(*x) for x in itertools.permutations([3, 8, 2],2)]

print(result)
</code>```

result:

```<code>['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']
</code>```

As a side note, don't use input as a variable name as it overrides the interactive text input function.

Title: How to generate all possible pairs with permutations from list in Python?

Body:
just feed your list to itertools.permutations and format accordingly in a list comprehension directly passing the tuple to format using the * operator.

import itertools

result = ["{}-{}".format(*x) for x in itertools.permutations([3, 8, 2],2)]

print(result)

result:

['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']

As a side note, don't use input as a variable name as it overrides the interactive text input function.


答:
You should allocate space for result using either malloc or calloc. Currently, result is NULL. Hence, the segfault.

Moreover, you should not use sizeof(temp)+1 in your call to memcpy. You are invoking UB. You are trying to access one byte beyond what you have allocated to temp. That's wrong.

Title: Memcpy a str[ ] to str*


问:
How can I combine two excel columns during import to a database?

I am trying to combine a date and time columns in excel and map it to one column in a database using sqlbulkcopy. I am getting an error:

Date][time does not match any column mapping

See my sample code below. Any ideas on how to accomplish this without copying it to a Datatable?

```<code>Dim sSourceConstr As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", sPath)

Dim sDestConstr As String = ConfigurationManager.ConnectionStrings("SolCards").ConnectionString
Dim sSourceConnection As New OleDbConnection(sSourceConstr)
Using sSourceConnection
    Dim sql As String = String.Format("Select [Customer Cod],[Customer],[PAN],[Vehicle],[Date],[Station],[Driver],[Authorized],[Product]" &
                                          ", [Pump], [Tran No], [Odo], [Metric], [UPrice], [Qty], [Amount], [TimeFormat] FROM [{0}$]", "trans")
    Dim command As New OleDbCommand(sql, sSourceConnection)

    sSourceConnection.Open()
    Using dr As OleDbDataReader = command.ExecuteReader()
        Using bulkCopy As New SqlBulkCopy(sDestConstr)
            bulkCopy.DestinationTableName = "FuelInformation"
            'column mapping

          bulkCopy.ColumnMappings.Add("[Date] [Time]", "DatePurchased")

            bulkCopy.WriteToServer(dr)
        End Using
    End Using
End Using
</code>```

答:
The fix for the error is :</p>

```<code> "Select ([date],[time])values(@date,@time)"
   bulkCopy.ColumnMappings.Add("@Date", "DatePurchased")
   bulkCopy.ColumnMappings.Add("@time", "DatePurchased")
</code>```

Body:
I am trying to combine a date and time columns in excel and map it to one column in a database using sqlbulkcopy. I am getting an error:

Date][time does not match any column mapping

See my sample code below. Any ideas on how to accomplish this without copying it to a Datatable?

Dim sSourceConstr As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", sPath)

Dim sDestConstr As String = ConfigurationManager.ConnectionStrings("SolCards").ConnectionString
Dim sSourceConnection As New OleDbConnection(sSourceConstr)
Using sSourceConnection
    Dim sql As String = String.Format("Select [Customer Cod],[Customer],[PAN],[Vehicle],[Date],[Station],[Driver],[Authorized],[Product]" &
                                          ", [Pump], [Tran No], [Odo], [Metric], [UPrice], [Qty], [Amount], [TimeFormat] FROM [{0}$]", "trans")
    Dim command As New OleDbCommand(sql, sSourceConnection)

    sSourceConnection.Open()
    Using dr As OleDbDataReader = command.ExecuteReader()
        Using bulkCopy As New SqlBulkCopy(sDestConstr)
            bulkCopy.DestinationTableName = "FuelInformation"
            'column mapping

          bulkCopy.ColumnMappings.Add("[Date] [Time]", "DatePurchased")

            bulkCopy.WriteToServer(dr)
        End Using
    End Using
End Using

Body:
The fix for the error is :

 "Select ([date],[time])values(@date,@time)"
   bulkCopy.ColumnMappings.Add("@Date", "DatePurchased")
   bulkCopy.ColumnMappings.Add("@time", "DatePurchased")


问:
Nodemailer is not sending mails to valid emailids if array contains invalid emailids
I have tried to send multiple emails with nodemailer-smtp-transport in nodejs but if multiple recipients list contains valid and invalid email ids then mails are not going to valid emails ,always it is going to error callback.

My sample code:-

```<code>var testemails=["name.@gmail.com,santosh@gmail.com"];
var mailOptions = {
    from:config.email_from_addr,
    //bcc :receiver_email,
    bcc:testemails,
    subject :subject,
    html:html
};
var transporter = nodemailer.createTransport(smtpTransport({
    host:config.email_host_name,
    port: 25
}));
transporter.sendMail(mailOptions, function(error, info){
    console.log("error: "+error);
    console.log("info: "+info);
    if(error){
        //console.log("Rejected: "+info.rejected);
        console.log("error",'Failed to send: '+subject+' ; Error: '+error);
        return callback(null);
    }else{
        console.log("info","Promotion_EmailFurnished:  "+subject+" : "+receiver_email);
        return callback(null);
    }
});
</code>```

//here Invalid emaild: name.@gmail.com and
 valid emailId:  santosh@gmail.com
and how to  collect if mails are failed to send due to invalid emails?

Any help?

Thanks is advance.

答:
Your array is wrong,

```<code>var testemails=["name.@gmail.com,santosh@gmail.com"];
</code>```

Should be,

```<code>var testemails=["name.@gmail.com","santosh@gmail.com"];
</code>```

Update

Above is just the first thing wrong with you code,

Second

in mailOptions you forgot to put the to address, bcc might work for nodemailer but without a to address it will fail from smtp endpoint.

```<code>var mailOptions = {
    from:config.email_from_addr,
    to : testemails,
    bcc:testemails,
    subject :subject,
    html:html
};
</code>```

Third,

Where is the password field for the transporter ?

sample for latest node mailer :

```<code>var transport = nodemailer.createTransport("SMTP", {
    host: "smtp.gmail.com", // hostname
    secureConnection: true, // use SSL
    port: 465, // port for secure SMTP
    auth: {
        user: "gmail.user@gmail.com",
        pass: "userpass"
    }
});
</code>```

Please use this for more info as well : Docs

Body:
I have tried to send multiple emails with nodemailer-smtp-transport in nodejs but if multiple recipients list contains valid and invalid email ids then mails are not going to valid emails ,always it is going to error callback.

My sample code:-

var testemails=["name.@gmail.com,santosh@gmail.com"];
var mailOptions = {
    from:config.email_from_addr,
    //bcc :receiver_email,
    bcc:testemails,
    subject :subject,
    html:html
};
var transporter = nodemailer.createTransport(smtpTransport({
    host:config.email_host_name,
    port: 25
}));
transporter.sendMail(mailOptions, function(error, info){
    console.log("error: "+error);
    console.log("info: "+info);
    if(error){
        //console.log("Rejected: "+info.rejected);
        console.log("error",'Failed to send: '+subject+' ; Error: '+error);
        return callback(null);
    }else{
        console.log("info","Promotion_EmailFurnished:  "+subject+" : "+receiver_email);
        return callback(null);
    }
});

//here Invalid emaild: name.@gmail.com and
 valid emailId:  santosh@gmail.com
and how to  collect if mails are failed to send due to invalid emails?

Any help?

Thanks is advance.

Body:
Your array is wrong,

var testemails=["name.@gmail.com,santosh@gmail.com"];

Should be,

var testemails=["name.@gmail.com","santosh@gmail.com"];

Update

Above is just the first thing wrong with you code,

Second

in mailOptions you forgot to put the to address, bcc might work for nodemailer but without a to address it will fail from smtp endpoint.

var mailOptions = {
    from:config.email_from_addr,
    to : testemails,
    bcc:testemails,
    subject :subject,
    html:html
};

Third,

Where is the password field for the transporter ?

sample for latest node mailer :

var transport = nodemailer.createTransport("SMTP", {
    host: "smtp.gmail.com", // hostname
    secureConnection: true, // use SSL
    port: 465, // port for secure SMTP
    auth: {
        user: "gmail.user@gmail.com",
        pass: "userpass"
    }
});

Please use this for more info as well : Docs


问:
Automated API blackbox testing
I have a (slightly complex) spring webservice which communicates with multiple frontends via a RESTful API (JSON) and additionally with other devices via SOAP or REST. I'd like setup an automated test environment which is capable of the following things:

create preconditions via fixtures (POSTGRES DB)

send REST or SOAP messages against the API

is able to run certain task (requests against the API) at a specific
time/date

assert and validate the produced results (return of the API call or
check the DB)

run all tests independet from any frontend/UI

integrate the testing environment in my infrastructure (i.e. create a
docker container which runs all tests deployed by Jenkins)

preferably I'd like to build reusable components (i.e. for creating a user that is needed in multiple different tests and so on...). I know there are a lot of tools and frameworks (SoapUI, JMETER,...). But before trying them all and getting lost, I'd like to get an experience report from someone who has a simular setup.

答:
we are using JMeter for API testing.  We tried SOAPui but it had some memory issues.  So we are pushing forward with JMeter and so far so good.

For your questions:

We are using MySQL, but this post seems to show how to set up a postgres connection in JMeter: https://hiromia.blogspot.com/2015/03/how-to-perform-load-testing-on.html

JMeter can send REST API requests

I'm not sure if this is possible but you could probably have your Jenkins job scheduled to run when you need the API to run the specific task at the specific time.

There are quite a few assertions in JMeter.  I use the Response and the BeanShell Assertions a lot.

JMeter is independent from any front end UI which helps pinpoint bugs.

I have not run docker but I am running via Jenkins.  This jenkins plugin has been helpful: https://wiki.jenkins.io/display/JENKINS/Log+Parser+Plugin

A few more Tips:

Use the HTTP Request Defaults element. It will save you from having to update all your HTTP requests.

Use the User Defined Variables to define variables you need.

You can combine user defined variables like:  ${namePrefix}${myTime} but it will have to be in a 2nd User Defined Variable element(you cant combine them in the same element)

If you have multiple test environments, set up a user defined variable with a value like this: ${__P(testenv,staging)}  This way, you can change it from a CLI like this: -Jtestenv=HOTFIX

We are using ExtentReports for pretty html results reports with a custom JSR223 Listener(find my old post on this site).

If your site uses cookies, use the HTTP Cookie Manager.

If you need things to happen in order, on the Test Plan element, check this option: Run Threat Groups consecutively.  If you dont, JMeter runs them in a random order.

Hope this is helpful.  Happy Testing!

Title: Automated API blackbox testing


问:
Images not filling wrapper
 elements

The Problem:

So I have this webpage: http://a.yfrog.com/img610/3543/p4.png

I have several images that are layered together to create the background gradient, but for whatever reason, the two side gradients aren't filling the entire page. All the gradients are in  elements that wrap the entire page. If I set the overflow of one of the divs to overflow:auto; I can scroll that div to the length of the page (which I set to 5000px for testing) but its only in the box where you see that little cutoff, and as far as I can tell, it does this in all browsers. What's the issue? And for further clarification, I'm talking about how the gradients on the sides suddenly stop.

CSS:

```<code>#super_wrapper { height:100%; }
#page_bg_top {
  background:url(../images/body/top_shadow.png) repeat-x top;
  height:400px;
}
#page_bg_topleft {
  background:url(../images/body/top_left.png) no-repeat top left;
  height:300px;
}
#page_bg_topright {
  background:url(../images/body/top_right.png) no-repeat top right;
  height:300px;
}
#page_bg_left {
  background:url(../images/body/left_shadow.png) repeat-y left;
  height:100%;
}
#page_bg_right {
  background:url(../images/body/right_shadow.png) repeat-y right;
  height:100%;
}
</code>```

HTML:

```<code><div id="super_wrapper"><div id="page_bg_top"><div id="page_bg_topleft"><div id="page_bg_topright"><div id="page_bg_left"><div id="page_bg_right">
... Page Body
</div></div></div></div></div></div>
</code>```

答:
Well, it appears that there was some sort of height inheritance happening. An element inside of the
 area had a height manually set, and when I removed the height from that element, the background filled the entire page. I haven't the slightest clue why that happened or what caused it.

Title: Images not filling wrapper <div> elements

Body:
The Problem:

So I have this webpage: http://a.yfrog.com/img610/3543/p4.png

I have several images that are layered together to create the background gradient, but for whatever reason, the two side gradients aren't filling the entire page. All the gradients are in  elements that wrap the entire page. If I set the overflow of one of the divs to overflow:auto; I can scroll that div to the length of the page (which I set to 5000px for testing) but its only in the box where you see that little cutoff, and as far as I can tell, it does this in all browsers. What's the issue? And for further clarification, I'm talking about how the gradients on the sides suddenly stop.

CSS:

#super_wrapper { height:100%; }
#page_bg_top {
  background:url(../images/body/top_shadow.png) repeat-x top;
  height:400px;
}
#page_bg_topleft {
  background:url(../images/body/top_left.png) no-repeat top left;
  height:300px;
}
#page_bg_topright {
  background:url(../images/body/top_right.png) no-repeat top right;
  height:300px;
}
#page_bg_left {
  background:url(../images/body/left_shadow.png) repeat-y left;
  height:100%;
}
#page_bg_right {
  background:url(../images/body/right_shadow.png) repeat-y right;
  height:100%;
}

HTML:

... Page Body

Body: Well, it appears that there was some sort of height inheritance happening. An element inside of the <div> area had a height manually set, and when I removed the height from that element, the background filled the entire page. I haven't the slightest clue why that happened or what caused it.


问:
Error Object of class mysqli_result could not be converted to int
Greetings to the whole forum, I'm having a problem with my code, would you give me a hand to understand where I'm wrong?

Notice: Object of class mysqli_result could not be converted to int in C:\xampp\htdocs\gos\page\appuntamenti_privati.phpon line 46

Notice: Object of class mysqli_result could not be converted to int in C:\xampp\htdocs\gos\page\appuntamenti_privati.phpon line 47

<?php
require_once('function/date_day.php');

$where='';

// Creo una variabile dove imposto il numero di record
// da mostrare in ogni pagina
$x_pag = 5;

// Recupero il numero di pagina corrente.
// Generalmente si utilizza una querystring
$pag = isset($_GET['pag']) ? $_GET['pag'] : 1;

// Controllo se $pag è valorizzato e se è numerico
// ...in caso contrario gli assegno valore 1
if (!$pag || !is_numeric($pag)) $pag = 1;

$sq1 = "SELECT id_app FROM appuntamenti WHERE stato_pren = 'ATTESA ACCETTAZIONE'";
$rs1 = $mysqli->query($sq1);
$all_rows = mysqli_num_rows($rs1);

// Tramite una semplice operazione matematica definisco il numero totale di pagine
$all_pages = ceil($all_rows / $x_pag);

// Calcolo da quale record iniziare
$first = ($pag - 1) * $x_pag;

$tipo = trim(strip_tags(stripslashes($_GET['tipo'])));

if ($tipo == "tutti") {
    $where = "WHERE data = '$oggi'";

}elseif ($tipo == "accettazione") {
    $where = "WHERE stato_pren = 'ATTESA ACCETTAZIONE' AND tipo_pren = 'CLIENTE PRIVATO'";

}elseif ($tipo == "lavorazione") {
    $where = "WHERE stato_pren = 'LAVORAZIONE' AND tipo_pren = 'CLIENTE PRIVATO'";

}elseif ($tipo == "terminato") {
    $where = "WHERE stato_pren = 'TERMINATO' AND tipo_pren = 'CLIENTE PRIVATO'";
}

$sq2 = "SELECT * FROM appuntamenti $where ORDER BY data ASC LIMIT $first, $x_pag";
$rs2 = $mysqli->query($sq2);

if ($rs2 != 0){
for($x = 0; $x < $rs2; $x++){

echo "
";

echo "
";
echo "
";
echo "
";
echo "Data	";
echo "Ora	";
echo "Cliente	";
echo "Telefono	";
echo "Veicolo	";
echo "Tipo Pren.	";
echo "Tipo Lav.	";
echo "Stato Pren.	";
echo "Note	";
echo "Aggiorna	";
echo "Stampa	";
echo "
";

while ($row = $rs2->fetch_assoc()) {
$id_app = mysqli_real_escape_string($mysqli, $row['id_app']);
$cliente = mysqli_real_escape_string($mysqli, $row['cliente']);
$data = mysqli_real_escape_string($mysqli, $row['data']);
$ora = mysqli_real_escape_string($mysqli, $row['ora']);
$gestore = mysqli_real_escape_string($mysqli, $row['gestore']);
$veicolo = mysqli_real_escape_string($mysqli, $row['veicolo']);
$stato_pren = mysqli_real_escape_string($mysqli, $row['stato_pren']);
$tipo_pren = mysqli_real_escape_string($mysqli, $row['tipo_pren']);
$tipo_lavorazione = mysqli_real_escape_string($mysqli, $row['tipo_lavorazione']);
$telefono = mysqli_real_escape_string($mysqli, $row['telefono']);
$note = mysqli_real_escape_string($mysqli, $row['note']);

/* FILTRI e CONVERSIONI SULLE VARIABILI POST */
$cliente = trim(strip_tags(stripslashes($cliente)));
$veicolo = trim(strip_tags(stripslashes($veicolo)));
$note = trim(strip_tags(stripslashes($note)));
$data = strtotime($data);
$data = date('d/m/Y', $data);
/* FINE FILTRI e CONVERSIONI SULLE VARIABILI POST */

if ($stato_pren == 'ATTESA ACCETTAZIONE') { $classe = 'table-danger-rs'; }
if ($stato_pren == 'LAVORAZIONE') { $classe = 'table-warning-rs'; }
if ($stato_pren == 'TERMINATO') { $classe = 'table-success-rs'; }

if ($tipo_lavorazione == 'MECCANICA') { $lav = 'table-warning-mec'; }
if ($tipo_lavorazione == 'CARROZZERIA') { $lav = 'table-warning-car'; }
if ($tipo_lavorazione == 'PNEUMATICI') { $lav = 'table-warning-pneus'; }
?>

<?php echo data_it($data); ?>
<?php echo $ora; ?>
<?php echo $cliente; ?>
<?php echo $telefono; ?>
<?php echo $veicolo; ?>
<?php echo $tipo_pren; ?>
<td class='<?= $lav; ?>'><? echo $tipo_lavorazione; ?>
<td class='<?= $classe; ?>'><? echo $stato_pren; ?>
<?php echo $note; ?>
<?php echo ""; ?>
<?php echo ""; ?>

<?php
}
echo "
";
echo "
";

echo "
";
if ($all_pages > 1){
  if ($pag > 1){
    echo "";
    echo "<< Precedente   ";
  }
  if ($all_pages > $pag){
    echo "";
    echo "Successiva >>";
  }
 }
echo "
";
}

}else{

echo "
";
echo "

Non ci sono appuntamenti in Accettazione.

";
echo "
";

}
?>```

答:
The offending lines 46 and 47 are

```<code>if ($rs2 != 0){
for($x = 0; $x < $rs2; $x++){
</code>```

where you are treating the result set as an integer

According to
http://php.net/manual/en/mysqli.query.php

your $rs2 object is a mysqli_result object. So you can find out the number of rows in the result, e.g.

```<code>$sq2 = "SELECT * FROM appuntamenti $where ORDER BY data ASC LIMIT $first, $x_pag";
$rs2 = $mysqli->query($sq2);

if ($rs2->num_rows > 0){
</code>```

But it's not clear why you then need the for loop with x as the

```<code>while ($row = $rs2->fetch_assoc())
</code>```

loop should loop over the rows in the results. See fetch_assoc

Body:
The offending lines 46 and 47 are

if ($rs2 != 0){
for($x = 0; $x < $rs2; $x++){

where you are treating the result set as an integer

According to
http://php.net/manual/en/mysqli.query.php

your $rs2 object is a mysqli_result object. So you can find out the number of rows in the result, e.g.

$sq2 = "SELECT * FROM appuntamenti $where ORDER BY data ASC LIMIT $first, $x_pag";
$rs2 = $mysqli->query($sq2);

if ($rs2->num_rows > 0){

But it's not clear why you then need the for loop with x as the

while ($row = $rs2->fetch_assoc())

loop should loop over the rows in the results. See fetch_assoc


问:
Mongodb text index - better scoring?
I have an index in MongoDB which covers name and email.
This works, and I can query it with:

```<code>const c = await Contact.
      find({ $text: { $search: search } }, { score: { $meta: "textScore" } })
.sort({ score: { $meta: "textScore" } })
.skip(skip)
.limit(20);
</code>```

But, the results are somewhat odd, yet logical.

e.g.

if I search for "Roger Johan"
It will start listing both people called Roger and Johan, which is logical.
but, it would have been less odd if it ranked "Roger Johansson" highest as that is a match on both Roger and Johan%

Is there any way to tune this?

I know I can regex match on partial, but that instead fails on things like:
data: Roger T. Johansson
query: Roger Johansson

Is there any fancy trick to combine parts of these two options?

答:
I haven't tried it myself, but maybe you need to do the search as a phrase: https://docs.mongodb.com/manual/reference/operator/query/text/#phrases

If not I think it will split your search term and then search.

Title: Mongodb text index - better scoring?

Body:
I have an index in MongoDB which covers name and email.
This works, and I can query it with:

const c = await Contact.
      find({ $text: { $search: search } }, { score: { $meta: "textScore" } })
.sort({ score: { $meta: "textScore" } })
.skip(skip)
.limit(20);

But, the results are somewhat odd, yet logical.

e.g.

if I search for "Roger Johan"
It will start listing both people called Roger and Johan, which is logical.
but, it would have been less odd if it ranked "Roger Johansson" highest as that is a match on both Roger and Johan%

Is there any way to tune this?

I know I can regex match on partial, but that instead fails on things like:
data: Roger T. Johansson
query: Roger Johansson

Is there any fancy trick to combine parts of these two options?


问:
Cannot get PyCharm Django project to read and display Django Templating Language Tags
I have been pulling my hair out over this, am new to using Django for web development and I have never setup a Django project in PyCharm. It is Django v2.0 and PyCharm 2017.3.

I have a basic project which consists of two apps, for examples sake lets call one Test and one TestProj. Test is the core of the site where settings.py is located, and TestProj is where I wish to add templates.

The Test urls.py points to the TestProj urls.py, which when requested, serves a html file to the root url of the site. This content is located in a folder again called Test which is located in a templates folder in TestProj

Essentially the directory structure is as follows:

```<code>Test  >
    settings.py etc
TestProj  >
    templates  >
        Test  >
            index.html
            header.html
    other python files are here!
</code>```

The index.html file is served fine but the problem occurs when I try to use Django templating to link in another html file. This is index.html:

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Test</title>
    </head>
   <body>
       <div>
           {% block content %}
           {% endblock %}
       </div>
   </body>
</html>
</code>```

And this is header html which is located in the same templates directory:

```<code>{% extends 'Test/index.html' %}

{% block content %}
    <p>Hello World</p>
{% endblock %}
</code>```

index.html is served as normal but for some reason no matter what I do the
Django {% block content %} in index.html doesnt seem to evaluate. Thus, my index.html, when served in the browser with Pycharm, has an empty body instead of Hello World.

The Test folder within templates is marked as a template folder in PyCharm so I don't see why this is the case. I also have Django selected as the template language in PyCharm settings and I have tried reinstalling PyCharm. The settings.py templates is also correctly configured to my knowledge as below:

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'TestProj/templates/Test')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
</code>```

Any help would be very much appreciated!

答:
make sure that you set  "Project Interpreter" correctly:
https://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html</p>

Body:
I have been pulling my hair out over this, am new to using Django for web development and I have never setup a Django project in PyCharm. It is Django v2.0 and PyCharm 2017.3.

I have a basic project which consists of two apps, for examples sake lets call one Test and one TestProj. Test is the core of the site where settings.py is located, and TestProj is where I wish to add templates.

The Test urls.py points to the TestProj urls.py, which when requested, serves a html file to the root url of the site. This content is located in a folder again called Test which is located in a templates folder in TestProj

Essentially the directory structure is as follows:

Test  >
    settings.py etc
TestProj  >
    templates  >
        Test  >
            index.html
            header.html
    other python files are here!

The index.html file is served fine but the problem occurs when I try to use Django templating to link in another html file. This is index.html:

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Test</title>

           {% block content %}
           {% endblock %}

And this is header html which is located in the same templates directory:

{% extends 'Test/index.html' %}

{% block content %}

Hello World

{% endblock %}

index.html is served as normal but for some reason no matter what I do the
Django {% block content %} in index.html doesnt seem to evaluate. Thus, my index.html, when served in the browser with Pycharm, has an empty body instead of Hello World.

The Test folder within templates is marked as a template folder in PyCharm so I don't see why this is the case. I also have Django selected as the template language in PyCharm settings and I have tried reinstalling PyCharm. The settings.py templates is also correctly configured to my knowledge as below:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'TestProj/templates/Test')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Any help would be very much appreciated!


问:
How can I asynchronously handle SSE events?
Optimally, I would like to be able to do something like this

```<code>Request request = new Request("http://someendpoint")
request.onMessage(payload -> System.out.println(payload))
request.onError(error -> error.printStackTrace())
request.onClose(() -> System.out.println("closed"))
request.onConnect(isReconnect -> System.out.println("connected"))
</code>```

Obviously doesn't have to be exactly like that, just thought it would help explain what I was trying to do.

I have seen that there is some sort of support for this in Jersey. I would like to find an alternative but will use that if nothing else is available.

答:
SSEs are available in JavaEE 8 through JAX-RS 2.1 in the javax.ws.rs.sse package. Unlike requests and responses which can be synchronous or asynchronous, SSEs are asynchronous by nature.

For a demonstration of SSEs have a look at this video by David Delabassee. Your code (which is client-side only) would looks something like this:

```<code>Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://someendpoint");

SseEventSource eventSource = SseEventSource.target(target)
                                           .reconnectingEvery(5, TimeUnit.SECONDS)
                                           .build();
eventSource.register(payload -> System.out.println(payload),   // Consumer<InboundSseEvent>
                     error -> error.printStackTrace(),         // Consumer<Throwable>
                     () -> System.out.println("no more events"));
eventSource.open();
// and eventually
eventSource.close();
</code>```

There are no built-in handlers for (re)connection and closing, but you could customize something to have the same effect.

JAX-RS 2.1 is implemented in (at least):

Jersey 2.26, which is included in Glassfish 5 and Payara 5 alpha/snapshot/pre-release.

RESTEasy  4.0.0.Beta1 (released less than a month ago) and is reported to work on Wildfly 10 and above, though I think only Wildfly 12 will implement the full JavaEE 8 (announcements change with time...).

Body:
Optimally, I would like to be able to do something like this

Request request = new Request("http://someendpoint")
request.onMessage(payload -> System.out.println(payload))
request.onError(error -> error.printStackTrace())
request.onClose(() -> System.out.println("closed"))
request.onConnect(isReconnect -> System.out.println("connected"))

Obviously doesn't have to be exactly like that, just thought it would help explain what I was trying to do.

I have seen that there is some sort of support for this in Jersey. I would like to find an alternative but will use that if nothing else is available.

Body:
SSEs are available in JavaEE 8 through JAX-RS 2.1 in the javax.ws.rs.sse package. Unlike requests and responses which can be synchronous or asynchronous, SSEs are asynchronous by nature.

For a demonstration of SSEs have a look at this video by David Delabassee. Your code (which is client-side only) would looks something like this:

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://someendpoint");

SseEventSource eventSource = SseEventSource.target(target)
                                           .reconnectingEvery(5, TimeUnit.SECONDS)
                                           .build();
eventSource.register(payload -> System.out.println(payload),   // Consumer<InboundSseEvent>
                     error -> error.printStackTrace(),         // Consumer<Throwable>
                     () -> System.out.println("no more events"));
eventSource.open();
// and eventually
eventSource.close();

There are no built-in handlers for (re)connection and closing, but you could customize something to have the same effect.

JAX-RS 2.1 is implemented in (at least):

Jersey 2.26, which is included in Glassfish 5 and Payara 5 alpha/snapshot/pre-release.

RESTEasy  4.0.0.Beta1 (released less than a month ago) and is reported to work on Wildfly 10 and above, though I think only Wildfly 12 will implement the full JavaEE 8 (announcements change with time...).


问:
Call function in jQuery
I have created a function inside a .click

```<code>$('#BeforeFunction').click(function(){

//something is entered here then the function below is called
Hello();

});

$('#HitMe').click(function(){
//something here.....
function Hello(){
alert ('Hit button is pressed');
}

});
</code>```

But the function when called causes an error, the message being Hello is not defined.

What is wrong exactly?

答: The curly braces define a scope and limit the definition of Hello function to that scope of "HitMe" function. Define your Hello function outside of the "Hitme" function, preferably before calling it. And you should be fine. </p>

Title: Call function in jQuery

Body:
I have created a function inside a .click

$('#BeforeFunction').click(function(){

//something is entered here then the function below is called
Hello();

});

$('#HitMe').click(function(){
//something here.....
function Hello(){
alert ('Hit button is pressed');
}

});

But the function when called causes an error, the message being Hello is not defined.

What is wrong exactly?


问:
Bad Escape String in variable returning image src in JSON

I am using Google Tag Manager to implement the 'article' JSON markup and return a couple of variables for changing elements on specific pages. One of the elements I am trying to return is an image src.

Right now I am using a DOM element to return this that is using a CSS selector. The HTML element that it is targeting is:

```<code> <div class="field-item even">
<img src="THISISTHEIMAGEURL.jpg">
</div>
</code>```

and I am targeting in GTM by collecting: div.field-item.even > img with an attribute name of src
This is a screenshot of how I'm targeting in GTM

Right now when I test this in preview mode the URL of the image is appearing exactly how it is supposed to and everything looks great.

When I check this using the Google Structured data testing tool I am returning an error that says "Bad Escape String" and a URL for the image that has slashes going both ways like http://\www.mysite.com/\image1.jpg/\

I have been doing some research, and it seems I may need to use a custom javascript variable or something in order to make this work.

I was trying to use something like this:

```<code> function() {
var src = document.querySelector(‘.fielditem.even > img').src;
}
</code>```

but then I get an error in GTM telling me I need a return value. Unfortanately, my javascript skills are pretty poor and after some more research I tried something like this:

```<code> var picture = document.getElementsByClassName(".fielditem.even");
var src = picture[0].firstElementChild.src;
</code>```

but I still am getting the same error, that I need a return value. Any help is greatly appreciated.

Thanks!

答:
Just return a value from your function:</p>

```<code>function imgSRC() {
  return document.querySelector('.field-item.even > img').src;
}
</code>```

Body:
I am using Google Tag Manager to implement the 'article' JSON markup and return a couple of variables for changing elements on specific pages. One of the elements I am trying to return is an image src.

Right now I am using a DOM element to return this that is using a CSS selector. The HTML element that it is targeting is:

and I am targeting in GTM by collecting: div.field-item.even > img with an attribute name of src
This is a screenshot of how I'm targeting in GTM

Right now when I test this in preview mode the URL of the image is appearing exactly how it is supposed to and everything looks great.

When I check this using the Google Structured data testing tool I am returning an error that says "Bad Escape String" and a URL for the image that has slashes going both ways like http://\www.mysite.com/\image1.jpg/\

I have been doing some research, and it seems I may need to use a custom javascript variable or something in order to make this work.

I was trying to use something like this:

 function() {
var src = document.querySelector(‘.fielditem.even > img').src;
}

but then I get an error in GTM telling me I need a return value. Unfortanately, my javascript skills are pretty poor and after some more research I tried something like this:

 var picture = document.getElementsByClassName(".fielditem.even");
var src = picture[0].firstElementChild.src;

but I still am getting the same error, that I need a return value. Any help is greatly appreciated.

Thanks!

Body:
Just return a value from your function:

function imgSRC() {
  return document.querySelector('.field-item.even > img').src;
}


问:
Preview amp generated pages to my browser
My web app generate an amp-valid page and via https://validator.ampproject.org/# I can check that the output is amp- valid.

But for me is not enough I want somehow to render visualy the <amp-*></amp-*> elements. I mean if I want to chance some css for these elements how I can do it without deploying my application all over the time?

答:
Some elements may not be rendered because they need the correct amp extention in order to load. Therefore if some elements do not get rendered just load the correct amp.js extention in order to get rendered into your browser.

Furthermore make sure that the AMP javascript and their plugis get loaded firtst in order to be able to correcly get rendered.


问:
Java read Properties file that is in same package as the class
I'm stuck in this for almost an hour so please help me.

I'm using netbeans and under my Sources Packages I have a package called com.cmsv1.properties. Inside this package I have 1 java class and .properties file. Called config.java and config.properties.

I've tried so many solutions I got from the internet but nothing works. I always get nullPointerException.

The following are the solutions i've tried:

```<code>try
          {
              Properties prop = new Properties();
              InputStream is = config.class.getResourceAsStream("config.properties");
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }
</code>```

another is:

```<code>try
          {
              Properties prop = new Properties();
              InputStream input = config.class.getClassLoader().getResourceAsStream("config.properties");
              prop.load(input);
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }
</code>```

And a couple more solutions. Please tell me how can I do this. Remember both of my java class and .properties file are in the same package. Thanks in advance.

答:
```<code>public Properties getPropertiesFromFile(String propertieFileName) throws IOException
    {
        try (InputStream propertyFile = this.getClass().getClassLoader().getResourceAsStream(propertieFileName)
        {

            if (propertyFile == null)
            {
                //logger not found
            }
            Properties propeties = new Properties();
            propeties.load(propertyFile);
            return propeties;
        }
    }
</code>```

Body:
I'm stuck in this for almost an hour so please help me.

I'm using netbeans and under my Sources Packages I have a package called com.cmsv1.properties. Inside this package I have 1 java class and .properties file. Called config.java and config.properties.

I've tried so many solutions I got from the internet but nothing works. I always get nullPointerException.

The following are the solutions i've tried:

try
          {
              Properties prop = new Properties();
              InputStream is = config.class.getResourceAsStream("config.properties");
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }

another is:

try
          {
              Properties prop = new Properties();
              InputStream input = config.class.getClassLoader().getResourceAsStream("config.properties");
              prop.load(input);
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }

And a couple more solutions. Please tell me how can I do this. Remember both of my java class and .properties file are in the same package. Thanks in advance.


问:
Rails: Catch a request in a scope when the request doesn't match anything in the scope
Let's take the following router  :

```<code>Rails.application.routes.draw do
  scope ":locale", locale: /en|nl/ do
    get "/:slug", to: "pages#prefixed_action", constraints: { slug: /.*/ }
  end

  root to: "pages#simple_action"
  get "/:slug", to: "pages#simple_action", constraints: { slug: /.*/ }
end
</code>```

If the request specifies a locale, the scope catches it and forwards it to pages#prefixed_action. If not the request is forwarded topages#simple_action.

My issue is that if I enter localhost:3000/en in the browser, it won't be catched by the scope. How can I arrange that ?

Edit1: I'd like the request to be routed to "pages#prefixed_action"

Edit2: added a root declaration in the code sample

答:
Maybe simply like this:

```<code>get '/:locale', to: "pages#prefixed_action", constraints: { locale: /(en|nl)/ }
get '/:locale', to: "pages#simple_action", constraints: { locale: /.*/ }
</code>```

If your goal is to send to pages#prefixed_action with paths /en and /nl and all other to pages#simple_action. If so, put

```<code>get '/:locale', to: "pages#simple_action", constraints: { locale: /.*/ }
</code>```

As a last route in your routes

Body:
Let's take the following router  :

Rails.application.routes.draw do
  scope ":locale", locale: /en|nl/ do
    get "/:slug", to: "pages#prefixed_action", constraints: { slug: /.*/ }
  end

  root to: "pages#simple_action"
  get "/:slug", to: "pages#simple_action", constraints: { slug: /.*/ }
end

If the request specifies a locale, the scope catches it and forwards it to pages#prefixed_action. If not the request is forwarded topages#simple_action.

My issue is that if I enter localhost:3000/en in the browser, it won't be catched by the scope. How can I arrange that ?

Edit1: I'd like the request to be routed to "pages#prefixed_action"

Edit2: added a root declaration in the code sample

Body:
Maybe simply like this:

get '/:locale', to: "pages#prefixed_action", constraints: { locale: /(en|nl)/ }
get '/:locale', to: "pages#simple_action", constraints: { locale: /.*/ }

If your goal is to send to pages#prefixed_action with paths /en and /nl and all other to pages#simple_action. If so, put

get '/:locale', to: "pages#simple_action", constraints: { locale: /.*/ }

As a last route in your routes


问:
C++ WinAPI screenshot of a window in the background
I want to take screenshots of a window which has no focus. My function works for some windows but not for all and I don't know why. I tried it to capture the window of Bluestacks App Player and it works perfectly. But for Nox App Player and some other games it doesn't work at all. I just get a black image with the size of the window.

Here is the code so far:

void screenshot_window(HWND handle) {
    RECT client_rect = { 0 };
    GetClientRect(handle, &client_rect);
    int width = client_rect.right - client_rect.left;
    int height = client_rect.bottom - client_rect.top;

    HDC hdcScreen = GetDC(handle);
    HDC hdc = CreateCompatibleDC(hdcScreen);
    HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen, width, height);
    SelectObject(hdc, hbmp);

    BitBlt(hdc, 0, 0, width, height, hdcScreen, 0, 0, SRCCOPY);

    BITMAPINFO bmp_info = { 0 };
    bmp_info.bmiHeader.biSize = sizeof(bmp_info.bmiHeader);
    bmp_info.bmiHeader.biWidth = width;
    bmp_info.bmiHeader.biHeight = height;
    bmp_info.bmiHeader.biPlanes = 1;
    bmp_info.bmiHeader.biBitCount = 24;
    bmp_info.bmiHeader.biCompression = BI_RGB;

    int bmp_padding = (width * 3) % 4;
    if (bmp_padding != 0) bmp_padding = 4 - bmp_padding;

    BYTE *bmp_pixels = new BYTE[(width * 3 + bmp_padding) * height];;
    GetDIBits(hdc, hbmp, 0, height, bmp_pixels, &bmp_info, DIB_RGB_COLORS);

    BITMAPFILEHEADER bmfHeader;
    HANDLE bmp_file_handle = CreateFile("TestFile.bmp", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    // Add the size of the headers to the size of the bitmap to get the total file size
    DWORD dwSizeofDIB = (width * 3 + bmp_padding) * height + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

    //Offset to where the actual bitmap bits start.
    bmfHeader.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER);

    //Size of the file
    bmfHeader.bfSize = dwSizeofDIB;

    //bfType must always be BM for Bitmaps
    bmfHeader.bfType = 0x4D42; //BM

    DWORD dwBytesWritten = 0;
    WriteFile(bmp_file_handle, (LPSTR)&bmfHeader, sizeof(BITMAPFILEHEADER), &dwBytesWritten, NULL);
    WriteFile(bmp_file_handle, (LPSTR)&bmp_info.bmiHeader, sizeof(BITMAPINFOHEADER), &dwBytesWritten, NULL);
    WriteFile(bmp_file_handle, (LPSTR)bmp_pixels, (width * 3 + bmp_padding) * height, &dwBytesWritten, NULL);

    //Close the handle for the file that was created
    CloseHandle(bmp_file_handle);

    DeleteDC(hdc);
    DeleteObject(hbmp);
    ReleaseDC(NULL, hdcScreen);
    delete[] bmp_pixels;
}
```

答:
This can happen with many applications where the target window is simply a container and is not responsible for paint messages. Standard win32 applications like notepad don't behave as such. But you may run in to this problem with many browsers for example.

You can always take screenshot of desktop window. You can get the screen coordinate of target window, then bitblt that section of target window. Make the following changes to your code:

```<code>//GetClientRect(handle, &client_rect);
GetWindowRect(handle, &client_rect);

//HDC hdcScreen = GetDC(handle);
HDC hdcScreen = GetDC(HWND_DESKTOP);

//BitBlt(hdc, 0, 0, width, height, hdcScreen, 0, 0, SRCCOPY);
BitBlt(hdc, 0, 0, width, height, hdcScreen, client_rect.left, client_rect.top, SRCCOPY);

//ReleaseDC(NULL, hdcScreen);
ReleaseDC(HWND_DESKTOP, hdcScreen);
</code>```

The target window must be top-most visible window on the screen before taking screen shot. For example you can call screenshot_window in this order:

```<code>HWND hwnd = FindWindow(0, L"Calculator");
SetForegroundWindow(hwnd);
Sleep(1000);
screenshot_window(hwnd);
</code>```

Alternatively, you can use Dwm Thumbnail APIs to paint the target window in your own window. But again, you cannot use GetDC(my_hWnd) to access the bitmap from "Dwm Thumbnail" on your window. Again you would have to take screen shot of desktop window using GetDC(HWND_DESKTOP). This time make sure your own window is the top window.

Application must be DPI aware otherwise screen coordinates will not match.

Also there is a resource leak in the original code. GetDC should be cleaned up with ReleaseDC using the same handle, not NULL

```<code>HDC hdcScreen = GetDC(handle);
...
//ReleaseDC(NULL, hdcScreen);
ReleaseDC(handle, hdcScreen);
</code>```

Body:
This can happen with many applications where the target window is simply a container and is not responsible for paint messages. Standard win32 applications like notepad don't behave as such. But you may run in to this problem with many browsers for example.

You can always take screenshot of desktop window. You can get the screen coordinate of target window, then bitblt that section of target window. Make the following changes to your code:

//GetClientRect(handle, &client_rect);
GetWindowRect(handle, &client_rect);

//HDC hdcScreen = GetDC(handle);
HDC hdcScreen = GetDC(HWND_DESKTOP);

//BitBlt(hdc, 0, 0, width, height, hdcScreen, 0, 0, SRCCOPY);
BitBlt(hdc, 0, 0, width, height, hdcScreen, client_rect.left, client_rect.top, SRCCOPY);

//ReleaseDC(NULL, hdcScreen);
ReleaseDC(HWND_DESKTOP, hdcScreen);

The target window must be top-most visible window on the screen before taking screen shot. For example you can call screenshot_window in this order:

HWND hwnd = FindWindow(0, L"Calculator");
SetForegroundWindow(hwnd);
Sleep(1000);
screenshot_window(hwnd);

Alternatively, you can use Dwm Thumbnail APIs to paint the target window in your own window. But again, you cannot use GetDC(my_hWnd) to access the bitmap from "Dwm Thumbnail" on your window. Again you would have to take screen shot of desktop window using GetDC(HWND_DESKTOP). This time make sure your own window is the top window.

Application must be DPI aware otherwise screen coordinates will not match.

Also there is a resource leak in the original code. GetDC should be cleaned up with ReleaseDC using the same handle, not NULL

HDC hdcScreen = GetDC(handle);
...
//ReleaseDC(NULL, hdcScreen);
ReleaseDC(handle, hdcScreen);


问:
Adobe BlazeDS 4 artifacts maven repository?
Does anybody know if Adobe has a maven repository to download the latest BlazeDS artifacts from?
I only can find the "older" versions of BlazeDS in the central mvn repository.

The other option is to deploy the downloaded BlazeDS jar files from the Adobe website into my local repository but it would be nice when Adobe provides the artifacts via a maven repository.

答:
Thanks Cornel. I added the following snippet to my pom.</p>

```<code><repositories>
   <repository>
      <id>spring-maven-external</id>
      <name>Springframework Maven External Repository</name>
      <url>http://maven.springframework.org/external</url>
   </repository>
</repositories>
</code>```

Body:
Thanks Cornel. I added the following snippet to my pom.

<repositories>
   <repository>
      <id>spring-maven-external</id>
      <name>Springframework Maven External Repository</name>
      <url>http://maven.springframework.org/external</url>
   </repository>
</repositories>