问:
How to make universal GET method for Realm objects?
I my viewControllers I often use realm.objects(className.self) to download data from className table. I wanted to simplify that so I created another swift file with get method.

It looks like this:

```<code>class Realm_manager {
    private init() {}
    static let shared = Realm_manager()

    let realm = try! Realm()
    func getObjects() -> [customType]{
            let result = realm.objects(customType.self)
            return Array(result)
        }
}
</code>```

But that getObjects method works only for customType objects.
With this in viewController it works fine:

```<code>    let result = Realm_manager.shared.getObjects()
    for item in result {
            myArray.append(item)
        }
    //this works because myArray is of type customType.
</code>```

I want to make getObjects universal method which can accept any class.

答:
Use Generics

```<code>class RealmManager {
    private init() {}
    static let shared = RealmManager()

    let realm = try! Realm()

    func getObjects<T: Object>() -> [T] {
        let result = realm.objects(T.self)
        return Array(result)
    }
}
</code>```

usage:

```<code>let manager = RealmManager.shared
let dogs: [Dogs] = manager.getObjects()
</code>```

Note: In Swift we generally do not use underscores in Type names, they are normally upper camel cased. Realm_manager -> RealmManager

Body:
I my viewControllers I often use realm.objects(className.self) to download data from className table. I wanted to simplify that so I created another swift file with get method.

It looks like this:

class Realm_manager {
    private init() {}
    static let shared = Realm_manager()

    let realm = try! Realm()
    func getObjects() -> [customType]{
            let result = realm.objects(customType.self)
            return Array(result)
        }
}

But that getObjects method works only for customType objects.
With this in viewController it works fine:

    let result = Realm_manager.shared.getObjects()
    for item in result {
            myArray.append(item)
        }
    //this works because myArray is of type customType.

I want to make getObjects universal method which can accept any class.

Body:
Use Generics

class RealmManager {
    private init() {}
    static let shared = RealmManager()

    let realm = try! Realm()

    func getObjects<T: Object>() -> [T] {
        let result = realm.objects(T.self)
        return Array(result)
    }
}

usage:

let manager = RealmManager.shared
let dogs: [Dogs] = manager.getObjects()

Note: In Swift we generally do not use underscores in Type names, they are normally upper camel cased. Realm_manager -> RealmManager


来源: stackexchange

问:
How to segregate higher numbers from lower numbers
```<code>import random
num = input('enter a number:')
n1=random.randrange(0,50)
n2=random.randrange(0,50)
n3=random.randrange(0,50)
n4=random.randrange(0,50)
n5=random.randrange(0,50)
</code>```

What i want to do is to compare those random numbers to my input number if the random number is higher it will be displayed all higher numbers than the user input also, it will display the smaller numbers compare to the user input at the same time
For example i entered
30
And the random numbers are 5, 45, 18, 22, 50
Output:
Higher number than 30 are: 45, 50
Lower number than 30 are: 5, 18, 22

I tried using if else but it wont display anything if the series of numbers are mixed like the example.

答:
An elegant way is to use Numpy module.

Instead of creating individual values, create a Numpy (1-d) array:

```<code>import numpy as np
arr = np.random.randint(0, 50, 5)
</code>```

(5 values between 0 and 50). Assume that the result is:

```<code>array([ 0,  1, 23, 42, 47])
</code>```

Then, assuming that the threshold value (num) == 30, to get values
<= or > from this value, run:

```<code>arr[arr <= num]
arr[arr > num]
</code>```

The result is:

```<code>array([ 0,  1, 23])
array([42, 47])
</code>```

If you want plain Python lists instead of Numpy arrays, run:

```<code>arr[arr <= num].tolist()
arr[arr > num].tolist()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
import random
num = input('enter a number:')
n1=random.randrange(0,50)
n2=random.randrange(0,50)
n3=random.randrange(0,50)
n4=random.randrange(0,50)
n5=random.randrange(0,50)

What i want to do is to compare those random numbers to my input number if the random number is higher it will be displayed all higher numbers than the user input also, it will display the smaller numbers compare to the user input at the same time
For example i entered
30
And the random numbers are 5, 45, 18, 22, 50
Output:
Higher number than 30 are: 45, 50
Lower number than 30 are: 5, 18, 22

I tried using if else but it wont display anything if the series of numbers are mixed like the example.

Body:
An elegant way is to use Numpy module.

Instead of creating individual values, create a Numpy (1-d) array:

import numpy as np
arr = np.random.randint(0, 50, 5)

(5 values between 0 and 50). Assume that the result is:

array([ 0,  1, 23, 42, 47])

Then, assuming that the threshold value (num) == 30, to get values
<= or > from this value, run:

arr[arr <= num]
arr[arr > num]

The result is:

array([ 0,  1, 23])
array([42, 47])

If you want plain Python lists instead of Numpy arrays, run:

arr[arr <= num].tolist()
arr[arr > num].tolist()


问:
Spring Controller - HashMap Return
I have a very basic REST controller...

```<code>@RestController
@CrossOrigin(origins = "*")
@RequestMapping(value = "/signKey", produces = "application/json")
public class SignKeyController {

@Autowired
private SignKeyService signKeyService;

@GetMapping(value = "/generate")
public ResponseEntity<?> generateSignKey() {
    String signKeyToken = signKeyService.generateNewToken();
    Map<String, String> data = new HashMap<>();
    data.put("signKey", signKeyToken);
    return new ResponseEntity<>(data, HttpStatus.OK);
}
</code>```

}

returns

```<code>{
"signKey": "_IjAY736MvwKZLtoJHrhNaD4MUL2r0Al"
}
</code>```

But because I want to return a json object to the frontend, instead of only a string I created an hashmap.
This code works fine but I feel like there should be a better way...

In this case I don't want to create models or anything. This is a simple return of a String. Do I really need to keep creating HashMaps in my controllers which only return some data that is not in any model?

Any help?

答:
If this helps ,
you can use JSONObject for putting values instead of a Model class.

Example -

```<code>import org.json.simple.JSONObject;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping(value = "/signKey", produces = "application/json")
public class SignKeyController {

@Autowired
private SignKeyService signKeyService;

@GetMapping(value = "/generate")
public ResponseEntity<?> generateSignKey() {
  String signKeyToken = signKeyService.generateNewToken();
  JSONObject data = new JSONObject();
  data.put("signKey", signKeyToken);
  return new ResponseEntity<>(data, HttpStatus.OK);
 }
}
</code>```

EDIT: Here is the Link for using JSONObject Vs HashMap

Title: Spring Controller - HashMap Return

Body:
I have a very basic REST controller...

@RestController
@CrossOrigin(origins = "*")
@RequestMapping(value = "/signKey", produces = "application/json")
public class SignKeyController {

@Autowired
private SignKeyService signKeyService;

@GetMapping(value = "/generate")
public ResponseEntity<?> generateSignKey() {
    String signKeyToken = signKeyService.generateNewToken();
    Map<String, String> data = new HashMap<>();
    data.put("signKey", signKeyToken);
    return new ResponseEntity<>(data, HttpStatus.OK);
}

}

returns

{
"signKey": "_IjAY736MvwKZLtoJHrhNaD4MUL2r0Al"
}

But because I want to return a json object to the frontend, instead of only a string I created an hashmap.
This code works fine but I feel like there should be a better way...

In this case I don't want to create models or anything. This is a simple return of a String. Do I really need to keep creating HashMaps in my controllers which only return some data that is not in any model?

Any help?

Body:
If this helps ,
you can use JSONObject for putting values instead of a Model class.

Example -

import org.json.simple.JSONObject;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping(value = "/signKey", produces = "application/json")
public class SignKeyController {

@Autowired
private SignKeyService signKeyService;

@GetMapping(value = "/generate")
public ResponseEntity<?> generateSignKey() {
  String signKeyToken = signKeyService.generateNewToken();
  JSONObject data = new JSONObject();
  data.put("signKey", signKeyToken);
  return new ResponseEntity<>(data, HttpStatus.OK);
 }
}

EDIT: Here is the Link for using JSONObject Vs HashMap


问:
Find item by key in Javascript
Quick rookie question please.

Suppose I have a javsacript object like so:

```<code>var meh=[["cars",27], ["bikes",85], ["skates",4]];
</code>```

To go through each data object here, I can do this:

```<code>$.each(meh, function(index,value){
    console.log(value) //returns ["cars",27] etc..
 });
</code>```

And considering I know the place of, say, cars, I can do this to access it:

```<code>console.log(meh[0][0]) //shows "Cars"
</code>```

and of course, if I want the value of cars, I need to do this:

```<code>console.log(meh[0][1]) //Shows 27
</code>```

Now, I have the string - Keys, like cars, bikes or skates

But I cant figure out this: How do I access their respective values?

meh["cars"] is returning undefined, since, as I understand, it cant find a description outside each object.

I can do meh[0]["cars"] but it defeats the point as the position of cars might change.

How do I access a value of something with their key please?

thanks.

答:
Use an object instead:

```<code>var meh = {
    "cars":   27,
    "bikes":  85,
    "skates": 4
};
</code>```

You can iterate over it using $.each():

```<code>$.each(meh, function (key, value) {
    // key == "cars" and value == 27, etc.
});
</code>```

Accessing values works like this:

```<code>meh.cars
</code>```

which is equivalent to this:

```<code>meh["cars"]
</code>```

Obviously, the second notation can be used with variables.

ContentLicense: CC BY-SA 3.0

Title: Find item by key in Javascript

Body:
Quick rookie question please.

Suppose I have a javsacript object like so:

var meh=[["cars",27], ["bikes",85], ["skates",4]];

To go through each data object here, I can do this:

$.each(meh, function(index,value){
    console.log(value) //returns ["cars",27] etc..
 });

And considering I know the place of, say, cars, I can do this to access it:

console.log(meh[0][0]) //shows "Cars"

and of course, if I want the value of cars, I need to do this:

console.log(meh[0][1]) //Shows 27

Now, I have the string - Keys, like cars, bikes or skates

But I cant figure out this: How do I access their respective values?

meh["cars"] is returning undefined, since, as I understand, it cant find a description outside each object.

I can do meh[0]["cars"] but it defeats the point as the position of cars might change.

How do I access a value of something with their key please?

thanks.

Body:
Use an object instead:

var meh = {
    "cars":   27,
    "bikes":  85,
    "skates": 4
};

You can iterate over it using $.each():

$.each(meh, function (key, value) {
    // key == "cars" and value == 27, etc.
});

Accessing values works like this:

meh.cars

which is equivalent to this:

meh["cars"]

Obviously, the second notation can be used with variables.


问:
Java: Converting a String to JSONArray, or Spliting an String the right way
I have an unusual qustion which looks as the following:

Question 1: How can i split a String the right way so that i get the json-File Entries separated from one another.

Or Question: How do i convert a String to JSONArray.

The JSON:

```<code>[
   {
   "id":"123483",
      "content":{
         "amount":"460",
         "price":"2.15",
         "name":"Post-it Block weiß",
         "weight":"0.3",
         "category":"Notizzettel"
 }
},
   {
      "id":"501993",
      "content":{
         "amount":"83",
         "price":"25.0",
         "name":"Trennstreifen 5x 100 bunt",
         "weight":"0.024",
         "category":"Register"

   }

}
]
</code>```

What i tried: // content succesfully encapsulates all the json content.

```<code>Path path = Paths.get("src/com/json/inventory.json");
String content = new String(Files.readAllBytes(path), Charset.defaultCharset());

JSONArray jsonArray = new JSONArray();
JSONObject jsnobject = new JSONObject(content);
jsonArray.put(jsnobject);
</code>```

The Errors with JSONArray: Errors

答:
Your content is an array, not a single object.

Try new JSONArray(content);

Or use a library like Jackson or Gson to read the file into a list of POJO classes

Also note that the src folder does not exist at runtime for your code. The standard layout for placing resource files looks like this

```<code>src
  main
    java
      Code.java
  resources
    file.json
</code>```

And you use ClassLoader to read the file

Body:
I have an unusual qustion which looks as the following:

Question 1: How can i split a String the right way so that i get the json-File Entries separated from one another.

Or Question: How do i convert a String to JSONArray.

The JSON:

[
   {
   "id":"123483",
      "content":{
         "amount":"460",
         "price":"2.15",
         "name":"Post-it Block weiß",
         "weight":"0.3",
         "category":"Notizzettel"
 }
},
   {
      "id":"501993",
      "content":{
         "amount":"83",
         "price":"25.0",
         "name":"Trennstreifen 5x 100 bunt",
         "weight":"0.024",
         "category":"Register"

   }

}
]

What i tried: // content succesfully encapsulates all the json content.

Path path = Paths.get("src/com/json/inventory.json");
String content = new String(Files.readAllBytes(path), Charset.defaultCharset());

JSONArray jsonArray = new JSONArray();
JSONObject jsnobject = new JSONObject(content);
jsonArray.put(jsnobject);

The Errors with JSONArray: Errors

Body:
Your content is an array, not a single object.

Try new JSONArray(content);

Or use a library like Jackson or Gson to read the file into a list of POJO classes

Also note that the src folder does not exist at runtime for your code. The standard layout for placing resource files looks like this

src
  main
    java
      Code.java
  resources
    file.json

And you use ClassLoader to read the file


问:
Modifying the SQL Eloquent uses per connection
I'm using the latest version of Laravel to connect to multiple data sources. One of those sources is an old Oracle database that contains a lot of white space thanks to some ancient software requiring string length. Despite this constraint, the fields have since been edited by new software with different requirements, and the columns are all varying length (and thus unknown).

On account of this, I need to edit the SQL that accesses it in order to wrap some pieces of the queries in trim()s. For instance,

$customer = Customer::whereRaw("RTRIM(\"ID\") = TO_CHAR($id)")->get();

I'd like to be able to merely call the find method:

$customer = Customer::find($id)

This is just one example. Pretty much all of the default functions are broken because the queries need some kind of trim prepended to them. I understand how I can affect the dynamic portion of the query, but I need to edit the column ahead of that. Sorry if this is a dumb question and I've just missed something in the documentation.

答: The easiest way to do this is to create a class that extends Eloquent, with the function for the query. Then modify all of your models to extend the new class instead of Eloquent. This way the models will have all the functionality of Eloquent as well as the functions you create.</p>


问:
How to handle pop up window dialog to download file automatically with firefox profile in python selenium on Linux (Ubuntu) system
I am trying to download the file automatically from system file download dialog by setting preference in firefox  profile in my python selenium code , but my code is not working.

Browser : Firefox 72.0
Selenium Version : 3.14
OS : linux Ubuntu
Filetype to download: *.enc (encrypted file type)
Path of firefox in linux : /usr/bin/firefox

Code :

```<code>profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.download.dir", "/home/user/Downloads/tests")
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/x-uuencoded,application/octet-stream")
self.driver = webdriver.Firefox(firefox_profile=profile)
</code>```

答:
The correct MIME type for .enc  is "text/x-uuencoded"
Updated as below in code and it's working :

```<code>profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/x-uuencoded")
</code>```

Body:
I am trying to download the file automatically from system file download dialog by setting preference in firefox  profile in my python selenium code , but my code is not working.

Browser : Firefox 72.0
Selenium Version : 3.14
OS : linux Ubuntu
Filetype to download: *.enc (encrypted file type)
Path of firefox in linux : /usr/bin/firefox

Code :

profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.download.dir", "/home/user/Downloads/tests")
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/x-uuencoded,application/octet-stream")
self.driver = webdriver.Firefox(firefox_profile=profile)

Body:
The correct MIME type for .enc  is "text/x-uuencoded"
Updated as below in code and it's working :

profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/x-uuencoded")


问:
PHP add missing key in loop
I have the following array.

```<code>    [rows] => Array
            (
                [0] => Array
                    (
                        [id] => 2704783858001796
                        [rowNumber] => 1
                        [expanded] => 1
                        [createdAt] => 2020-02-18T18:42:54Z
                        [modifiedAt] => 2020-02-18T22:07:36Z
                        [cells] => Array
                            (
                                    [0] => Array
                                        (
                                            [columnId] => 1676391784703876
                                            [value] => Approved
                                            [displayValue] => Approved
                                        )

                                    [1] => Array
                                        (
                                            [columnId] => 1225963934640004
                                            [value] => Submitted
                                            [displayValue] => Submitted
                                        )

                                    [2] => Array
                                        (
                                            [columnId] => 4979307467564932
                                            [value] => 2020-02-18
                                        )
                                    [3] => Array
                                        (
                                            [columnId] => 3203730339325828
</code>```

Where [value] and [displayValue] are not always shown.  When I loop through the array, I need to be able to insert a [value] as blank or 0.  I cannot have the loop skip over the key.

```<code>$j = count($dataID['rows']);
for ($i = 0; $i < $j; $i++) {
    array_push($dataRows, array_column($dataID['rows'][$i]['cells'], 'value'));
}
</code>```

答:
This code loops through every element of $dataID['row'] and within through every element of $row['cells'] to add the both keys if they dont exists:

```<code>foreach( $dataID['rows'] as &$row ) {
  foreach( $row['cells'] as &$cell ) {
    if( !array_key_exists( 'value', $cell ) )  {
      $cell['value'] = null;
    }
    if( !array_key_exists( 'displayValue', $cell ) )  {
      $cell['displayValue'] = null;
    }
  }
}
</code>```

So that this array (short version of yours):

```<code>Array
(
    [rows] => Array
        (
            [0] => Array
                (
                    [cells] => Array
                        (
                            [0] => Array
                                (
                                )

                            [1] => Array
                                (
                                )

                        )

                )

        )

)
</code>```

Becomes:

```<code>Array
(
    [rows] => Array
        (
            [0] => Array
                (
                    [cells] => Array
                        (
                            [0] => Array
                                (
                                    [value] =>
                                    [displayValue] =>
                                )

                            [1] => Array
                                (
                                    [value] =>
                                    [displayValue] =>
                                )

                        )

                )

        )

)
</code>```

Title: PHP add missing key in loop

Body:
I have the following array.

    [rows] => Array
            (
                [0] => Array
                    (
                        [id] => 2704783858001796
                        [rowNumber] => 1
                        [expanded] => 1
                        [createdAt] => 2020-02-18T18:42:54Z
                        [modifiedAt] => 2020-02-18T22:07:36Z
                        [cells] => Array
                            (
                                    [0] => Array
                                        (
                                            [columnId] => 1676391784703876
                                            [value] => Approved
                                            [displayValue] => Approved
                                        )

                                    [1] => Array
                                        (
                                            [columnId] => 1225963934640004
                                            [value] => Submitted
                                            [displayValue] => Submitted
                                        )

                                    [2] => Array
                                        (
                                            [columnId] => 4979307467564932
                                            [value] => 2020-02-18
                                        )
                                    [3] => Array
                                        (
                                            [columnId] => 3203730339325828

Where [value] and [displayValue] are not always shown.  When I loop through the array, I need to be able to insert a [value] as blank or 0.  I cannot have the loop skip over the key.

$j = count($dataID['rows']);
for ($i = 0; $i < $j; $i++) {
    array_push($dataRows, array_column($dataID['rows'][$i]['cells'], 'value'));
}

Body:
This code loops through every element of $dataID['row'] and within through every element of $row['cells'] to add the both keys if they dont exists:

foreach( $dataID['rows'] as &$row ) {
  foreach( $row['cells'] as &$cell ) {
    if( !array_key_exists( 'value', $cell ) )  {
      $cell['value'] = null;
    }
    if( !array_key_exists( 'displayValue', $cell ) )  {
      $cell['displayValue'] = null;
    }
  }
}

So that this array (short version of yours):

Array
(
    [rows] => Array
        (
            [0] => Array
                (
                    [cells] => Array
                        (
                            [0] => Array
                                (
                                )

                            [1] => Array
                                (
                                )

                        )

                )

        )

)

Becomes:

Array
(
    [rows] => Array
        (
            [0] => Array
                (
                    [cells] => Array
                        (
                            [0] => Array
                                (
                                    [value] =>
                                    [displayValue] =>
                                )

                            [1] => Array
                                (
                                    [value] =>
                                    [displayValue] =>
                                )

                        )

                )

        )

)


问:
Two different objects implement the same Interface in the same way - how to stay DRY
I have the interface:

IColored that guarantees the function getColor.

Now I have two objects:

 1. Ferrari

 2. RedApple

that both implement this interface/function in the same way.

(But cannot inherit from the same object - no multi-inheritance allowed).

How would you avoid code-duplication?

答:
If I understand you correctly, you can't - not entirely. But you can get close this way:

```<code>TYPE
  IColored = INTERFACE('GUID')
               FUNCTION getColor : TColor;
             END;

  TFerrari = CLASS(IColored)
               FUNCTION getColor: TColor;
             END;

  TRedApple = CLASS(IColored)
               FUNCTION getColor: TColor;
             END;

FUNCTION CommonFunction : TColor;
  BEGIN
    // Lots of code that ends with Result:=clRed
  END;

FUNCTION TFerrari.getColor : TColor;
  BEGIN
    Result:=CommonFunction
  END;

FUNCTION TRedApple.getColor : TColor;
  BEGIN
    Result:=CommonFunction
  END;
</code>```

ie. delegate the actual code into a function outside your object hierarchy, so that you can call it independently from your INTERFACE implementations.

That's the only way (besides serious low-level hacking) that I know off to implement what you are looking for (minimum code duplication).

Body:
If I understand you correctly, you can't - not entirely. But you can get close this way:

TYPE
  IColored = INTERFACE('GUID')
               FUNCTION getColor : TColor;
             END;

  TFerrari = CLASS(IColored)
               FUNCTION getColor: TColor;
             END;

  TRedApple = CLASS(IColored)
               FUNCTION getColor: TColor;
             END;

FUNCTION CommonFunction : TColor;
  BEGIN
    // Lots of code that ends with Result:=clRed
  END;

FUNCTION TFerrari.getColor : TColor;
  BEGIN
    Result:=CommonFunction
  END;

FUNCTION TRedApple.getColor : TColor;
  BEGIN
    Result:=CommonFunction
  END;

ie. delegate the actual code into a function outside your object hierarchy, so that you can call it independently from your INTERFACE implementations.

That's the only way (besides serious low-level hacking) that I know off to implement what you are looking for (minimum code duplication).


问:
How to find next birthday date from list of date from date now?
I'm struggling with this question? How can I find next birthday Date from my list of date ?
I got

```<code>const myArray = [
          {
            name: 'Joe Blow',
            date: 'Wednesday, November 25, 1992'
          },
          {
            name: 'Sam lol',
            date: 'Thursday, April 16, 1992'
          },
          {
            name: 'Eva lol',
            date: 'Thursday, February 26, 1991'
          }
        ];
        myArray.sort(function compare(a, b) {
          const dateA = new Date(a.date);
          const dateB = new Date(b.date);
          return dateA.getUTCDate() - dateB.getUTCDate();
        });
        // console.log(this.usersBirthdayDate);
        console.log(myArray);
</code>```

but I got Sam first cause he got 1992.. But I would like to display Thursday, February 26, 1991 first

Updated
my solution :

```<code>    sortByDateNoYear(adate, bdate) {
        let results;
        const lhdate = moment(adate.birthdayDate);
        const rhdate = moment(bdate.birthdayDate);
        results =
          lhdate.month() > rhdate.month()
            ? 1
            : lhdate.month() < rhdate.month()
            ? -1
            : 0;
        if (results === 0) {
          results =
            lhdate.date() > rhdate.date()
              ? 1
              : lhdate.date() < rhdate.date()
              ? -1
              : 0;
        }
        return results;
      }
 [array].sort(this.sortByDateNoYear);
</code>```

答:
You are currently sorting by the day of month by using .getUTCDate().

Instead, use .getTime() in your comparison.

From MDN

The getTime() method returns the number of milliseconds* since the Unix Epoch.

```<code>myArray.sort(function compare(a, b) {
  const dateA = new Date(a.date);
  const dateB = new Date(b.date);
  return dateA.getTime() - dateB.getTime();
});
</code>```

Also, if you're using Angular, you're safe to use arrow functions

```<code>myArray.sort((a, b) => {
  const dateA = new Date(a.date);
  const dateB = new Date(b.date);
  return dateA.getTime() - dateB.getTime();
});
</code>```

Body:
I'm struggling with this question? How can I find next birthday Date from my list of date ?
I got

const myArray = [
          {
            name: 'Joe Blow',
            date: 'Wednesday, November 25, 1992'
          },
          {
            name: 'Sam lol',
            date: 'Thursday, April 16, 1992'
          },
          {
            name: 'Eva lol',
            date: 'Thursday, February 26, 1991'
          }
        ];
        myArray.sort(function compare(a, b) {
          const dateA = new Date(a.date);
          const dateB = new Date(b.date);
          return dateA.getUTCDate() - dateB.getUTCDate();
        });
        // console.log(this.usersBirthdayDate);
        console.log(myArray);

but I got Sam first cause he got 1992.. But I would like to display Thursday, February 26, 1991 first

Updated
my solution :

    sortByDateNoYear(adate, bdate) {
        let results;
        const lhdate = moment(adate.birthdayDate);
        const rhdate = moment(bdate.birthdayDate);
        results =
          lhdate.month() > rhdate.month()
            ? 1
            : lhdate.month() < rhdate.month()
            ? -1
            : 0;
        if (results === 0) {
          results =
            lhdate.date() > rhdate.date()
              ? 1
              : lhdate.date() < rhdate.date()
              ? -1
              : 0;
        }
        return results;
      }
 [array].sort(this.sortByDateNoYear);

Body:
You are currently sorting by the day of month by using .getUTCDate().

Instead, use .getTime() in your comparison.

From MDN

The getTime() method returns the number of milliseconds* since the Unix Epoch.

myArray.sort(function compare(a, b) {
  const dateA = new Date(a.date);
  const dateB = new Date(b.date);
  return dateA.getTime() - dateB.getTime();
});

Also, if you're using Angular, you're safe to use arrow functions

myArray.sort((a, b) => {
  const dateA = new Date(a.date);
  const dateB = new Date(b.date);
  return dateA.getTime() - dateB.getTime();
});


问:
Generate Selenium Cucumber reports without overwriting the previous Maven test output result?
I need to save each report files separately in Report directory on each Run.How can we create Report files by concatenating current date & Time along with the file name .
I have used the below code in my TestRunnerTest.java to generate Extentreport in cucumber-selenium framework.

```<code>package testRunner;

import java.io.File;
import java.io.IOException;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.vimalselvam.cucumber.listener.Reporter;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(

    features = "src/test/resources"
            , glue= {"stepDefinition"}
    , plugin = { "com.vimalselvam.cucumber.listener.ExtentCucumberFormatter:target/cucumber-reports/report.html"},
            monochrome = true
    )
public class TestRunnerTest {
public static WebDriver driver;
private static TestRunnerTest sharedInstance = new TestRunnerTest();

 private TestRunnerTest() { }

 public static TestRunnerTest getInstance() {
        return sharedInstance;
    }

 @BeforeClass
    public static void before() {

           System.setProperty("webdriver.chrome.driver",
"E:\\ChromeDriverNew\\chromedriver.exe");
           driver=new ChromeDriver();

           driver.manage().window().maximize();
 driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    }
 @AfterClass
    public static void after() {

     Reporter.loadXMLConfig(new File("config/report.xml"));
     driver.quit();
    }
}
</code>```

And this is my POM dependency file.

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>selcuc</groupId>
  <artifactId>DemoEurasia</artifactId>
  <version>0.0.1-SNAPSHOT</version>

<properties>
<version.cucumber>3.0.2</version.cucumber>
</properties>
  <dependencies>
 <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
 </dependency>
 <dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.14.0</version>
</dependency>
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>1.2.5</version>
    <scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-jvm-deps</artifactId>
<version>1.0.5</version>
<scope>provided</scope>
</dependency>
 <dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>1.2.5</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-picocontainer</artifactId>
    <version>1.2.5</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>gherkin</artifactId>
    <version>2.12.2</version>
</dependency>
<dependency>
    <groupId>com.aventstack</groupId>
    <artifactId>extentreports</artifactId>
    <version>3.1.5</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>com.vimalselvam</groupId>
    <artifactId>cucumber-extentsreport</artifactId>
    <version>3.1.1</version>
</dependency>
</code>```

```<code>   <build>
    <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
              <source>1.8</source>
              <target>1.8</target>
               <encoding>UTF-8</encoding>
            </configuration>
          </plugin>
          <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.17</version>
    </plugin>
    </plugins>
</build>
</code>```

Can anyone answer how to generate Report logs on each execution using Selenium- Cucumber Maven Framework. Thanks in advance

答:
I am not sure if you have got the solution , but below there are 2 ways you can do it.

1 . Set the value of plugin in the tetsRunner.java file upto ExtentCucumberFormatter i.e ,plugin = { "com.cucumber.listener.ExtentCucumberFormatter:"} and execute the tetscase . Here by default the report will be created under the Output folder in your project directory (Just refresh your project from the Project Explorer , output folder would be generated)

Set the dynamic output file path like below in the @BeforeClass Hooker as below  in the testRunner file.

```<code>@CucumberOptions(
features = "src/test/java/Features"
,glue= {"StepDefinations"}
,plugin = { "com.cucumber.listener.ExtentCucumberFormatter:"}
,monochrome = true
)
public class testRunner {
@BeforeClass
public static void setup() {
ExtentProperties extentProperties = ExtentProperties.INSTANCE;
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
String userDir =System.getProperty("user.dir");
extentProperties.setReportPath(userDir+
                             "/target/cucumberreports/report_"+timeStamp+".html");
}
}
</code>```

Body:
I need to save each report files separately in Report directory on each Run.How can we create Report files by concatenating current date & Time along with the file name .
I have used the below code in my TestRunnerTest.java to generate Extentreport in cucumber-selenium framework.

package testRunner;

import java.io.File;
import java.io.IOException;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.vimalselvam.cucumber.listener.Reporter;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(

    features = "src/test/resources"
            , glue= {"stepDefinition"}
    , plugin = { "com.vimalselvam.cucumber.listener.ExtentCucumberFormatter:target/cucumber-reports/report.html"},
            monochrome = true
    )
public class TestRunnerTest {
public static WebDriver driver;
private static TestRunnerTest sharedInstance = new TestRunnerTest();

 private TestRunnerTest() { }

 public static TestRunnerTest getInstance() {
        return sharedInstance;
    }

 @BeforeClass
    public static void before() {

           System.setProperty("webdriver.chrome.driver",
"E:\\ChromeDriverNew\\chromedriver.exe");
           driver=new ChromeDriver();

           driver.manage().window().maximize();
 driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    }
 @AfterClass
    public static void after() {

     Reporter.loadXMLConfig(new File("config/report.xml"));
     driver.quit();
    }
}

And this is my POM dependency file.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>selcuc</groupId>
  <artifactId>DemoEurasia</artifactId>
  <version>0.0.1-SNAPSHOT</version>

<properties>
<version.cucumber>3.0.2</version.cucumber>
</properties>
  <dependencies>
 <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
 </dependency>
 <dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.14.0</version>
</dependency>
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>1.2.5</version>
    <scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-jvm-deps</artifactId>
<version>1.0.5</version>
<scope>provided</scope>
</dependency>
 <dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>1.2.5</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-picocontainer</artifactId>
    <version>1.2.5</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>gherkin</artifactId>
    <version>2.12.2</version>
</dependency>
<dependency>
    <groupId>com.aventstack</groupId>
    <artifactId>extentreports</artifactId>
    <version>3.1.5</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>com.vimalselvam</groupId>
    <artifactId>cucumber-extentsreport</artifactId>
    <version>3.1.1</version>
</dependency>

   <build>
    <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
              <source>1.8</source>
              <target>1.8</target>
               <encoding>UTF-8</encoding>
            </configuration>
          </plugin>
          <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.17</version>
    </plugin>
    </plugins>
</build>

Can anyone answer how to generate Report logs on each execution using Selenium- Cucumber Maven Framework. Thanks in advance

Body:
I am not sure if you have got the solution , but below there are 2 ways you can do it.

1 . Set the value of plugin in the tetsRunner.java file upto ExtentCucumberFormatter i.e ,plugin = { "com.cucumber.listener.ExtentCucumberFormatter:"} and execute the tetscase . Here by default the report will be created under the Output folder in your project directory (Just refresh your project from the Project Explorer , output folder would be generated)

Set the dynamic output file path like below in the @BeforeClass Hooker as below  in the testRunner file.

@CucumberOptions(
features = "src/test/java/Features"
,glue= {"StepDefinations"}
,plugin = { "com.cucumber.listener.ExtentCucumberFormatter:"}
,monochrome = true
)
public class testRunner {
@BeforeClass
public static void setup() {
ExtentProperties extentProperties = ExtentProperties.INSTANCE;
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
String userDir =System.getProperty("user.dir");
extentProperties.setReportPath(userDir+
                             "/target/cucumberreports/report_"+timeStamp+".html");
}
}


问:
Configure Eclipse workspace automatically
I have a eclipse workspace which constitutes of 15 different java projects . To configure the eclipse workspace , every time I need to add the java projects manually and add the dependency and refrences in the java build path.
Adding all the  projects and resolving dependency every time becomes a manual and redundant task. I explored on the .classpath inside the every projects which stores the dependency and refrences information.
I would like to automate this redundant process.
Have any one tried doing that , any inputs will be helpful.

I don't need to add same project more than once , but often need to create a new eclipse workspace with new code changes and delivery (I can't take some of the changes in the current work space).In simple terms for e.g if some one need to create eclipse workspace again and again , or multiple people need to create the same workspace for their work . How can we reduce that manual effort?

答:
I am still a little unsure about your motivations but I am going to assume that by new code changes and delivery you mean a different revision/branch of the same code base. For this purpose and for many other reasons, if you are not using source control like SVN or Git, look into it. These tools are priceless and also free.

Eclipse

I don't think this is technically part of your question but I wanted to add it for completeness. If you're implementing the techniques below, it is also handy to have a 'fully loaded eclipse'. I keep a 'fully loaded eclipse' on a network drive somewhere with some plugins pre-loaded so that new additions to the team don't have to download/install the plugins. It's not hard to do since eclipse doesn't need to be 'installed'. You can just copy the eclipse folder to where you want it and run it. Personally I like to include plugins for source control, code style, code coverage and metrics but you should include anything that you use consistently in your project.

The Workspace

To copy an existing workspace (not including any projects, I'll get to that later) all you have to do is copy the .metadata folder from an existing workspace folder to an empty folder that will be your new workspace folder. When you start up eclipse simply choose the new workspace folder and you will have all the same preferences as you had in the other workspace.

I have used this technique before so that when people join a project they can take a copy of a 'clean workspace' I keep on a network drive somewhere that helps them get up and running quickly. Preferably, this 'clean workspace' should not have any preferences that are only personal preferences like having the perspectives setup just the way you like it but should only have preferences like Ant global properties, compiler compliance level, pre-made commonly-used external tool and run configurations etc.

Projects

For the projects themselves, I would recommend checking them into source control including the eclipse .project and .classpath files. The SVN plugin (subclipse) makes it very easy to do this. Then when someone joins your project, all they have to do is check them out as projects in their new 'clean workspace' which is also very easy to do. Since the project you're checking-out already has the .project and .classpath files, all of the dependencies are already setup! Just make sure that all the jars and any other dependencies are checked-in with the projects.

Workspace Setup Procedure

Take a copy of the 'fully loaded eclipse'.

Take a copy of the 'clean workspace'.

Check out the projects into that workspace.

That's it! Your new recruit should be ready to go!

Multiple Code Branches

Now, if I was right to assume that by new code changes and delivery you mean a different branch of the same code base, creating a workspace for a different branch as easy as following the same steps but checking out the required revision or branch instead of the latest version from the trunk. If you don't quite understand what I mean by that, read up on source control.

Cudos

Good on you for taking the time to do this, I have been in projects where it can literally take a day to get setup...


问:
Angular - Storing an array into a form array
this is my first question here. As I'm French, I hope you'll understand it :D
And it's not quite easy to explain.
I started learning Angular two weeks ago. Just to let you know...

It's about a collection of audio albums (EPs, CDs).
Here's the JS interface:

```<code>export interface Album {
    id: number;
    artist: string;
    title: string;
    year: number;
    cover: string;
    tracks: [string, string][]; //[title, duration]
}
</code>```

I try to build a reactive form to add new albums to an existing array that shouldn't be modified. So the tracks property cannot be an array of objects. It must remain an array of string tuples. For example:

```<code>{
    id: 5,
    artist: ' Dntel',
    title: 'Life Is Full Of Possibilities',
    year: 2001,
    cover: 'R-16855-1196613859.jpg',
    tracks: [
      ['Umbrella', '4:43'],
      ['Anywhere Anyone', '4:37'],
      ...
    ]
}
</code>```

The form in the component:

```<code>export class AddAlbumComponent implements OnInit {
  albumForm: FormGroup = this.fb.group({
    artist: ['', Validators.required],
    title: ['', Validators.required],
    year: ['', Validators.required],
    cover: [''],
    tracks: this.fb.array([
      this.fb.group(
        [
          this.fb.control(''), // title input
          this.fb.control('')  // duration input
        ]
      )
    ])
  });
}
</code>```

The actual form looks like that (sorry, the interface is in French):
reactive form

And now my question: how can I store the title and duration of each track in my formarray?

I tried:

```<code><input type="text" id="title" [formControlName]="tracks.at(i,0)">
<input type="text" id="duration" [formControlName]="tracks.at(i,1)">
</code>```

But the array only contains empty strings: [['0','',''],['1','','']].

Thank you!

答:
You has an array of array, so you need use a FromArray of FormArray

```<code>albumForm: FormGroup = this.fb.group({
    artist: ['', Validators.required],
    title: ['', Validators.required],
    year: ['', Validators.required],
    cover: [''],
    tracks: this.fb.array([
      this.fb.array(  //<--this is fb.array
        [
          this.fb.control(''), // title input
          this.fb.control('')  // duration input
        ]
      )
    ])
  });
</code>```

To avoid problems in production, you declare two auxiliars functions

```<code>  get tracks()
  {
    return this.albumForm.get('tracks') as FormArray
  }
  getTrack(i)
  {
    return (this.albumForm.get('tracks') as FormArray).at(i) as FormArray
  }
</code>```

And you .html

```<code><form [formGroup]="albumForm">
    <div *ngFor="let tracks of tracks.controls;let i=index" >
        <input [formControl]="getTrack(i).at(0)">
        <input [formControl]="getTrack(i).at(1)">
    </div>
</form>
</code>```

See that we use formControl directly -not formControlName- to the inner array

stackblitz

Body:
this is my first question here. As I'm French, I hope you'll understand it :D
And it's not quite easy to explain.
I started learning Angular two weeks ago. Just to let you know...

It's about a collection of audio albums (EPs, CDs).
Here's the JS interface:

export interface Album {
    id: number;
    artist: string;
    title: string;
    year: number;
    cover: string;
    tracks: [string, string][]; //[title, duration]
}

I try to build a reactive form to add new albums to an existing array that shouldn't be modified. So the tracks property cannot be an array of objects. It must remain an array of string tuples. For example:

{
    id: 5,
    artist: ' Dntel',
    title: 'Life Is Full Of Possibilities',
    year: 2001,
    cover: 'R-16855-1196613859.jpg',
    tracks: [
      ['Umbrella', '4:43'],
      ['Anywhere Anyone', '4:37'],
      ...
    ]
}

The form in the component:

export class AddAlbumComponent implements OnInit {
  albumForm: FormGroup = this.fb.group({
    artist: ['', Validators.required],
    title: ['', Validators.required],
    year: ['', Validators.required],
    cover: [''],
    tracks: this.fb.array([
      this.fb.group(
        [
          this.fb.control(''), // title input
          this.fb.control('')  // duration input
        ]
      )
    ])
  });
}

The actual form looks like that (sorry, the interface is in French):
reactive form

And now my question: how can I store the title and duration of each track in my formarray?

I tried:

<input type="text" id="title" [formControlName]="tracks.at(i,0)">
<input type="text" id="duration" [formControlName]="tracks.at(i,1)">

But the array only contains empty strings: [['0','',''],['1','','']].

Thank you!

Body:
You has an array of array, so you need use a FromArray of FormArray

albumForm: FormGroup = this.fb.group({
    artist: ['', Validators.required],
    title: ['', Validators.required],
    year: ['', Validators.required],
    cover: [''],
    tracks: this.fb.array([
      this.fb.array(  //<--this is fb.array
        [
          this.fb.control(''), // title input
          this.fb.control('')  // duration input
        ]
      )
    ])
  });

To avoid problems in production, you declare two auxiliars functions

  get tracks()
  {
    return this.albumForm.get('tracks') as FormArray
  }
  getTrack(i)
  {
    return (this.albumForm.get('tracks') as FormArray).at(i) as FormArray
  }

And you .html

<form [formGroup]="albumForm">
    <div *ngFor="let tracks of tracks.controls;let i=index" >
        <input [formControl]="getTrack(i).at(0)">
        <input [formControl]="getTrack(i).at(1)">
    </div>
</form>

See that we use formControl directly -not formControlName- to the inner array

stackblitz


问:
Flex container items exceeding width
Hello I have a problem where my container is exceeding the maximum allowed width of my flex container (with justify space - between)

basically i divided my 3 children into 33.33%, but even so it exceeds the width:

img:

my jsx****:

```<code>const NavAcessibility = props => {
  return (
    <Accessibility>
      <ul>
        <li>
          <a>
            <p>Acessibilidade</p>
          </a>
        </li>
        <li>
          <a>A-</a>
        </li>
        <li>
          <a>A+</a>
        </li>
        <li>
          <a>
            <FontAwesomeIcon
              className="adjust"
              icon={faAdjust}
              size="1x"
              fixedWidth
              color="white"
            />
          </a>
        </li>
      </ul>
    </Accessibility>
  );
};

const ItemsTop = () => {
  return (
    <>
      <ImgWrap>
        <img src={LogoImg} />
      </ImgWrap>
      <SearchContainer>
        <IconContainer>
          <FontAwesomeIcon
            className="searchIcon"
            icon={faSearch}
            size="2x"
            fixedWidth
            color="white"
          />
        </IconContainer>
        <input placeholder="Pesquisar" />
      </SearchContainer>
    </>
  );
};

const TopHeader = () => {
  return (
    <ContainerTop>
      <HeaderTop>
        <ItemsTop />
        <NavAcessibility />
      </HeaderTop>
    </ContainerTop>
  );
};
</code>```

my css:

```<code>export const ContainerTop = styled.div`
  position: relative;
  width: 100%;
  background: red;
  box-shadow: 0 0 5px rgba(18, 23, 39, 0.2);
`;

export const HeaderTop = styled.div`
  ${mxw80}
  padding-bottom: 10px;
  padding-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1em 0;
`;

export const ImgWrap = styled.div`
  width: 33.3333%;
  display: flex;
  align-items: center;
  & > img {
    width: 80px;
  }
`;

export const IconContainer = styled.div``;
export const SearchContainer = styled.div`
  display: inline-flex;
  align-items: center;
  width: 33.3333%;
  border-radius: 25px;
  overflow: hidden;
  height: 50px;
  border: 0;
  background: rgba(0, 0, 0, 0.1);
  box-shadow: 3px 3px 6px 0 rgba(0, 0, 0, 0.07);
  transition: all 0.4s;
  margin-right: 20px;
  ${IconContainer} {
    ${flexAlignCenter}
    width: 50px;
    padding: 0.5rem 1.3rem;
    height: 100%;
    & > svg {
      font-size: 1.3em;
      color: white;
    }
  }
  & > input {
    background: transparent;
    width: calc(100% - 50px);
    height: 100%;
    border: 0;
    padding: 0.5rem 0.5rem 0.5rem 0.5rem;
    outline: none;
    color: white;
    font-size: 16px;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    box-sizing: initial;
    font-family: Roboto, Arial, sans-serif;
    ::placeholder {
      font-size: 16px;
      color: white;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      box-sizing: initial;
      font-family: Roboto, Arial, sans-serif;
    }
  }
`;

export const Accessibility = styled.nav`
  width: 33.3333%;
  height: 100%;
  & > ul {
    ${flexAlignCenter}
    width:100%;
    flex-wrap: wrap;
    height: auto;
    justify-content: center;
  }
  & > ul > li {
    position: relative;
    display: inline-block;
    font-family: "Open Sans", sans-serif;
    font-size: 13px;
    line-height: 24px;
    color: #fff;
    user-select: none;
  }
  & > ul > li:nth-child(2) {
    cursor: not-allowed;
    pointer-events: none;
    font-size: 18px;
    font-weight: 700;
    font-style: italic;
    opacity: 0.5;
    padding: 0 9px;
  }
  & > ul > li:nth-child(3) {
    font-size: 18px;
    font-weight: 700;
    font-size: 18px;
    font-weight: 700;
    padding: 0 9px;
  }
  & > ul > li > a {
    font-family: "Open Sans", sans-serif;
    font-size: 13px;
    line-height: 24px;
  }
  & > ul > li > a > p {
    position: relative;
    display: inline-block;
    pointer-events: none;
    padding: 0 9px;
  }
`;
</code>```

example:

https://codesandbox.io/s/long-monad-m54pu

I can't find where I went wrong.

答:
in your styled.js remove the width and maxwidth from

```<code>const mxw80 = css`
  height: 100%;
  margin: 0 auto;
  max-width: 80rem !important;
  width: 80rem !important;
`;
</code>```

or simply dont use mxw80 component.

or just use % or vw units instead of rem.
https://www.sitepoint.com/understanding-and-using-rem-units-in-css/

Title: Flex container items exceeding width

Body:
Hello I have a problem where my container is exceeding the maximum allowed width of my flex container (with justify space - between)

basically i divided my 3 children into 33.33%, but even so it exceeds the width:

img:

my jsx****:

const NavAcessibility = props => {
  return (
    <Accessibility>

Acessibilidade

          A-

          A+

            <FontAwesomeIcon
              className="adjust"
              icon={faAdjust}
              size="1x"
              fixedWidth
              color="white"
            />

    </Accessibility>
  );
};

const ItemsTop = () => {
  return (
    <>
      <ImgWrap>

      </ImgWrap>
      <SearchContainer>
        <IconContainer>
          <FontAwesomeIcon
            className="searchIcon"
            icon={faSearch}
            size="2x"
            fixedWidth
            color="white"
          />
        </IconContainer>
        <input placeholder="Pesquisar" />
      </SearchContainer>
    </>
  );
};

const TopHeader = () => {
  return (
    <ContainerTop>
      <HeaderTop>
        <ItemsTop />
        <NavAcessibility />
      </HeaderTop>
    </ContainerTop>
  );
};

my css:

export const ContainerTop = styled.div`
  position: relative;
  width: 100%;
  background: red;
  box-shadow: 0 0 5px rgba(18, 23, 39, 0.2);
`;

export const HeaderTop = styled.div`
  ${mxw80}
  padding-bottom: 10px;
  padding-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1em 0;
`;

export const ImgWrap = styled.div`
  width: 33.3333%;
  display: flex;
  align-items: center;
  & > img {
    width: 80px;
  }
`;

export const IconContainer = styled.div``;
export const SearchContainer = styled.div`
  display: inline-flex;
  align-items: center;
  width: 33.3333%;
  border-radius: 25px;
  overflow: hidden;
  height: 50px;
  border: 0;
  background: rgba(0, 0, 0, 0.1);
  box-shadow: 3px 3px 6px 0 rgba(0, 0, 0, 0.07);
  transition: all 0.4s;
  margin-right: 20px;
  ${IconContainer} {
    ${flexAlignCenter}
    width: 50px;
    padding: 0.5rem 1.3rem;
    height: 100%;
    & > svg {
      font-size: 1.3em;
      color: white;
    }
  }
  & > input {
    background: transparent;
    width: calc(100% - 50px);
    height: 100%;
    border: 0;
    padding: 0.5rem 0.5rem 0.5rem 0.5rem;
    outline: none;
    color: white;
    font-size: 16px;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    box-sizing: initial;
    font-family: Roboto, Arial, sans-serif;
    ::placeholder {
      font-size: 16px;
      color: white;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      box-sizing: initial;
      font-family: Roboto, Arial, sans-serif;
    }
  }
`;

export const Accessibility = styled.nav`
  width: 33.3333%;
  height: 100%;
  & > ul {
    ${flexAlignCenter}
    width:100%;
    flex-wrap: wrap;
    height: auto;
    justify-content: center;
  }
  & > ul > li {
    position: relative;
    display: inline-block;
    font-family: "Open Sans", sans-serif;
    font-size: 13px;
    line-height: 24px;
    color: #fff;
    user-select: none;
  }
  & > ul > li:nth-child(2) {
    cursor: not-allowed;
    pointer-events: none;
    font-size: 18px;
    font-weight: 700;
    font-style: italic;
    opacity: 0.5;
    padding: 0 9px;
  }
  & > ul > li:nth-child(3) {
    font-size: 18px;
    font-weight: 700;
    font-size: 18px;
    font-weight: 700;
    padding: 0 9px;
  }
  & > ul > li > a {
    font-family: "Open Sans", sans-serif;
    font-size: 13px;
    line-height: 24px;
  }
  & > ul > li > a > p {
    position: relative;
    display: inline-block;
    pointer-events: none;
    padding: 0 9px;
  }
`;

example:

https://codesandbox.io/s/long-monad-m54pu

I can't find where I went wrong.

Body:
in your styled.js remove the width and maxwidth from

const mxw80 = css`
  height: 100%;
  margin: 0 auto;
  max-width: 80rem !important;
  width: 80rem !important;
`;

or simply dont use mxw80 component.

or just use % or vw units instead of rem.
https://www.sitepoint.com/understanding-and-using-rem-units-in-css/


问:
fatal: fsync error on git/repo/path
I try to whole day resolve the trouble:
When i try to pull or clone exists repository in empty directory, i got error:

```<code>$ git clone https://bitbucket.org/path_to_repo/aroma
Cloning into 'aroma'...
remote: Counting objects: 1335, done.
remote: Compressing objects: 100% (1174/1174), done.
remote: Total 1335 (delta 618), rReecused 551 (deltea 72)
Receiving objects: 100% (1335/1335), 43.16 MiB | 3.78 MiB/s, done.
Resolving deltas: 100% (618/618), done.
fatal: fsync error on 'H:/Project/testrep/aroma/.git/objects/pack/tmp_pack_xqHCKb': Bad file descriptor
fatal: index-pack failed
</code>```

I tried set pack.windowMemory size and pack.packSizeLimit in config and more. The same error ;[
Before I could to clone repositories. But something went wrong

答:
Confirm the config is done for the git, check using the below command.

```<code>$ git config --list
</code>```

If you can't see anything then setup the config using commands

```<code>$ git config --global user.name "Your Name"
$ git config --global user.email "youremail@yourdomain.com"
</code>```

confirm again

```<code>$ git config --list
</code>```

Title: fatal: fsync error on git/repo/path

Body:
I try to whole day resolve the trouble:
When i try to pull or clone exists repository in empty directory, i got error:

$ git clone https://bitbucket.org/path_to_repo/aroma
Cloning into 'aroma'...
remote: Counting objects: 1335, done.
remote: Compressing objects: 100% (1174/1174), done.
remote: Total 1335 (delta 618), rReecused 551 (deltea 72)
Receiving objects: 100% (1335/1335), 43.16 MiB | 3.78 MiB/s, done.
Resolving deltas: 100% (618/618), done.
fatal: fsync error on 'H:/Project/testrep/aroma/.git/objects/pack/tmp_pack_xqHCKb': Bad file descriptor
fatal: index-pack failed

I tried set pack.windowMemory size and pack.packSizeLimit in config and more. The same error ;[
Before I could to clone repositories. But something went wrong

Body:
Confirm the config is done for the git, check using the below command.

$ git config --list

If you can't see anything then setup the config using commands

$ git config --global user.name "Your Name"
$ git config --global user.email "youremail@yourdomain.com"

confirm again

$ git config --list


问:
postgreSQL: field separated by semicolon
I have a field called client_no_all:

```<code>client_no_all
14521;555555;636582142;
</code>```

I want to separate the values and assign them to client_no:

```<code>client_no
14521
555555
636582142
</code>```

Should I use a cursor to loop or pivot?

答:
You can use following query.
The function string_to_array() splits a string by a delimiter into an array.
With the function unnest() you can expand an array to a set of rows.

```<code>SELECT unnest(string_to_array('1;2;3;4;5', ';')) AS val
</code>```

Body:
I have a field called client_no_all:

client_no_all
14521;555555;636582142;

I want to separate the values and assign them to client_no:

client_no
14521
555555
636582142

Should I use a cursor to loop or pivot?

Body:
You can use following query.
The function string_to_array() splits a string by a delimiter into an array.
With the function unnest() you can expand an array to a set of rows.

SELECT unnest(string_to_array('1;2;3;4;5', ';')) AS val


问:
Apache try full filename (GET parameters as part of filename)
I have files on my Apache webserver with names like "index.cfm?PageID=30" where ?PageID=30 is a part of the actual filename. How can I set up .htaccess to make Apache open these files correctly without using PageID as URL parameters?

I use try_files $uri $uri$args for similar issues in Nginx, but I'm new with Apache.

Same for files like "news.asp?sec=news&article=24".

I just need to 200 OK (with content of file /var/example/news.asp?sec=news&article=24) when I ask for page example.com/news.asp?sec=news&article=24.

答:
I have found the correct code:

```<code><IfModule mod_rewrite.c>

RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} !200
RewriteCond %{QUERY_STRING} !^$
RewriteRule ^(.*)$ /$1\%3F%{QUERY_STRING} [L,NE]

</IfModule>
</code>```

You can check how it works mt website. For example http://www.drugeducationforum.com/index.cfm?PageID=30
Where index.cfm?PageID=30 is a full name of the file.

Body:
I have found the correct code:

<IfModule mod_rewrite.c>

RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} !200
RewriteCond %{QUERY_STRING} !^$
RewriteRule ^(.*)$ /$1\%3F%{QUERY_STRING} [L,NE]

</IfModule>

You can check how it works mt website. For example http://www.drugeducationforum.com/index.cfm?PageID=30
Where index.cfm?PageID=30 is a full name of the file.


问:
Stored procedure executes successfully but changes are not saved to database
I have the following stored procedure that I invoke through a WCF service (C#.NET).

The procedure executes successfully (I traced using profile), problem is that changes are not saved to database. I googled a lot but I couldn't find a solution to this problem...

```<code>   ALTER PROCEDURE [dbo].[sp_create_x]
   (
       @X VarChar(10), @Y VarChar(2), @Z DateTime,
       @A VarChar(10), @B DateTime, @C Int)
   AS
   BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
IF NOT EXISTS (SELECT x FROM tblTable WHERE x = @X)
BEGIN
            INSERT INTO
                tblTable (x, y, z, a, b, c)
            VALUES (@X, @Y, @Z, @A, @B, @C)
    END
END
RETURN @@ERROR
</code>```

The C# code that is used to invoke the sp is as follows:

```<code>    SqlConnection conn = new SqlConnection(myConnectionString);
    SqlCommand cmd = new SqlCommand("sp_create_x", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.Clear();
    cmd.Parameters.Add("@X", SqlDbType.VarChar).Value = "somevalue";
    cmd.Parameters.Add("@Y", SqlDbType.VarChar).Value = "somevalue";
    cmd.Parameters.Add("@Z", SqlDbType.DateTime).Value = DateTime.Now;
    cmd.Parameters.Add("@A", SqlDbType.VarChar).Value = "somevalue";
    cmd.Parameters.Add("@B", SqlDbType.DateTime).Value = DateTime.Now;
    cmd.Parameters.Add("@C", SqlDbType.Int).Value = 1;
    cmd.Parameters.Add("@RETURN", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;

    cmd.Transaction = trans;

    cmd.ExecuteNonQuery();

    int errCode = (int)cmd.Parameters["@RETURN"].Value;
    conn.Close();

    if (errCode != 0)
    {
       throw new Exception(string.Format("Error!));
    }
</code>```

What am I missing???

Thanks a billion in advance

答: I'm guessing the cmd.Transaction = trans assigns a transaction that is never comitted.

Body:
I have the following stored procedure that I invoke through a WCF service (C#.NET).

The procedure executes successfully (I traced using profile), problem is that changes are not saved to database. I googled a lot but I couldn't find a solution to this problem...

   ALTER PROCEDURE [dbo].[sp_create_x]
   (
       @X VarChar(10), @Y VarChar(2), @Z DateTime,
       @A VarChar(10), @B DateTime, @C Int)
   AS
   BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
IF NOT EXISTS (SELECT x FROM tblTable WHERE x = @X)
BEGIN
            INSERT INTO
                tblTable (x, y, z, a, b, c)
            VALUES (@X, @Y, @Z, @A, @B, @C)
    END
END
RETURN @@ERROR

The C# code that is used to invoke the sp is as follows:

    SqlConnection conn = new SqlConnection(myConnectionString);
    SqlCommand cmd = new SqlCommand("sp_create_x", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.Clear();
    cmd.Parameters.Add("@X", SqlDbType.VarChar).Value = "somevalue";
    cmd.Parameters.Add("@Y", SqlDbType.VarChar).Value = "somevalue";
    cmd.Parameters.Add("@Z", SqlDbType.DateTime).Value = DateTime.Now;
    cmd.Parameters.Add("@A", SqlDbType.VarChar).Value = "somevalue";
    cmd.Parameters.Add("@B", SqlDbType.DateTime).Value = DateTime.Now;
    cmd.Parameters.Add("@C", SqlDbType.Int).Value = 1;
    cmd.Parameters.Add("@RETURN", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;

    cmd.Transaction = trans;

    cmd.ExecuteNonQuery();

    int errCode = (int)cmd.Parameters["@RETURN"].Value;
    conn.Close();

    if (errCode != 0)
    {
       throw new Exception(string.Format("Error!));
    }

What am I missing???

Thanks a billion in advance


问:
Set value to a variable in a CASE statement
Background:
I have a tabel called History. In this table i have 3 different columns that represents 3 different types of adresses (domestic adress, foreign adress and other adress). A record set from this tabel may contain values for one, more or none of these adress types. I am therefore trying to retrieve the adresstype and it's value by using a CASE statement and assigning the value to a variable.

Question:
I get no errors in my query but it returns nothing. What am i doing wrong?

```<code>DECLARE @vAdress AS VARCHAR(50)

SELECT H.FIRSTNAME, H.LASTNAME, @vAdress, C.COUNTRY
FROM History H
LEFT JOIN COUNTRY C
ON H.COUNTRYCODE = C.COUNTRYCODE
WHERE H.EMAILADRESS = 'johndoe.doe@test.com'
AND @vAdress = CASE
                   WHEN H.D_ADRESS IS NOT NULL THEN H.D_ADRESS
                   WHEN H.F_ADRESS IS NOT NULL THEN H.F_ADRESS
                   ELSE H.O_ADRESS
               END
</code>```

答:
I would move the CASE to the Select so you get a valid value depending on the address column that has actual data. Like this:

```<code>DECLARE @vAdress AS VARCHAR(50)

SELECT H.FIRSTNAME, H.LASTNAME,
@vAdress = CASE
               WHEN H.D_ADRESS IS NOT NULL THEN H.D_ADRESS
                   WHEN H.F_ADRESS IS NOT NULL THEN H.F_ADRESS
                   ELSE H.O_ADRESS
               END,
C.COUNTRY
FROM History H
LEFT JOIN COUNTRY C
ON H.COUNTRYCODE = C.COUNTRYCODE
WHERE H.EMAILADRESS = 'johndoe.doe@test.com'
</code>```

In this case you will get the address value from the column that has data in it.

Body:
Background:
I have a tabel called History. In this table i have 3 different columns that represents 3 different types of adresses (domestic adress, foreign adress and other adress). A record set from this tabel may contain values for one, more or none of these adress types. I am therefore trying to retrieve the adresstype and it's value by using a CASE statement and assigning the value to a variable.

Question:
I get no errors in my query but it returns nothing. What am i doing wrong?

DECLARE @vAdress AS VARCHAR(50)

SELECT H.FIRSTNAME, H.LASTNAME, @vAdress, C.COUNTRY
FROM History H
LEFT JOIN COUNTRY C
ON H.COUNTRYCODE = C.COUNTRYCODE
WHERE H.EMAILADRESS = 'johndoe.doe@test.com'
AND @vAdress = CASE
                   WHEN H.D_ADRESS IS NOT NULL THEN H.D_ADRESS
                   WHEN H.F_ADRESS IS NOT NULL THEN H.F_ADRESS
                   ELSE H.O_ADRESS
               END

Body:
I would move the CASE to the Select so you get a valid value depending on the address column that has actual data. Like this:

DECLARE @vAdress AS VARCHAR(50)

SELECT H.FIRSTNAME, H.LASTNAME,
@vAdress = CASE
               WHEN H.D_ADRESS IS NOT NULL THEN H.D_ADRESS
                   WHEN H.F_ADRESS IS NOT NULL THEN H.F_ADRESS
                   ELSE H.O_ADRESS
               END,
C.COUNTRY
FROM History H
LEFT JOIN COUNTRY C
ON H.COUNTRYCODE = C.COUNTRYCODE
WHERE H.EMAILADRESS = 'johndoe.doe@test.com'

In this case you will get the address value from the column that has data in it.


问:
Plotting an hyperbola with matplotlib
I need to plot an hyperbola of the type (y-ax)(y-bx)=-1 with matplotlib, I've tried to express y(x) but it gives an sqrt with impossible values. How can I assign to y the values to be plotted?
The function i want to plot is

$$(y-\log(r^a 10^c))(y-\log(r^b10^d))=-1$$

which I "can" be rewritten as

$$y=1/2[log(r^(a+b)10^(c+d))\pm\sqrt{-4+\log^2(r^(a-b)10^(c-d))}]$$

答:
With sympy, Python's symbolic math library, that builds on matplotlib to directly plot an implicit curve.

from sympy import plot_implicit, Eq
from sympy.abc import x, y

a = -1
b = 3
plot_implicit(Eq((y - a * x) * (y - b * x), -1), (x, -10, 10), (y, -10, 10))
```

<p><img src="https://i.stack.imgur.com/IpKGX.png" alt="enter image description here"></p>

<p>The other equation could be plotted as follows, provided you rename <code>x</code> to <code>r</code> and have interesting values for the parameters and limits.</p>

<pre class="lang-py prettyprint-override"><code>from sympy import plot_implicit, Eq, log
from sympy.abc import x, y

a = ...
b = ...
c = ...
d = ...
eq1 = Eq ((y- log(x**a * 10**c))*(x-log(x**b * 10*d)), -1)
plot_implicit(eq1, (x, -100, 100), (y, -100, 100))
</code>```

Title: Plotting an hyperbola with matplotlib

Body:
With sympy, Python's symbolic math library, that builds on matplotlib to directly plot an implicit curve.

from sympy import plot_implicit, Eq
from sympy.abc import x, y

a = -1
b = 3
plot_implicit(Eq((y - a * x) * (y - b * x), -1), (x, -10, 10), (y, -10, 10))

The other equation could be plotted as follows, provided you rename x to r and have interesting values for the parameters and limits.

from sympy import plot_implicit, Eq, log
from sympy.abc import x, y

a = ...
b = ...
c = ...
d = ...
eq1 = Eq ((y- log(x**a * 10**c))*(x-log(x**b * 10*d)), -1)
plot_implicit(eq1, (x, -100, 100), (y, -100, 100))


问:
WCF error management using WebFaultException - Wrong HttpStatusCode
I have implemented a simple web service and I want to return appropriate Http Status Error codes depending on the error that occurred in the method being called.

I am using .NET framework 4.7.2 with Visual Studio 2019 and the IIS Express 10 built into Visual Studio for testing at the moment. I am using the Boomerang extension for Chrome to call the service.

I have implemented a FindPerson method that takes a name. If the person is not found, or more than one person is found, I want to return a "Not Found" response (404).

I have implemented a simple ServiceError class that I am using to throw a WebFaultException along with a Not Found error code. When I throw the WebFaultException the appropriate fault response is sent to the consumer (I see the details of the problem) but the http status is 500 (internal service error) instead of the 404 error I used (and expected to be received)

Here is my simple FindPerson method:

```<code>Private Function FindPerson(ByVal name As String) As Person Implements MyService.FindPerson

    Dim foundPerson As Person = Nothing
    Dim people = GetPeople(name)
    Select Case people.Count
        Case Is > 1
            Throw New WebFaultException(Of ServiceError)(New ServiceError("More than 1 person found with the name provided.", ""), HttpStatusCode.NotFound)
        Case Is = 0
            Throw New WebFaultException(Of ServiceError)(New ServiceError("No Person with the name provided was found.", ""), HttpStatusCode.NotFound)
        Case Else
            foundPerson = people(0)
    End Select

    Return foundPerson
End Function
</code>```

Here is my ServiceError class:

```<code><DataContract>
Public Class ServiceError
    <DataMember>
    Public Property ErrorInfo As String
    <DataMember>
    Public Property ErrorDetails As String
    Public Sub New(ByVal info As String, ByVal details As String)
        Me.ErrorInfo = info
        Me.ErrorDetails = details
    End Sub
    Public Sub New()

    End Sub

End Class
</code>```

This is the response I get. Like I said, the details are correct... but the Http Status Error code is 500 instead of 404:

```<code><s:Envelope
    xmlns:s="http://www.w3.org/2003/05/soap-envelope"
    xmlns:a="http://www.w3.org/2005/08/addressing">
    <s:Header>
        <a:Action s:mustUnderstand="1">http://www.w3.org/2005/08/addressing/soap/fault</a:Action>
    </s:Header>
    <s:Body>
        <s:Fault>
            <s:Code>
                <s:Value>s:Sender</s:Value>
                <s:Subcode>
                    <s:Value
                        xmlns:a="http://schemas.microsoft.com/2009/WebFault">a:NotFound
                    </s:Value>
                </s:Subcode>
            </s:Code>
            <s:Reason>
                <s:Text xml:lang="en-US">Not Found</s:Text>
            </s:Reason>
            <s:Detail>
                <ServiceError
                    xmlns="http://schemas.datacontract.org/2004/07/My_Web_Service"
                    xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
                    <ErrorDetails/>
                    <ErrorInfo>No Person with the name provided was found.</ErrorInfo>
                </ServiceError>
            </s:Detail>
        </s:Fault>
    </s:Body>
</s:Envelope>
</code>```

Edit:
I found a solution to my problem but it has only made me realize I need to find a better solution.

The solution involved implementing a method called RaiseWebException that set the outgoing response status code to the status that was also set in the WebFaultException:

```<code>Private Sub RaiseWebException(ByVal status As HttpStatusCode, ByVal info As String, ByVal details As String)
        WebOperationContext.Current.OutgoingResponse.StatusCode = status
        Throw New WebFaultException(Of ServiceError)(New ServiceError(info, details), HttpStatusCode.NotFound)
End Sub
</code>```

I called the method when I failed to find my person:

```<code>Private Function FindPerson(ByVal name As String) As Person Implements MyService.FindPerson

  Dim foundPerson As Person = Nothing
  Dim people = GetPeople(name)
  Select Case people.Count
    Case Is > 1
        RaiseWebException(HttpStatusCode.NotFound, "More than 1 person found with the name provided.", "")
    Case Is = 0
        RaiseWebException(HttpStatusCode.NotFound, "Person with the name provided was found.", "")
    Case Else
        foundPerson = people(0)
  End Select

  Return foundPerson
End Function
</code>```

This works well when calling the method from the browser using Boomerang; however, when I test calling the method in a vb.net consuming test application, I am not seeing the service error details. I am getting the generic 404 error with a generic error message that states that "the endpoint couldn't be reached" instead of "the person wasn't found". This will be confusing for anyone calling the service through a consuming application implemented with .NET

I'm not sure this is the best solution for error management in my service going forward.

I am open to any suggestions on the best practices for error management in .NET web services.

Thank you

答:
I found a solution to my original question: Set the OutGoingResponse.StatusCode to the same status code I used for the WebFaultException

The solution involved implementing a method called RaiseWebException that set the outgoing response status code to the status that was also set in the WebFaultException:

```<code>Private Sub RaiseWebException(ByVal status As HttpStatusCode, ByVal info As String, ByVal details As String)
        WebOperationContext.Current.OutgoingResponse.StatusCode = status
        Throw New WebFaultException(Of ServiceError)(New ServiceError(info, details), status)
End Sub
</code>```

I call the method when I failed to find my person:

```<code>Private Function FindPerson(ByVal name As String) As Person Implements MyService.FindPerson

  Dim foundPerson As Person = Nothing
  Dim people = GetPeople(name)
  Select Case people.Count
    Case Is > 1
        RaiseWebException(HttpStatusCode.NotFound, "More than 1 person found with the name provided.", "")
    Case Is = 0
        RaiseWebException(HttpStatusCode.NotFound, "Person with the name provided was found.", "")
    Case Else
        foundPerson = people(0)
  End Select

  Return foundPerson
End Function
</code>```

This works well when calling the method from the browser using Boomerang; however, when I test calling the method in a vb.net consuming test application, I am not seeing the service error details. I am getting the generic 404 error with a generic error message that states that "the endpoint couldn't be reached" instead of "the person wasn't found". This will be confusing for anyone calling the service through a consuming application implemented with .NET.

So, while this is the answer to my original question/problem, it appears to be inadequate for the overall project. Best of luck to anyone else facing the same thing.

Body:
I have implemented a simple web service and I want to return appropriate Http Status Error codes depending on the error that occurred in the method being called.

I am using .NET framework 4.7.2 with Visual Studio 2019 and the IIS Express 10 built into Visual Studio for testing at the moment. I am using the Boomerang extension for Chrome to call the service.

I have implemented a FindPerson method that takes a name. If the person is not found, or more than one person is found, I want to return a "Not Found" response (404).

I have implemented a simple ServiceError class that I am using to throw a WebFaultException along with a Not Found error code. When I throw the WebFaultException the appropriate fault response is sent to the consumer (I see the details of the problem) but the http status is 500 (internal service error) instead of the 404 error I used (and expected to be received)

Here is my simple FindPerson method:

Private Function FindPerson(ByVal name As String) As Person Implements MyService.FindPerson

    Dim foundPerson As Person = Nothing
    Dim people = GetPeople(name)
    Select Case people.Count
        Case Is > 1
            Throw New WebFaultException(Of ServiceError)(New ServiceError("More than 1 person found with the name provided.", ""), HttpStatusCode.NotFound)
        Case Is = 0
            Throw New WebFaultException(Of ServiceError)(New ServiceError("No Person with the name provided was found.", ""), HttpStatusCode.NotFound)
        Case Else
            foundPerson = people(0)
    End Select

    Return foundPerson
End Function

Here is my ServiceError class:

<DataContract>
Public Class ServiceError
    <DataMember>
    Public Property ErrorInfo As String
    <DataMember>
    Public Property ErrorDetails As String
    Public Sub New(ByVal info As String, ByVal details As String)
        Me.ErrorInfo = info
        Me.ErrorDetails = details
    End Sub
    Public Sub New()

    End Sub

End Class

This is the response I get. Like I said, the details are correct... but the Http Status Error code is 500 instead of 404:

<s:Envelope
    xmlns:s="http://www.w3.org/2003/05/soap-envelope"
    xmlns:a="http://www.w3.org/2005/08/addressing">
    <s:Header>
        http://www.w3.org/2005/08/addressing/soap/fault
    </s:Header>
    <s:Body>
        <s:Fault>
            <s:Code>
                <s:Value>s:Sender</s:Value>
                <s:Subcode>
                    <s:Value
                        xmlns:a="http://schemas.microsoft.com/2009/WebFault">a:NotFound
                    </s:Value>
                </s:Subcode>
            </s:Code>
            <s:Reason>
                <s:Text xml:lang="en-US">Not Found</s:Text>
            </s:Reason>
            <s:Detail>
                <ServiceError
                    xmlns="http://schemas.datacontract.org/2004/07/My_Web_Service"
                    xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
                    <ErrorDetails/>
                    <ErrorInfo>No Person with the name provided was found.</ErrorInfo>
                </ServiceError>
            </s:Detail>
        </s:Fault>
    </s:Body>
</s:Envelope>

Edit:
I found a solution to my problem but it has only made me realize I need to find a better solution.

The solution involved implementing a method called RaiseWebException that set the outgoing response status code to the status that was also set in the WebFaultException:

Private Sub RaiseWebException(ByVal status As HttpStatusCode, ByVal info As String, ByVal details As String)
        WebOperationContext.Current.OutgoingResponse.StatusCode = status
        Throw New WebFaultException(Of ServiceError)(New ServiceError(info, details), HttpStatusCode.NotFound)
End Sub

I called the method when I failed to find my person:

Private Function FindPerson(ByVal name As String) As Person Implements MyService.FindPerson

  Dim foundPerson As Person = Nothing
  Dim people = GetPeople(name)
  Select Case people.Count
    Case Is > 1
        RaiseWebException(HttpStatusCode.NotFound, "More than 1 person found with the name provided.", "")
    Case Is = 0
        RaiseWebException(HttpStatusCode.NotFound, "Person with the name provided was found.", "")
    Case Else
        foundPerson = people(0)
  End Select

  Return foundPerson
End Function

This works well when calling the method from the browser using Boomerang; however, when I test calling the method in a vb.net consuming test application, I am not seeing the service error details. I am getting the generic 404 error with a generic error message that states that "the endpoint couldn't be reached" instead of "the person wasn't found". This will be confusing for anyone calling the service through a consuming application implemented with .NET

I'm not sure this is the best solution for error management in my service going forward.

I am open to any suggestions on the best practices for error management in .NET web services.

Thank you

Body:
I found a solution to my original question: Set the OutGoingResponse.StatusCode to the same status code I used for the WebFaultException

The solution involved implementing a method called RaiseWebException that set the outgoing response status code to the status that was also set in the WebFaultException:

Private Sub RaiseWebException(ByVal status As HttpStatusCode, ByVal info As String, ByVal details As String)
        WebOperationContext.Current.OutgoingResponse.StatusCode = status
        Throw New WebFaultException(Of ServiceError)(New ServiceError(info, details), status)
End Sub

I call the method when I failed to find my person:

Private Function FindPerson(ByVal name As String) As Person Implements MyService.FindPerson

  Dim foundPerson As Person = Nothing
  Dim people = GetPeople(name)
  Select Case people.Count
    Case Is > 1
        RaiseWebException(HttpStatusCode.NotFound, "More than 1 person found with the name provided.", "")
    Case Is = 0
        RaiseWebException(HttpStatusCode.NotFound, "Person with the name provided was found.", "")
    Case Else
        foundPerson = people(0)
  End Select

  Return foundPerson
End Function

This works well when calling the method from the browser using Boomerang; however, when I test calling the method in a vb.net consuming test application, I am not seeing the service error details. I am getting the generic 404 error with a generic error message that states that "the endpoint couldn't be reached" instead of "the person wasn't found". This will be confusing for anyone calling the service through a consuming application implemented with .NET.

So, while this is the answer to my original question/problem, it appears to be inadequate for the overall project. Best of luck to anyone else facing the same thing.


问:
Cell formating based on other cell value google sheets
I have 2 sheets the first one is Orders and second one is the ShippingDoc.

At Shipping doc, I have Cell C2. In that cell I choose/write  ID from range of A7:A from Orders.

Is there a way if I choose example ID 1 at C2 then automatically A7 at Orders to change background to green. Also if I change the ID to 2 the A8 to be green and to not delete the A7 color.

答:
There is a better way of achieving this using Apps Script. Go to tools->Script editor and there use the following code (explained on the comments in the code):

  // Update everytime the value on C2 changes
  function onEdit() {
    var spreadsheet = SpreadsheetApp.getActive();
    // Get C2 value
    var C2value = spreadsheet.getSheetByName("ShippingDoc").getRange('C2').getValue();

    // If input value is higher than 0
    if(C2value>0){
      // Ofset to set the background after A7
      var number = C2value+6;
      // Set background color of appropiate cell
      spreadsheet.getSheetByName("Orders").getRange('A'+number+'').setBackground('green');
    }

  }```

Check out more information about how to do amazing things in sheets with simple scripts HERE

I hope this has helped you. Let me know if you need anything or if you did  not understand something.

Body:
There is a better way of achieving this using Apps Script. Go to tools->Script editor and there use the following code (explained on the comments in the code):

  // Update everytime the value on C2 changes
  function onEdit() {
    var spreadsheet = SpreadsheetApp.getActive();
    // Get C2 value
    var C2value = spreadsheet.getSheetByName("ShippingDoc").getRange('C2').getValue();

    // If input value is higher than 0
    if(C2value>0){
      // Ofset to set the background after A7
      var number = C2value+6;
      // Set background color of appropiate cell
      spreadsheet.getSheetByName("Orders").getRange('A'+number+'').setBackground('green');
    }

  }

Check out more information about how to do amazing things in sheets with simple scripts HERE

I hope this has helped you. Let me know if you need anything or if you did  not understand something.


答:
You need to constrain the parent width inside the html & body.
I suggest you should use 100vw for the parent element instead of 100%</p>

Title: Flex container items exceeding width


问:
Global Error Handler for Flash Player 10.1 not working
Trying to implement the new FP 10.1 Global error handler into my projects but no matter what I do any uncaught error will still show up the Exception window (both in debug and release versions of the SWF). All I want to do is to prevent these popups but instead send a message to my logger. Here's my code ...

EDIT: I simplified the code now. Could somebody do me a favor and test the following class and see if it's works for him? Because it's doesn't for me! ...

```<code>package
{
    import flash.display.Sprite;
    import flash.events.UncaughtErrorEvent;

    public class GlobalErrorHandlerTest extends Sprite
    {
        public function GlobalErrorHandlerTest()
        {
            stage.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onUncaughtError);
            throw new Error();
        }

        private function onUncaughtError(e:UncaughtErrorEvent):void
        {
            var message:String;
            if (e.error["message"])
            {
                message = e.error["message"];
            }
            else if (e.error["text"])
            {
                message = e.error["text"];
            }
            else
            {
                message = e.error["toString"]();
            }

            trace("Uncaught Error: " + e.text);
        }
    }
}
</code>```

答:
UPDATE: I think I may know why you think this isn't working. I made the mistake of testing inside the debugger. When the debugger stopped on the runtime errors I assumed that this proved my uncaughtErrorHandler function was not working. In fact, this was in error. It's just a quirk of the debugger. The debugger will still stop as if it is an unhandled error or exception, but if you press Run again you'll see it DOES execute the error handling code. See my thread Flex 4.0/4.5 global error handling for more info.

Original response:
I am looking for this same info. None of the examples in the API doc nor various blogs on the subject work for me. I've tried just loaderInfo, stage.loaderInfo, systemManager.loaderInfo... It makes no difference. I even tried all of them in a single test case! The addEventListener are being set but the uncaught errors are not firing the uncaughtErrorHandler. Argh. I have wasted far too much time on this! I've reduced it to a very simple program much like above except with all the code in the main mxml file.

How about this: can someone post a Global Error Handling example that DOES work? I'm using Flex SDK 4.1 (I've also tried with 4.5), targeting FP 10.1 (or 10.2 for 4.5), in a mx:Application-based mxml Flex project.

My thread: Flex 4.0/4.5 global error handling

Body:
Trying to implement the new FP 10.1 Global error handler into my projects but no matter what I do any uncaught error will still show up the Exception window (both in debug and release versions of the SWF). All I want to do is to prevent these popups but instead send a message to my logger. Here's my code ...

EDIT: I simplified the code now. Could somebody do me a favor and test the following class and see if it's works for him? Because it's doesn't for me! ...

package
{
    import flash.display.Sprite;
    import flash.events.UncaughtErrorEvent;

    public class GlobalErrorHandlerTest extends Sprite
    {
        public function GlobalErrorHandlerTest()
        {
            stage.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onUncaughtError);
            throw new Error();
        }

        private function onUncaughtError(e:UncaughtErrorEvent):void
        {
            var message:String;
            if (e.error["message"])
            {
                message = e.error["message"];
            }
            else if (e.error["text"])
            {
                message = e.error["text"];
            }
            else
            {
                message = e.error["toString"]();
            }

            trace("Uncaught Error: " + e.text);
        }
    }
}


问:
Cant match a particular pattern in regex using OR
Here is my regex :

```<code>(M|D|MD|A|AM|AD|AMD)?=(0|1|-1|D|A|!D|!A|-D|-A|D\+A)?
</code>```

It matches with

```<code>M=D
M=A
M=1
and so on
</code>```

but it doesnt match with

```<code>M=D+A
</code>```

what am i doing wrong here?

答:
You need a quantifier for the group as in:

```<code>(M|D|MD|A|AM|AD|AMD)?=((?:\+A|0|1|-1|D|A|!D|!A|-D|-A)+)
#                      ^^^                          ^^^
</code>```

See a demo on regex101.com.

Depending on your actual needs, a simpler regex like (\w+)=([-+!\w]+) and a programmatical check afterwards might be easier to understand though.

See an example for the latter on regex101.com as well.

Body:
Here is my regex :

(M|D|MD|A|AM|AD|AMD)?=(0|1|-1|D|A|!D|!A|-D|-A|D\+A)?

It matches with

M=D
M=A
M=1
and so on

but it doesnt match with

M=D+A

what am i doing wrong here?

Body:
You need a quantifier for the group as in:

(M|D|MD|A|AM|AD|AMD)?=((?:\+A|0|1|-1|D|A|!D|!A|-D|-A)+)
#                      ^^^                          ^^^

See a demo on regex101.com.

Depending on your actual needs, a simpler regex like (\w+)=([-+!\w]+) and a programmatical check afterwards might be easier to understand though.

See an example for the latter on regex101.com as well.


问:
raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: Assertion failed
I have a problem with Selenium Webdriver, trying to locate the element, the program gives an error    "raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message:     Assertion failed"

My code is with a page-object model:
My code:
1st part -

```<code>  def located_element(self, locator):
        wait = WebDriverWait(self.driver, 30)
        element = wait.until(EC.presence_of_element_located(locator))
        return element
</code>```

2nd part

```<code> def enter_email(self, user):
        email_field = self.located_element(self.locator.Email)
        email_field.click()
        email_field.send_keys(Users.get_user(user)["email"])
</code>```

3rd(running)

I have tried some recommendations from related issues but it didn't help me. At first, it couldn't find the element, that's why I added EC, but now it raises an error. Please, help me, how can I handle the Exception. I have tried the locator both with xpath and css-selector too.

答:
In the first time you open the site the email field doesn't have class input-error. Try

```<code>email_field = self.located_element((By.CSS_SELECTOR, '[data-login-source="loginPage"] [name="email"]'))
</code>```

Body:
I have a problem with Selenium Webdriver, trying to locate the element, the program gives an error    "raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message:     Assertion failed"

My code is with a page-object model:
My code:
1st part -

  def located_element(self, locator):
        wait = WebDriverWait(self.driver, 30)
        element = wait.until(EC.presence_of_element_located(locator))
        return element

2nd part

 def enter_email(self, user):
        email_field = self.located_element(self.locator.Email)
        email_field.click()
        email_field.send_keys(Users.get_user(user)["email"])

3rd(running)

I have tried some recommendations from related issues but it didn't help me. At first, it couldn't find the element, that's why I added EC, but now it raises an error. Please, help me, how can I handle the Exception. I have tried the locator both with xpath and css-selector too.

Body:
In the first time you open the site the email field doesn't have class input-error. Try

email_field = self.located_element((By.CSS_SELECTOR, '[data-login-source="loginPage"] [name="email"]'))