问:
What if i don't need time along with date from room database type converter
```<code>public class DateConverter {

@TypeConverter
public Date fromTimestamp(Long value) {
    return value == null ? null : new Date(value);
}

@TypeConverter
public Long dateToTimestamp(Date date) {
    if (date == null) {
        return null;
    } else {
        return date.getTime();
    }
}
}
</code>```

In the above code it is giving both time and date...But if i want only date to display, what should i do?

答:
You can convert the date from Date object to String and then convert the String (primitive) to Date. I haven't tested the code, but it should look something like this:

```<code>public class DateConverter {

  public static Date toDate(String dateString){
     if(timestamp == null)
         return null;
     return new Date(dateString);
  }

  public static String toTimestamp(Date date){
      SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yy");
      return dateTimeFormat.format(date);
  }
}
</code>```

Body:
public class DateConverter {

@TypeConverter
public Date fromTimestamp(Long value) {
    return value == null ? null : new Date(value);
}

@TypeConverter
public Long dateToTimestamp(Date date) {
    if (date == null) {
        return null;
    } else {
        return date.getTime();
    }
}
}

In the above code it is giving both time and date...But if i want only date to display, what should i do?

Body:
You can convert the date from Date object to String and then convert the String (primitive) to Date. I haven't tested the code, but it should look something like this:

public class DateConverter {

  public static Date toDate(String dateString){
     if(timestamp == null)
         return null;
     return new Date(dateString);
  }

  public static String toTimestamp(Date date){
      SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yy");
      return dateTimeFormat.format(date);
  }
}


来源: stackexchange

问:
Executing command using SSH.NET on digi 6030dx modem - what are this character sequences starting with left square bracket?
I have some large project that connect to many devices over SSH.NET

Now I have to add support for new modem witch is digi 6030dx.

I added it and I am able to connect with no issues

But when I send some/any command like show config the output is:

[16C[0K
[16C[0Ks
[17C[0Kh
[18C[0Ko
[19C[0Kw
[20C[0K
[20C[0Kc
[21C[0Ko
[22C[0Kn
[23C[0Kf
[24C[0Ki
[25C[0Kg

Commands
-------------------------------------------------------------------------------
config      View and modify the configuration
exit        Exit the CLI
analyzer    Analyzer commands.
cli-legacy  Enter the legacy Admin CLI.
cp          Copy a file or directory.
help        Show CLI editing and navigation commands.
ls          List a directory.
mkdir       Create a directory.
modem       Modem commands.
more        View a file.
mv          Move a file or directory.
ping        Ping a host.
reboot      Reboot the system.
rm          Remove a file or directory.
scp         Copy a file or directory over SSH.
show        Show instance statistics.
system      System commands.
traceroute  Print the route packets trace to network host.
update      Update firmware.

dra.wk.0001> ashowconfigdra.wk.0001> ashowconfig
[16C[0K
```

Does anyone known what are this strange signs / why my command is splited by this and newlines?
It is first device that have this issue and the app support over 200 other with no issues.

I guess some coding issue or something ? putty does not show this signs so probably 'understand' them somehow?

答:
i did for now

this.answer = Regex.Replace(this.answer, @"\r\[\d{0,3}C\[0K", "", RegexOptions.IgnoreCase);

will see if have any negative impact but looks perfect for now :D

ContentLicense: CC BY-SA 4.0

Body:
I have some large project that connect to many devices over SSH.NET

Now I have to add support for new modem witch is digi 6030dx.

I added it and I am able to connect with no issues

But when I send some/any command like show config the output is:

[16C[0K
[16C[0Ks
[17C[0Kh
[18C[0Ko
[19C[0Kw
[20C[0K
[20C[0Kc
[21C[0Ko
[22C[0Kn
[23C[0Kf
[24C[0Ki
[25C[0Kg

Commands
-------------------------------------------------------------------------------
config      View and modify the configuration
exit        Exit the CLI
analyzer    Analyzer commands.
cli-legacy  Enter the legacy Admin CLI.
cp          Copy a file or directory.
help        Show CLI editing and navigation commands.
ls          List a directory.
mkdir       Create a directory.
modem       Modem commands.
more        View a file.
mv          Move a file or directory.
ping        Ping a host.
reboot      Reboot the system.
rm          Remove a file or directory.
scp         Copy a file or directory over SSH.
show        Show instance statistics.
system      System commands.
traceroute  Print the route packets trace to network host.
update      Update firmware.

dra.wk.0001> ashowconfigdra.wk.0001> ashowconfig
[16C[0K

Does anyone known what are this strange signs / why my command is splited by this and newlines?
It is first device that have this issue and the app support over 200 other with no issues.

I guess some coding issue or something ? putty does not show this signs so probably 'understand' them somehow?


问:
How to generate daily/weekly/monthly/annual aggregate values from a database
I am working on an API with Django Rest Framework. I want to generate daily/weekly/monthly/annual aggregate values for total bookings that have happened.

I have added an image to give an idea of how the aggregated weekly data may look. Here is simplified model. Most of the queries I attempted failed to achieve what I wanted.

```<code>class Booking(models.Model):
    trans_date = models.DateTime(auto_now_add=True)
    amount_paid = models.DecimalField(decimal_places=2, max_digits=20)
    trans_date = models.DateField(auto_now=True)
</code>```

Here is a query I attempted;

```<code>weekly_agg = Booking.objects.annotate(week=ExtractWeek('trans_date')).values('trans_date').annotate(count=Count('id')).values('trans_date','count')
</code>```

答:
Here is the solution,you can substitute the variables appropriately for daily,weekly etc counts:</p>

```<code>from django.db.models.functions import ExtractDay,ExtractWeek,..Month,..Year
from django.db.models import Count

weekly_aggregate = Booking.objects.annotate(week=ExtractWeek('trans_date')).values('week').annotate(count=Count('id')).values('week'
,'count')

#output
<QuerySet [{'week': 3, 'count': 2}, {'week': 7, 'count': 7}, {'week': 20, 'count': 1}, {'week': 19, 'count': 1}, {'week': 1, 'count': 1}]>
</code>```

Body:
I am working on an API with Django Rest Framework. I want to generate daily/weekly/monthly/annual aggregate values for total bookings that have happened.

I have added an image to give an idea of how the aggregated weekly data may look. Here is simplified model. Most of the queries I attempted failed to achieve what I wanted.

class Booking(models.Model):
    trans_date = models.DateTime(auto_now_add=True)
    amount_paid = models.DecimalField(decimal_places=2, max_digits=20)
    trans_date = models.DateField(auto_now=True)

Here is a query I attempted;

weekly_agg = Booking.objects.annotate(week=ExtractWeek('trans_date')).values('trans_date').annotate(count=Count('id')).values('trans_date','count')

Body:
Here is the solution,you can substitute the variables appropriately for daily,weekly etc counts:

from django.db.models.functions import ExtractDay,ExtractWeek,..Month,..Year
from django.db.models import Count

weekly_aggregate = Booking.objects.annotate(week=ExtractWeek('trans_date')).values('week').annotate(count=Count('id')).values('week'
,'count')

#output
<QuerySet [{'week': 3, 'count': 2}, {'week': 7, 'count': 7}, {'week': 20, 'count': 1}, {'week': 19, 'count': 1}, {'week': 1, 'count': 1}]>


问:
How to substring one by one in one button in php?
How to substring one by one in one button in php ?
Example:
$myvar="abc";
i need one button when click 1 time=display a, click 2time display b, and click 3time
display c. click how many time ?depend on string of $myvar.

Best regards

答:
i assume the element you use to display has an id "Txt", which can be a "span" or a "div" or any other elements you like.</p>

```<code><a href="#" id="Btn">Click Me!</a>
<span id="Txt"></span>

---------------------------------------------------------------------------------------
function displayOneByOne(str) {
    var n = 0;
    var btn = document.getElementById('Btn')    //get the clickable element
    var txt = document.getElementById('Txt')    //get the area to display the character

    btn.onclick = function() {
        txt.innerHTML = str.substring(n, n + 1);
------------------------------------------------
        if (n < str.length) n++;
        else return false;
------------------------------------------------
    }
}

displayOneByOne("YOUR_STRING_HERE");
---------------------------------------------------------------------------------------
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i assume the element you use to display has an id "Txt", which can be a "span" or a "div" or any other elements you like.

<a href="#" id="Btn">Click Me!</a>
<span id="Txt"></span>

---------------------------------------------------------------------------------------
function displayOneByOne(str) {
    var n = 0;
    var btn = document.getElementById('Btn')    //get the clickable element
    var txt = document.getElementById('Txt')    //get the area to display the character

    btn.onclick = function() {
        txt.innerHTML = str.substring(n, n + 1);
------------------------------------------------
        if (n < str.length) n++;
        else return false;
------------------------------------------------
    }
}

displayOneByOne("YOUR_STRING_HERE");
---------------------------------------------------------------------------------------


问:
Generic variable and function calling in Javascript
I am trying to find a way to use generic variable and function calling. Like setting a reference in react dynamically, depending on another variable.

An vision of what I would like to get is:

```<code>ref={ref => (eval(`this.${this.props.controlId}`) = ref)}
</code>```

which would end up being something like

```<code>this.props.controlId = "myid"

ref={ref => (this.myid = ref)}
</code>```

答:
Well, you can destruct the props like:

```<code>const { controlId : myId } = this.props; // renamed to myId
ref={ref => (this[myId] = ref)} // <---here you can use it.
</code>```

In your case you can use [] notation for this:

```<code>ref={ref => (this[this.props.controlId]= ref)}
</code>```

Body:
I am trying to find a way to use generic variable and function calling. Like setting a reference in react dynamically, depending on another variable.

An vision of what I would like to get is:

ref={ref => (eval(`this.${this.props.controlId}`) = ref)}

which would end up being something like

this.props.controlId = "myid"

ref={ref => (this.myid = ref)}

Body:
Well, you can destruct the props like:

const { controlId : myId } = this.props; // renamed to myId
ref={ref => (this[myId] = ref)} // <---here you can use it.

In your case you can use [] notation for this:

ref={ref => (this[this.props.controlId]= ref)}


问:
How to I call post api in requests python?
I have an API which takes three parameter, Two are strings, while third is a file named "content".

```<code>from datetime import date

AuthToken = "xxxxxxxxxxx"
fileName = "a.txt"
FolderID = "xxxxxxxxxxx"
myfiles = {'file': ('report.xls', open('C:\\Users\\Nawaf Momin\\Desktop\\a.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
URL = "https://apidocs.zoho.com/files/v1/upload?authtoken=" + AuthToken + "&scope=docsapi"
mydata = {
    'filename': fileName,
    'fid': FolderID,
    'content': myfiles
}
r = requests.post(url=URL, data=mydata)
print(r.status_code)
print(r.text)
</code>```

for api documentation visit :https://www.zoho.com/docs/zoho-docs-api.html
its upload post api..

答:
I solved it.
myfiles = {'file': ('report.xls', open('C:\\Users\\Nawaf Momin\\Desktop\\a.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
here I sent parameter_name instead of file.
so now it looks like myfiles = {'parametername': ('report.xls', open('pathToFile', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}

Body:
I have an API which takes three parameter, Two are strings, while third is a file named "content".

from datetime import date

AuthToken = "xxxxxxxxxxx"
fileName = "a.txt"
FolderID = "xxxxxxxxxxx"
myfiles = {'file': ('report.xls', open('C:\\Users\\Nawaf Momin\\Desktop\\a.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
URL = "https://apidocs.zoho.com/files/v1/upload?authtoken=" + AuthToken + "&scope=docsapi"
mydata = {
    'filename': fileName,
    'fid': FolderID,
    'content': myfiles
}
r = requests.post(url=URL, data=mydata)
print(r.status_code)
print(r.text)

for api documentation visit :https://www.zoho.com/docs/zoho-docs-api.html
its upload post api..


问:
How can i sort multidimension array with specific name in swift?
In my json result, there is odds array. And inside of it, there will be 8 types of bet. And i want to sort the array by bet type as i want to show.  Eg. first "name": "3Way Result", second another one, third "over/under" etc..

Here is my json result from server.

```<code> {
    "success": true,
    "result": [
        {
            "league_id": 5,
            "localTeam": {"data": {}},
            "visitorTeam": {"data": {}},
            "scores": {},
            "time": {"starting_at": {},},
            "league": {"data": {"coverage": {}}},
            "odds": [
                {
                    "id": 12,
                    "name": "Over/Under",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "Over",
                                            "value": "2.00",
                                            "extra": null,
                                            "probability": "50%",
                                            "dp3": "2.000",
                                            "american": 100,
                                            "handicap": null,
                                            "total": "2.5",
                                            "winning": null,
                                            "stop": false,
                                            "bookmaker_event_id": 84922729,
                                        },
                                        {
                                            "label": "Under",
                                            "value": "1.80",
                                            "probability": "55.56%",
                                            "dp3": "1.800",

                                        }
                                    ]
                                }
                            }
                        ]
                    }
                },
                {
                    "id": 1,
                    "name": "3Way Result",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "1",
                                            "value": "2.10",
                                            "extra": null,
                                            "probability": "47.62%",
                                            "dp3": "2.100",
                                            "american": 110,

                                        },
                                        {
                                            "label": "X",
                                            "value": "3.30",
                                            "extra": null,
                                            "probability": "30.3%",
                                            "dp3": "3.300",
                                            "american": 229,

                                        },
                                        {
                                            "label": "2",
                                            "value": "3.60",

                                        }
                                    ]
                                }
                            }
                        ]
                    }
                },
                {
                    "id": 975909,
                    "name": "Correct Score",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "1:0",
                                            "value": "7.50",
                                            "extra": null,
                                            "probability": "13.33%",
                                            "dp3": "7.500",
                                            "american": 650,
                                            "factional": null,
                                            "handicap": null,
                                            "total": null,
                                            "winning": null,
                                            "stop": false,
                                            "bookmaker_event_id": 84922729,
                                            "last_update": {
                                                "date": "2020-02-20 10:59:06.746514",
                                                "timezone_type": 3,
                                                "timezone": "UTC"
                                            }
                                        },
                                        {
                                            "label": "2:0",
                                            "value": "10.00",

                                        },

                                    ]
                                }
                            }
                        ]
                    }
                },

            ],
            "tipsters": 2
        }
    ]
}
</code>```

so it is not alphabetically, datetime or anytype i could access. How could i do ?

Update: I have added model.

```<code>struct BetterMatchResults: APIModel, Codable {
    var success: Bool?
    var result: [BetterMatch]?
}
struct BetterMatch: APIModel, Codable  {
    var id,_id: String?
    var localTeam, visitorTeam: BetterTeam?
    var spId, league_id, seasonID: Int?
    var winningOddsCalculated: Bool?
    var time: BetterTime?
    var league: BetterLeague?
    var createdAt, updatedAt: String?
    var odds: [BetterOdd]!
    var resultID: String?
    var tipsters: Int?
    var stats_url: String?
}

struct BetterLeague : APIModel, Codable {
    var data: LeagueData?
}

struct LeagueData : APIModel, Codable{
    var id: Int?
    var active: Bool?
    //var legacyID, countryID: Int?
    var logo_path: String?
    var name: String?
    //var isCup: Bool?

}

struct BetterOdd : APIModel, Codable {
    var id: Int?
    var name: String?
    var suspended: Bool?
    var bookmaker: BetterBookmaker?
   }

// MARK: - Bookmaker
struct BetterBookmaker : APIModel, Codable {
    var data: [BetterBookmakerDatum]?
}

// MARK: - BookmakerDatum
struct BetterBookmakerDatum : APIModel, Codable {
    var id: Int?
    var name: String?
    var odds: BetterOdds?
}

// MARK: - Odds
struct BetterOdds : APIModel, Codable {
    var data: [BetterOddsDatum]?
}

class BetterOddsDatum: APIModel , Codable {

    var label: String?
     //var extra: NSNull?
     //var probability, dp3: String?
     var american: Int?
     //var factional, handicap: NSNull?
     var total: String?
     var winning: Bool?
     var stop: Bool?
     var bookmakerEventID: Int?
    //private var odd: Double
    public var value: String?
    init() {

    }
}
</code>```

答:
If I understand your question correctly you want to be able sort the data based on betting type but the value of betting types are not sortable if used as a String variable. The solution would be to converting them into enum types with raw values and then sorting the array based on those raw values. Here is an example:

```<code>// Create a BetType for your datas
enum BetType: Int {
  case overUnder = 0
  case threeWayResult = 1 // 3WayResult
  ...
}

// Update your BetterOdd
struct BetterOdd : APIModel, Codable {
    var id: Int?
    var name: String?
    var betType: BetType = .overUnder // or put your default value here
    var suspended: Bool?
    var bookmaker: BetterBookmaker?
   }

// Loop your BetterMatch property's odds value after fetching datas.
for i in 0..<betterMatch.odds {
   if betterMatch.odds[i].name == "over/under" {
      betterMatch.odds[i].betType = .overUnder
   }
   ... // Do the same for other types as well in else if blocks
}
</code>```

Another alternative would be to add a function for getting the type in BetterOdd

```<code>struct BetterOdd ... {
  ... // Your properties

  func getBetType() -> BetType {
    if name == "over/under" {
       return .overUnder
    } else if name == "3WayResult" {
       return .threeWayResult
    }
    ... // Other cases
  }
}
</code>```

Finnaly for sorting you can do:

```<code>let result = betterMatch.odds.sorted({ $0.betType.rawValue > $1.betType.rawValue })
// or if you used the function solution
let result = betterMatch.odds.sorted({ $0.getBetType().rawValue > $1.getBetType().rawValue })
</code>```

Since you are using a Codable approach you might need to loop the array and set the betType values based on name values.

Body:
In my json result, there is odds array. And inside of it, there will be 8 types of bet. And i want to sort the array by bet type as i want to show.  Eg. first "name": "3Way Result", second another one, third "over/under" etc..

Here is my json result from server.

 {
    "success": true,
    "result": [
        {
            "league_id": 5,
            "localTeam": {"data": {}},
            "visitorTeam": {"data": {}},
            "scores": {},
            "time": {"starting_at": {},},
            "league": {"data": {"coverage": {}}},
            "odds": [
                {
                    "id": 12,
                    "name": "Over/Under",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "Over",
                                            "value": "2.00",
                                            "extra": null,
                                            "probability": "50%",
                                            "dp3": "2.000",
                                            "american": 100,
                                            "handicap": null,
                                            "total": "2.5",
                                            "winning": null,
                                            "stop": false,
                                            "bookmaker_event_id": 84922729,
                                        },
                                        {
                                            "label": "Under",
                                            "value": "1.80",
                                            "probability": "55.56%",
                                            "dp3": "1.800",

                                        }
                                    ]
                                }
                            }
                        ]
                    }
                },
                {
                    "id": 1,
                    "name": "3Way Result",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "1",
                                            "value": "2.10",
                                            "extra": null,
                                            "probability": "47.62%",
                                            "dp3": "2.100",
                                            "american": 110,

                                        },
                                        {
                                            "label": "X",
                                            "value": "3.30",
                                            "extra": null,
                                            "probability": "30.3%",
                                            "dp3": "3.300",
                                            "american": 229,

                                        },
                                        {
                                            "label": "2",
                                            "value": "3.60",

                                        }
                                    ]
                                }
                            }
                        ]
                    }
                },
                {
                    "id": 975909,
                    "name": "Correct Score",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "1:0",
                                            "value": "7.50",
                                            "extra": null,
                                            "probability": "13.33%",
                                            "dp3": "7.500",
                                            "american": 650,
                                            "factional": null,
                                            "handicap": null,
                                            "total": null,
                                            "winning": null,
                                            "stop": false,
                                            "bookmaker_event_id": 84922729,
                                            "last_update": {
                                                "date": "2020-02-20 10:59:06.746514",
                                                "timezone_type": 3,
                                                "timezone": "UTC"
                                            }
                                        },
                                        {
                                            "label": "2:0",
                                            "value": "10.00",

                                        },

                                    ]
                                }
                            }
                        ]
                    }
                },

            ],
            "tipsters": 2
        }
    ]
}

so it is not alphabetically, datetime or anytype i could access. How could i do ?

Update: I have added model.

struct BetterMatchResults: APIModel, Codable {
    var success: Bool?
    var result: [BetterMatch]?
}
struct BetterMatch: APIModel, Codable  {
    var id,_id: String?
    var localTeam, visitorTeam: BetterTeam?
    var spId, league_id, seasonID: Int?
    var winningOddsCalculated: Bool?
    var time: BetterTime?
    var league: BetterLeague?
    var createdAt, updatedAt: String?
    var odds: [BetterOdd]!
    var resultID: String?
    var tipsters: Int?
    var stats_url: String?
}

struct BetterLeague : APIModel, Codable {
    var data: LeagueData?
}

struct LeagueData : APIModel, Codable{
    var id: Int?
    var active: Bool?
    //var legacyID, countryID: Int?
    var logo_path: String?
    var name: String?
    //var isCup: Bool?

}

struct BetterOdd : APIModel, Codable {
    var id: Int?
    var name: String?
    var suspended: Bool?
    var bookmaker: BetterBookmaker?
   }

// MARK: - Bookmaker
struct BetterBookmaker : APIModel, Codable {
    var data: [BetterBookmakerDatum]?
}

// MARK: - BookmakerDatum
struct BetterBookmakerDatum : APIModel, Codable {
    var id: Int?
    var name: String?
    var odds: BetterOdds?
}

// MARK: - Odds
struct BetterOdds : APIModel, Codable {
    var data: [BetterOddsDatum]?
}

class BetterOddsDatum: APIModel , Codable {

    var label: String?
     //var extra: NSNull?
     //var probability, dp3: String?
     var american: Int?
     //var factional, handicap: NSNull?
     var total: String?
     var winning: Bool?
     var stop: Bool?
     var bookmakerEventID: Int?
    //private var odd: Double
    public var value: String?
    init() {

    }
}

Body:
If I understand your question correctly you want to be able sort the data based on betting type but the value of betting types are not sortable if used as a String variable. The solution would be to converting them into enum types with raw values and then sorting the array based on those raw values. Here is an example:

// Create a BetType for your datas
enum BetType: Int {
  case overUnder = 0
  case threeWayResult = 1 // 3WayResult
  ...
}

// Update your BetterOdd
struct BetterOdd : APIModel, Codable {
    var id: Int?
    var name: String?
    var betType: BetType = .overUnder // or put your default value here
    var suspended: Bool?
    var bookmaker: BetterBookmaker?
   }

// Loop your BetterMatch property's odds value after fetching datas.
for i in 0..<betterMatch.odds {
   if betterMatch.odds[i].name == "over/under" {
      betterMatch.odds[i].betType = .overUnder
   }
   ... // Do the same for other types as well in else if blocks
}

Another alternative would be to add a function for getting the type in BetterOdd

struct BetterOdd ... {
  ... // Your properties

  func getBetType() -> BetType {
    if name == "over/under" {
       return .overUnder
    } else if name == "3WayResult" {
       return .threeWayResult
    }
    ... // Other cases
  }
}

Finnaly for sorting you can do:

let result = betterMatch.odds.sorted({ $0.betType.rawValue > $1.betType.rawValue })
// or if you used the function solution
let result = betterMatch.odds.sorted({ $0.getBetType().rawValue > $1.getBetType().rawValue })

Since you are using a Codable approach you might need to loop the array and set the betType values based on name values.


问:
Why doesn't C# have support for first pass exception filtering?
Note: this is not a duplicate of Jeff's question.

That question asked "Is an equivalent?" I know there isn't, and I want to know why!

The reason I ask is that I've only just become clear on how important it is, and the conclusion seems very strange to me.

The Exception Handling block of Microsoft's Enterprise Library advises us to use this pattern:

```<code>catch (Exception x)
{
    if (ExceptionPolicy.HandleException(x, ExceptionPolicies.MyPolicy))
        throw;

    // recover from x somehow
}
</code>```

The policy is defined in an XML file, so that means that if a customer has an issue, we can modify the policy to assist with tracking down (or perhaps papering over) the problem to give them a fast resolution until we deal with it properly - which may involve arguing with 3rd parties, about whose fault it all is.

This is basically an acknowledgement of the simple fact that in real applications the number of exception types and their "recoverability" status is practically impossible to manage without a facility like this.

Meanwhile, the CLR team at MS says this is not an option, and it turns out those guys know what they're talking about! The problem is that right before the catch block runs, any finally blocks nested inside the try block will be executed. So those finally blocks may do any of the following:

Harmlessly modify the program state (phew, lucky).

Trash something important in the customer's data, because the program state is screwed up to an unknown degree.

Disguise or destroy important evidence that we need to diagnose an issue - especially if we're talking about calls into native code.

Throw another exception, adding to the general confusion and misery.

Note that the using statement and C++/CLI destructors are built on try/finally, so they're affected too.

So clearly the catch/throw pattern for filtering exceptions is no good. What is actually needed is a way to filter exceptions, via a policy, without actually catching them and so triggering the execution of finally blocks, unless we find a policy that tells us the exception is safe to recover from.

The CLR team blogged about this recently:

Catch, Rethrow and Filters - Why should you care?

Why catch(Exception)/empty catch is bad

The outcome is that we have to write a helper function in VB.NET to allow us to access this vital capability from C#. The big clue that there is a problem is that there is code in the BCL that does this. Lots of people have blogged about doing it, but they rarely if ever mention the thing about try/finally blocks, which is the killer.

What I would like to know is:

Are there any public statements or direct emails people have received from the C# team on this subject?

Are there any existing Microsoft Connect suggestions asking for this? I've heard rumours of them but none of the likely keywords turned up anything.

Update: as noted above, I have already searched on Microsoft Connect without finding anything. I have also (unsurprisingly) Googled. I've only found people explaining why they need this feature, or pointing out the advantages of it in VB.NET, or fruitlessly hoping that it will be added in a future version of C#, or working around it, And plenty of misleading advice. But no statement on the rationale for omitting it from all current versions of C#. And the reason I'm asking about existing Connect issues is so that (a) I don't create an unnecessary duplicate and (b) I can tell interested people if I have to create one.

Update 2: Found an interesting old blog post from Eric Gunnerson, formerly of the C# team:

"Yes, being able to put a condition on
  a catch is somewhat more convenient
  than having to write the test
  yourself, but it doesn't really enable
  you to do anything new."

That was the same assumption I had until it was properly explained to me!

答:
In regards to the first question, if there was a public statement, then it was more than likely put on the web somewhere, in which case, Google should turn up something (if it exists).

If it is a direct email with the C# team, then it is more than likely that it is under NDA, so it wouldn't be able to be published anyways.

With the second question, there is a search capability on Microsoft Connect which they prompt you to use before entering a new suggestion.  If you can't find it, then there probably isn't one.

My recommendation would be to put a suggestion in, and then promote it to get others to weigh in on it.

OwnerDisplayName: Earwicker

ContentLicense: CC BY-SA 2.5

Body:
Note: this is not a duplicate of Jeff's question.

That question asked "Is an equivalent?" I know there isn't, and I want to know why!

The reason I ask is that I've only just become clear on how important it is, and the conclusion seems very strange to me.

The Exception Handling block of Microsoft's Enterprise Library advises us to use this pattern:

catch (Exception x)
{
    if (ExceptionPolicy.HandleException(x, ExceptionPolicies.MyPolicy))
        throw;

    // recover from x somehow
}

The policy is defined in an XML file, so that means that if a customer has an issue, we can modify the policy to assist with tracking down (or perhaps papering over) the problem to give them a fast resolution until we deal with it properly - which may involve arguing with 3rd parties, about whose fault it all is.

This is basically an acknowledgement of the simple fact that in real applications the number of exception types and their "recoverability" status is practically impossible to manage without a facility like this.

Meanwhile, the CLR team at MS says this is not an option, and it turns out those guys know what they're talking about! The problem is that right before the catch block runs, any finally blocks nested inside the try block will be executed. So those finally blocks may do any of the following:

Harmlessly modify the program state (phew, lucky).

Trash something important in the customer's data, because the program state is screwed up to an unknown degree.

Disguise or destroy important evidence that we need to diagnose an issue - especially if we're talking about calls into native code.

Throw another exception, adding to the general confusion and misery.

Note that the using statement and C++/CLI destructors are built on try/finally, so they're affected too.

So clearly the catch/throw pattern for filtering exceptions is no good. What is actually needed is a way to filter exceptions, via a policy, without actually catching them and so triggering the execution of finally blocks, unless we find a policy that tells us the exception is safe to recover from.

The CLR team blogged about this recently:

Catch, Rethrow and Filters - Why should you care?

Why catch(Exception)/empty catch is bad

The outcome is that we have to write a helper function in VB.NET to allow us to access this vital capability from C#. The big clue that there is a problem is that there is code in the BCL that does this. Lots of people have blogged about doing it, but they rarely if ever mention the thing about try/finally blocks, which is the killer.

What I would like to know is:

Are there any public statements or direct emails people have received from the C# team on this subject?

Are there any existing Microsoft Connect suggestions asking for this? I've heard rumours of them but none of the likely keywords turned up anything.

Update: as noted above, I have already searched on Microsoft Connect without finding anything. I have also (unsurprisingly) Googled. I've only found people explaining why they need this feature, or pointing out the advantages of it in VB.NET, or fruitlessly hoping that it will be added in a future version of C#, or working around it, And plenty of misleading advice. But no statement on the rationale for omitting it from all current versions of C#. And the reason I'm asking about existing Connect issues is so that (a) I don't create an unnecessary duplicate and (b) I can tell interested people if I have to create one.

Update 2: Found an interesting old blog post from Eric Gunnerson, formerly of the C# team:

"Yes, being able to put a condition on
  a catch is somewhat more convenient
  than having to write the test
  yourself, but it doesn't really enable
  you to do anything new."

That was the same assumption I had until it was properly explained to me!

LastEditorDisplayName: Earwicker

OwnerDisplayName: casperOne


问:
How would I remove non-duplicates from a CSV file in Python?
I have a CSV file with the following format:

```<code>User1, User2
1,2
1,3
2,1
</code>```

I am trying to remove the non-duplicated reverse values, so in this instance I would like to remove 1,3 as it doesn't have a reverse duplicate of 3,1

I currently have this script which removes the duplicate values:

```<code>import csv

reader=csv.reader(open('facebook-friendships.csv', 'r'), delimiter=',')
writer=csv.writer(open('facebook-friendships-write.csv', 'w'), delimiter=',')

entries = set()

for row in reader:
   key = (row[0], row[1])
   key = tuple(key)
   if key in entries and key[::-1] in entries:
       writer.writerow(row)
       entries.add(key)
</code>```

How would I edit this script to remove the non-duplicated reverse values? So that I am only left with

```<code>1,2
2,1
</code>```

Thanks

答:
You could simply loop through each row and check whether a particular row's reverse exists or not. If yes, then it is written in the same sequence as present in the original csv file. Advantage being the original sequence is maintained.</p>

```<code>import csv

reader=csv.reader(open('facebook-friendships.csv', 'r'), delimiter=',')
writer=csv.writer(open('facebook-friendships-write.csv', 'w'), delimiter=',')

allRows = []
for row in reader:
    allRows.append(row)
for i in range(len(allRows)):
    for j in range(len(allRows)):
        #Checking whether or not the index is same.
        #If index is same then there's no need to check the value at that particular index.
        if i!=j:
            if allRows[i]==allRows[j] or allRows[i][::-1]==allRows[j]:
                writer.writerow(tuple(allRows[i]))
</code>```

Body:
I have a CSV file with the following format:

User1, User2
1,2
1,3
2,1

I am trying to remove the non-duplicated reverse values, so in this instance I would like to remove 1,3 as it doesn't have a reverse duplicate of 3,1

I currently have this script which removes the duplicate values:

import csv

reader=csv.reader(open('facebook-friendships.csv', 'r'), delimiter=',')
writer=csv.writer(open('facebook-friendships-write.csv', 'w'), delimiter=',')

entries = set()

for row in reader:
   key = (row[0], row[1])
   key = tuple(key)
   if key in entries and key[::-1] in entries:
       writer.writerow(row)
       entries.add(key)

How would I edit this script to remove the non-duplicated reverse values? So that I am only left with

1,2
2,1

Thanks

Body:
You could simply loop through each row and check whether a particular row's reverse exists or not. If yes, then it is written in the same sequence as present in the original csv file. Advantage being the original sequence is maintained.

import csv

reader=csv.reader(open('facebook-friendships.csv', 'r'), delimiter=',')
writer=csv.writer(open('facebook-friendships-write.csv', 'w'), delimiter=',')

allRows = []
for row in reader:
    allRows.append(row)
for i in range(len(allRows)):
    for j in range(len(allRows)):
        #Checking whether or not the index is same.
        #If index is same then there's no need to check the value at that particular index.
        if i!=j:
            if allRows[i]==allRows[j] or allRows[i][::-1]==allRows[j]:
                writer.writerow(tuple(allRows[i]))


问:
Laravel: Display data using drop down list
I am implementing a drop down menu list to display a list of hotels from my system. I currently have the following code which when i click submit, nothing is happening (no data displayed).

Does anyone know how i can potentially display data once i press submit. I do believe i need code in my controller.

SEARCH.BLADE.PHP

```<code><form action="/search" method="POST" role="search">
   <div class="form-group">
    <select name="country" id="country" class="form-control input-lg dynamic" data-dependent="state">
 @foreach($posts as $post)
  <option value="{{$post->distance}}">{{$post->distance}} </option>
 @endforeach

   <br/>
   <div class="form-group">
    <select name="state" id="state" class="form-control input-lg dynamic" data-dependent="city">
    </select>
   </div>
   <br />
   <div class="form-group">
    <select name="city" id="city" class="form-control input-lg">
    @foreach($posts as $post)
  <option value="{{$post->title}}">{{$post->title}} </option>
 @endforeach
</div>
    </select>
   </div>
  </div>
  {{Form::Submit('submit', ['class' => 'btn btn-primary'])}}
 </body>
</code>```

SearchController.php

```<code>class SearchController extends Controller {
   public function index()
   {
     $posts = Post::all();
     return view('Pages.search')->with('posts', $posts);
   }
</code>```

I do not have much is the search controller but i do believe i need some code in there to display the data.

答:
Use this

```<code><form action="/search" method="POST" role="search">

<div class="form-group">

<select name="country" id="country" class="form-control input-lg dynamic" data-dependent="state">

@foreach($posts as $post)
   <option value="{{$post->id}}">{{$post->title}} </option>
@endforeach

</select>
</div>

<div class="form-group">

<select name="city" id="city" class="form-control input-lg">

@foreach($posts as $post)
  <option value="{{$post->id}}">{{$post->title}} </option>
@endforeach

</select>
</div>

<div class="form-group">

<button type="submit" class="btn btn-adminsqure pull-right submitbutton"> Submit</button>

</div>
</code>```

Also change in your controller

```<code>class SearchController extends Controller {

  public function index()
  {
    $posts = Post::get();
    return view('Pages.search', compact('posts'));
  }
</code>```

Body:
I am implementing a drop down menu list to display a list of hotels from my system. I currently have the following code which when i click submit, nothing is happening (no data displayed).

Does anyone know how i can potentially display data once i press submit. I do believe i need code in my controller.

SEARCH.BLADE.PHP

<form action="/search" method="POST" role="search">

    <select name="country" id="country" class="form-control input-lg dynamic" data-dependent="state">
 @foreach($posts as $post)
  <option value="{{$post->distance}}">{{$post->distance}} </option>
 @endforeach

    <select name="state" id="state" class="form-control input-lg dynamic" data-dependent="city">
    </select>

    <select name="city" id="city" class="form-control input-lg">
    @foreach($posts as $post)
  <option value="{{$post->title}}">{{$post->title}} </option>
 @endforeach

    </select>

  {{Form::Submit('submit', ['class' => 'btn btn-primary'])}}

SearchController.php

class SearchController extends Controller {
   public function index()
   {
     $posts = Post::all();
     return view('Pages.search')->with('posts', $posts);
   }

I do not have much is the search controller but i do believe i need some code in there to display the data.

Body:
Use this

<form action="/search" method="POST" role="search">

<div class="form-group">

<select name="country" id="country" class="form-control input-lg dynamic" data-dependent="state">

@foreach($posts as $post)
   <option value="{{$post->id}}">{{$post->title}} </option>
@endforeach

</select>
</div>

<div class="form-group">

<select name="city" id="city" class="form-control input-lg">

@foreach($posts as $post)
  <option value="{{$post->id}}">{{$post->title}} </option>
@endforeach

</select>
</div>

<div class="form-group">

<button type="submit" class="btn btn-adminsqure pull-right submitbutton"> Submit</button>

</div>

Also change in your controller

class SearchController extends Controller {

  public function index()
  {
    $posts = Post::get();
    return view('Pages.search', compact('posts'));
  }


问:
Secure Elasticsearch installation retrospectively
I have an Elasticsearch installation (V7.3.2). Is it possible to secure this retrospectively? This link states that a password can only be set "during the initial configuration of the Elasticsearch". Basically, I require consumers of the restful API to provide a password (?) going forward.</p>

答:
The elastic bootstrap password is used to init the internal/reserved users used by the components or features of the elastic stack (kibana, logstash, beats, monitoring, ...).

If you want to secure the API, you need to create users/roles for your scenario on top.

Please use TLS in your cluster when handling with passwords and don't expose the cluster directly for security reasons.

Here are all informations regarding a secure cluster including some tutorials: https://www.elastic.co/guide/en/elasticsearch/reference/7.3/secure-cluster.html

EDIT: Added links as requested. Feel free to raise a new question here at SO if you're facing serious problems!


问:
How do I determine whether the program was built as 32 bit or 64 bit in Go?
The closest I can get is runtime.GOARCH, but that might also give arm, which could be either 32 or 64 bit.

I only care how this program was built, not whether the OS also supports 64-bit executables.  e.g. for ARM mode on an AArch64 CPU or 32-bit compat mode on an x86-64 CPU, I still want 32 because that's the mode this program is running in.

Related: Detect OS x86 or x64, when compiled as x86 in GO is about detecting what the OS supports, e.g. for maybe running a differently-compiled executable.

答:
const is64Bit = uint64(^uintptr(0)) == ^uint64(0)
```

This works because if uintptr is 32 bits, ^uintptr(0) will be 0xffffffff rather than 0xffffffffffffffff.

^uint64(0) will always be 0xffffffffffffffff regardless of 32 or 64 bit architectures.

Body:
const is64Bit = uint64(^uintptr(0)) == ^uint64(0)

This works because if uintptr is 32 bits, ^uintptr(0) will be 0xffffffff rather than 0xffffffffffffffff.

^uint64(0) will always be 0xffffffffffffffff regardless of 32 or 64 bit architectures.


问:
How Can i Show Location with Marker on Map using longitude & latitude From Firestore Collection?
I had Stored longitude & latitude in Firestore Collection, How can i display location on Map using longitude & latitude

Following is what I tried :

```<code>@Override
public void onMapReady(final GoogleMap googleMap) {
    MapsInitializer.initialize(getContext());
    mGoogleMap = googleMap;

    collectionReference.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            googleMap.addMarker(new MarkerOptions().position(new LatLng(18.5204, 73.8567)).title("pune"));
            CameraPosition cameraPosition = CameraPosition.builder().target(new LatLng(18.5204, 73.8567)).zoom(16).bearing(0).tilt(45).build();

        }
    });
}
</code>```

答:
You have to retrieve latitude and longitude from QuerySnapshot and then need to add this to marker. Check below:

```<code>@Override
public void onMapReady(final GoogleMap googleMap) {
    ....

    FirebaseFirestore mDatabase = FirebaseFirestore.getInstance();
    CollectionReference mOrderRef = mDatabase.collection("Job Post1");

    mOrderRef.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            for(QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
                if(documentSnapshot.contains("lat") && documentSnapshot.contains("lon")) {
                    String lat = (String) documentSnapshot.get("lat");
                    String lon = (String) documentSnapshot.get("lon");
                    String title = (String) documentSnapshot.get("title");

                    if(lat != null && lon != null && !lat.isEmpty() && !lon.isEmpty()) {
                        double latitude = Double.parseDouble(lat.trim());
                        double longitude = Double.parseDouble(lon.trim());

                        LatLng latLng = new LatLng(latitude, longitude);
                        googleMap.addMarker(new MarkerOptions().position(latLng).title(title));
                    }
                }
            }
        }
    });
}
</code>```

Body:
I had Stored longitude & latitude in Firestore Collection, How can i display location on Map using longitude & latitude

Following is what I tried :

@Override
public void onMapReady(final GoogleMap googleMap) {
    MapsInitializer.initialize(getContext());
    mGoogleMap = googleMap;

    collectionReference.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            googleMap.addMarker(new MarkerOptions().position(new LatLng(18.5204, 73.8567)).title("pune"));
            CameraPosition cameraPosition = CameraPosition.builder().target(new LatLng(18.5204, 73.8567)).zoom(16).bearing(0).tilt(45).build();

        }
    });
}

Body:
You have to retrieve latitude and longitude from QuerySnapshot and then need to add this to marker. Check below:

@Override
public void onMapReady(final GoogleMap googleMap) {
    ....

    FirebaseFirestore mDatabase = FirebaseFirestore.getInstance();
    CollectionReference mOrderRef = mDatabase.collection("Job Post1");

    mOrderRef.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            for(QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
                if(documentSnapshot.contains("lat") && documentSnapshot.contains("lon")) {
                    String lat = (String) documentSnapshot.get("lat");
                    String lon = (String) documentSnapshot.get("lon");
                    String title = (String) documentSnapshot.get("title");

                    if(lat != null && lon != null && !lat.isEmpty() && !lon.isEmpty()) {
                        double latitude = Double.parseDouble(lat.trim());
                        double longitude = Double.parseDouble(lon.trim());

                        LatLng latLng = new LatLng(latitude, longitude);
                        googleMap.addMarker(new MarkerOptions().position(latLng).title(title));
                    }
                }
            }
        }
    });
}


问:
ElasticSearch NEST searchresponse.hits data not populated
I have an index in ElasticSearch. I have setup an ASP.NET core lambda serverless app. I inject IElasticClient into my controller.

I want my controller to be signed as public IEnumerable<StreamSummary> Get() and the ElasticSearch query I would have thought to be as as simple as return searchResponse.Hits.Select(h => h.Source).ToList(); but this is not the case as can be seen below.

I query my Index with something basic like this

```<code>var searchResponse = elasticClient.Search<StreamSummary>(s => s
                .Index("myindex")
                .Query(q => q.MatchAll()
                )
            );
</code>```

When I log how many "hits" I get, it is the correct amount (searchResponse.Hits.Count).

When I set my controller  return IEnumerable<StreamSummary> and use searchResponse.Hits.Select(h => h.Source).ToList() the list is the correct number but every entry has no values. DateTime fields are all Datetime.Min strings are empty, nullables are null. It's basically an empty/freshly instantiated class and not populated/serialised as I would have expected it to be.

When I iterate the hits and display/log Index,Type and Id, this all works and displays exactly as I expect. The Issue I am having is with _source (Source Property NEST).

```<code>foreach (var searchResponseHit in searchResponse.Hits)
                    {
                        hits.Add(searchResponseHit.Index);
                        hits.Add(searchResponseHit.Type);
                        hits.Add(searchResponseHit.Id); searchResponseHit.Source
                    searchResponseHit.Source // here is the problem, no populated StreamSummary data}
</code>```

Where hits is List<string> hits = new List<string>();

So I dig a bit further and in my Startup.cs I DisableDirectStreaming() on ConnectionSettings() so I can get at the request/response buffered byte streams.

I then do the following:

```<code>var requestJson = System.Text.Encoding.UTF8.GetString(searchResponse.ApiCall.RequestBodyInBytes);
                    var responseJson = System.Text.Encoding.UTF8.GetString(searchResponse.ApiCall.ResponseBodyInBytes);
                    return searchResponse.ApiCall.HttpMethod.ToString() + searchResponse.ApiCall.Uri + "\n" + requestJson + "\r\n" + responseJson;
</code>```

This is an inccomplete/part response but as you can see it contains a lot of escape characters etc. (Could this be part of the problem, a serialisation issue??)

```<code>\"hits\" : {\n    \"total\" : {\n      \"value\" : 9,\n      \"relation\" : \"eq\"\n    },\n    \"max_score\" : 1.0,\n    \"hits\" : [\n      {\n        \"_index\" : \"accounts\",\n        \"_type\" : \"_doc\",\n        \"_id\" : \"U3P 1 8fb4b770-4e29-4f0d-aec8-1bcd4199005f\",\n        \"_score\" : 1.0,\n        \"_source\" : {\n          \"ProcessingResponse\" : \"Success\",\n          \"ProviderId\" : 6,\n
</code>```

Connection/Client:

```<code> var uri = new Uri(Configuration["ElasticSearch:Url"]);
        var httpConnection = new AwsHttpConnection(new BasicAWSCredentials(Configuration["AWS:AwsAccessKeyId"], Configuration["AWS:AwsSecretAccessKey"]),
            RegionEndpoint.GetBySystemName(Configuration["ElasticSearch:Region"]));
        var pool = new SingleNodeConnectionPool(uri);
        var config = new ConnectionSettings(pool, httpConnection).DefaultIndex(Startup.ElasticSearchIndex)
            .DisableDirectStreaming().PrettyJson();
        var elasticClient = new ElasticClient(config);
        services.AddSingleton<IElasticClient>(elasticClient);
</code>```

POCO is:

```<code>public class StreamSummary : ResponseSummary
{
    public string Type { get; set; }
    public int? ProviderId { get; set; }
    public string ProviderAccount { get; set; }
    public int? ProcessingTime { get; set; }
    public DateTime ProcessedTimeUtc { get; set; }
}
</code>```

where Response Summary Contains a couple of nullable decimals(but also has an IList<AnotherClass>)

Help Appreciated.

答:
If I'm not mistaken, this is what you're after:</p>

```<code>searchResponse.Documents
</code>```

Body:
I have an index in ElasticSearch. I have setup an ASP.NET core lambda serverless app. I inject IElasticClient into my controller.

I want my controller to be signed as public IEnumerable<StreamSummary> Get() and the ElasticSearch query I would have thought to be as as simple as return searchResponse.Hits.Select(h => h.Source).ToList(); but this is not the case as can be seen below.

I query my Index with something basic like this

var searchResponse = elasticClient.Search<StreamSummary>(s => s
                .Index("myindex")
                .Query(q => q.MatchAll()
                )
            );

When I log how many "hits" I get, it is the correct amount (searchResponse.Hits.Count).

When I set my controller  return IEnumerable<StreamSummary> and use searchResponse.Hits.Select(h => h.Source).ToList() the list is the correct number but every entry has no values. DateTime fields are all Datetime.Min strings are empty, nullables are null. It's basically an empty/freshly instantiated class and not populated/serialised as I would have expected it to be.

When I iterate the hits and display/log Index,Type and Id, this all works and displays exactly as I expect. The Issue I am having is with _source (Source Property NEST).

foreach (var searchResponseHit in searchResponse.Hits)
                    {
                        hits.Add(searchResponseHit.Index);
                        hits.Add(searchResponseHit.Type);
                        hits.Add(searchResponseHit.Id); searchResponseHit.Source
                    searchResponseHit.Source // here is the problem, no populated StreamSummary data}

Where hits is List<string> hits = new List<string>();

So I dig a bit further and in my Startup.cs I DisableDirectStreaming() on ConnectionSettings() so I can get at the request/response buffered byte streams.

I then do the following:

var requestJson = System.Text.Encoding.UTF8.GetString(searchResponse.ApiCall.RequestBodyInBytes);
                    var responseJson = System.Text.Encoding.UTF8.GetString(searchResponse.ApiCall.ResponseBodyInBytes);
                    return searchResponse.ApiCall.HttpMethod.ToString() + searchResponse.ApiCall.Uri + "\n" + requestJson + "\r\n" + responseJson;

This is an inccomplete/part response but as you can see it contains a lot of escape characters etc. (Could this be part of the problem, a serialisation issue??)

\"hits\" : {\n    \"total\" : {\n      \"value\" : 9,\n      \"relation\" : \"eq\"\n    },\n    \"max_score\" : 1.0,\n    \"hits\" : [\n      {\n        \"_index\" : \"accounts\",\n        \"_type\" : \"_doc\",\n        \"_id\" : \"U3P 1 8fb4b770-4e29-4f0d-aec8-1bcd4199005f\",\n        \"_score\" : 1.0,\n        \"_source\" : {\n          \"ProcessingResponse\" : \"Success\",\n          \"ProviderId\" : 6,\n

Connection/Client:

 var uri = new Uri(Configuration["ElasticSearch:Url"]);
        var httpConnection = new AwsHttpConnection(new BasicAWSCredentials(Configuration["AWS:AwsAccessKeyId"], Configuration["AWS:AwsSecretAccessKey"]),
            RegionEndpoint.GetBySystemName(Configuration["ElasticSearch:Region"]));
        var pool = new SingleNodeConnectionPool(uri);
        var config = new ConnectionSettings(pool, httpConnection).DefaultIndex(Startup.ElasticSearchIndex)
            .DisableDirectStreaming().PrettyJson();
        var elasticClient = new ElasticClient(config);
        services.AddSingleton<IElasticClient>(elasticClient);

POCO is:

public class StreamSummary : ResponseSummary
{
    public string Type { get; set; }
    public int? ProviderId { get; set; }
    public string ProviderAccount { get; set; }
    public int? ProcessingTime { get; set; }
    public DateTime ProcessedTimeUtc { get; set; }
}

where Response Summary Contains a couple of nullable decimals(but also has an IList<AnotherClass>)

Help Appreciated.

Body:
If I'm not mistaken, this is what you're after:

searchResponse.Documents


问:
How to get variable from public function to another function?
Hey guys I am trying to figure something out for my streaming site. The only thing I need is that one variable out of another function.

I need to get the $vsurl from the method ajax() to another (public static function).
I tried return and global but I get the error:

Fatal error: Uncaught Error: Call to undefined function ajax()

for example with global it would be:

```<code>public function ajax(){
    global $vsurl;
    if($post_id && $play_nm){
        // Get post meta
        switch ($post_ty) {
            case 'movie'
                $vsurl = $this->checkForMovie1( $postmeta );
                break;
            case 'tv':
                $vsurl = $this->checkTv1( $postmeta );
                break;
        }
</code>```

And then I would write ajax(); where I needed the variable. I left a few lines of code out, because they are for sure not the problem. This is where I am calling it to. Heres the full code: http://txt.do/16gsl

```<code>public static function viewer($post, $type, $players, $trailer, $size, $views, $ads = false, $image = false){
    ajax();
    $html .="<h2>".__d('<a href="//videospider.in/getvideo?key=idlIJqJKfi8VzbQT'.$vsurl.'">Alternative Player</a>')." <span id='playernotice' data-text='{$views}'>{$views}</span></h2>"
</code>```

I am a coding noob so it could be the simplest mistake ever.

答:
The error tells you that ajax is undefined. Since you try to use it from a static function, this is the expected behavior. You have a class, which has static functions and instance-level functions. static functions are the abilities of the class, instance functions are the abilities of instances of the class. You cannot call instance-level functions from a static function in the manner of

```<code>$this->ajax()
</code>```

because static functions are agnostic to instances. You can make ajax static and then the other static function will see it via self::ajax() (assuming they are in the same class). Or, you can make the other function instance-level by removing the keyword static before its name, so it will see ajax from the other function, again, assuming that they are in the same class.

You can do somehing of the like of

```<code>$vsurl = $this->ajax();
</code>```

assuming that you are in an instance-level context and that ajax ends with

```<code>return $vsurl;
</code>```

You do not need global, it's an anti-pattern. You can work with global, nothing stops you, but it's an approach frequently frowned upon.

EDIT

You attempt to call ajax in the form of

```<code>ajax();
</code>```

in your static method. This is incorrect, because your ajax function is not a standard function, you need to specify the instance or class this function belongs to, try the following:

```<code>public function viewer($post, $type, $players, $trailer, $size, $views, $ads = false, $image = false){
    $vsurl = $this->ajax();
    //Make sure that $html is properly initialized
    $html .="<h2>".__d('<a href="//videospider.in/getvideo?key=idlIJqJKfi8VzbQT'.$vsurl.'">Alternative Player</a>')." <span id='playernotice' data-text='{$views}'>{$views}</span></h2>";
}
</code>```

and make sure that the value is returned:

```<code>public function ajax(){
    $vsurl = "some default value";
    if($post_id && $play_nm){
        // Get post meta
        switch ($post_ty) {
            case 'movie'
                $vsurl = $this->checkForMovie1( $postmeta );
                break;
            case 'tv':
                $vsurl = $this->checkTv1( $postmeta );
                break;
        }
    }
    return $vsurl;
}
</code>```

and remember to instantiate your class before you call viewer.

Body:
Hey guys I am trying to figure something out for my streaming site. The only thing I need is that one variable out of another function.

I need to get the $vsurl from the method ajax() to another (public static function).
I tried return and global but I get the error:

Fatal error: Uncaught Error: Call to undefined function ajax()

for example with global it would be:

public function ajax(){
    global $vsurl;
    if($post_id && $play_nm){
        // Get post meta
        switch ($post_ty) {
            case 'movie'
                $vsurl = $this->checkForMovie1( $postmeta );
                break;
            case 'tv':
                $vsurl = $this->checkTv1( $postmeta );
                break;
        }

And then I would write ajax(); where I needed the variable. I left a few lines of code out, because they are for sure not the problem. This is where I am calling it to. Heres the full code: http://txt.do/16gsl

public static function viewer($post, $type, $players, $trailer, $size, $views, $ads = false, $image = false){
    ajax();
    $html .="
".__d('Alternative Player')." {$views}
"

I am a coding noob so it could be the simplest mistake ever.

Body:
The error tells you that ajax is undefined. Since you try to use it from a static function, this is the expected behavior. You have a class, which has static functions and instance-level functions. static functions are the abilities of the class, instance functions are the abilities of instances of the class. You cannot call instance-level functions from a static function in the manner of

$this->ajax()

because static functions are agnostic to instances. You can make ajax static and then the other static function will see it via self::ajax() (assuming they are in the same class). Or, you can make the other function instance-level by removing the keyword static before its name, so it will see ajax from the other function, again, assuming that they are in the same class.

You can do somehing of the like of

$vsurl = $this->ajax();

assuming that you are in an instance-level context and that ajax ends with

return $vsurl;

You do not need global, it's an anti-pattern. You can work with global, nothing stops you, but it's an approach frequently frowned upon.

EDIT

You attempt to call ajax in the form of

ajax();

in your static method. This is incorrect, because your ajax function is not a standard function, you need to specify the instance or class this function belongs to, try the following:

public function viewer($post, $type, $players, $trailer, $size, $views, $ads = false, $image = false){
    $vsurl = $this->ajax();
    //Make sure that $html is properly initialized
    $html .="<h2>".__d('<a href="//videospider.in/getvideo?key=idlIJqJKfi8VzbQT'.$vsurl.'">Alternative Player</a>')." <span id='playernotice' data-text='{$views}'>{$views}</span></h2>";
}

and make sure that the value is returned:

public function ajax(){
    $vsurl = "some default value";
    if($post_id && $play_nm){
        // Get post meta
        switch ($post_ty) {
            case 'movie'
                $vsurl = $this->checkForMovie1( $postmeta );
                break;
            case 'tv':
                $vsurl = $this->checkTv1( $postmeta );
                break;
        }
    }
    return $vsurl;
}

and remember to instantiate your class before you call viewer.


问:
Haskell eagerly evaluates trace when there are constant values in lambda?
I was playing around with Continuation Passing Style with Haskell, and wrote the following:

import Debug.Trace

maxcps xx k = aux xx k
  where aux [] k' = trace (show "Base case") k' 0
        aux (1:xs) k' = k 1
        aux (x:xs) k' = aux xs (\res -> k' (trace ((show xs) ++ " and " ++ show res) (max x res) ))

main :: IO()
main = maxcps [2,3,4,5] print
```

<p>That yields the following:</p>

```"Base case"
[] and 0
[5] and 5
[4,5] and 5
[3,4,5] and 5
```

<p>Which is the order I would expect (I think?) based on the fact that the continuations should get called in reverse order starting from the base case, unwinding from there.</p>

<p>However, if I just modify it ever so slightly to, say, instead of <code>show res</code> I change it to some constant like <code>show 1</code> as seen here:</p>

```trace ((show xs) ++ " and " ++ show "Hello!")
```

<p>Then I get the opposite order being printed:</p>

```"Base case"
[3,4,5] and 1
[4,5] and 1
[5] and 1
[] and 1
```

I'nm confused on why this is happening—I would expect the first result since in a language like JavaScript, nesting callbacks will defer the execution of console.log statements until the body of the callback is run, but here it seems like in the second case it prints immediately as the recursive calls get made (so the lambda expression hasn't even been called yet). Is this a correct observation, and what's happening exactly to cause this behavior?

答:
This is tricky to explain, but is a consequence of laziness.

When \res -> ... is called, res is not fully evaluated, yet, but is an unevaluated expression involving some trace calls. When you use trace (.... ++ show res) you force res to be evaluated, triggering the trace calls it has inside, which are printed before the outer traces.

In other words, the evaluation of

```<code>trace ((show xs) ++ " and " ++ show res) (max x res)
</code>```

performs, usually in order:

the (full) evalution of xs

the evaluation of res (which triggers the inner trace calls)

the printing of the trace message

the evaluation of max x res, which triggers:

the evaluation of x

the evaluation of res (no-op, it's already been evaluated earlier)

Instead,

```<code>trace ((show xs) ++ " and " ++ show 1) (max x res)
</code>```

performs:

the (full) evalution of xs

the printing of the trace message

the evaluation of max x res, which triggers:

the evaluation of x

the evaluation of res (which now triggers the inner trace calls)

So, roughly put, the former expression prints the trace message before the inner trace calls in res, while the latter uses the other order. This causes the trace messages to appear reversed.

Body:
I was playing around with Continuation Passing Style with Haskell, and wrote the following:

import Debug.Trace

maxcps xx k = aux xx k
  where aux [] k' = trace (show "Base case") k' 0
        aux (1:xs) k' = k 1
        aux (x:xs) k' = aux xs (\res -> k' (trace ((show xs) ++ " and " ++ show res) (max x res) ))

main :: IO()
main = maxcps [2,3,4,5] print

That yields the following:

"Base case"
[] and 0
[5] and 5
[4,5] and 5
[3,4,5] and 5

Which is the order I would expect (I think?) based on the fact that the continuations should get called in reverse order starting from the base case, unwinding from there.

However, if I just modify it ever so slightly to, say, instead of show res I change it to some constant like show 1 as seen here:

trace ((show xs) ++ " and " ++ show "Hello!")

Then I get the opposite order being printed:

"Base case"
[3,4,5] and 1
[4,5] and 1
[5] and 1
[] and 1

I'nm confused on why this is happening—I would expect the first result since in a language like JavaScript, nesting callbacks will defer the execution of console.log statements until the body of the callback is run, but here it seems like in the second case it prints immediately as the recursive calls get made (so the lambda expression hasn't even been called yet). Is this a correct observation, and what's happening exactly to cause this behavior?

Body:
This is tricky to explain, but is a consequence of laziness.

When \res -> ... is called, res is not fully evaluated, yet, but is an unevaluated expression involving some trace calls. When you use trace (.... ++ show res) you force res to be evaluated, triggering the trace calls it has inside, which are printed before the outer traces.

In other words, the evaluation of

trace ((show xs) ++ " and " ++ show res) (max x res)

performs, usually in order:

the (full) evalution of xs

the evaluation of res (which triggers the inner trace calls)

the printing of the trace message

the evaluation of max x res, which triggers:

the evaluation of x

the evaluation of res (no-op, it's already been evaluated earlier)

Instead,

trace ((show xs) ++ " and " ++ show 1) (max x res)

performs:

the (full) evalution of xs

the printing of the trace message

the evaluation of max x res, which triggers:

the evaluation of x

the evaluation of res (which now triggers the inner trace calls)

So, roughly put, the former expression prints the trace message before the inner trace calls in res, while the latter uses the other order. This causes the trace messages to appear reversed.


问:
SQL server 2005 can't reference column that has been "casted"
this query works:

```<code>select ist_id,  ist_opis , CAST(ist_sifra as float ) as sifra
from IZOBRAZBENA_STOPNJA
where ist_aktivno<>0
order by sifra
</code>```

but if I want to see only only when sifra = 5 I get "Invalid column name 'sifra'."

```<code>select ist_id,  ist_opis , CAST(ist_sifra as float ) as sifra
from IZOBRAZBENA_STOPNJA
where ist_aktivno<>0 and sifra = 5
order by sifra
</code>```

I tryed wraping working sql statement in another select and then using "where sifra = 5" it also fails..

答:
yes, it is a fact.  you sould do something like

where ist_aktivno<>0 and ist_sifra = 5

or

where ist_aktivno<>0 and CAST(ist_sifra as float ) =5

Body:
this query works:

select ist_id,  ist_opis , CAST(ist_sifra as float ) as sifra
from IZOBRAZBENA_STOPNJA
where ist_aktivno<>0
order by sifra

but if I want to see only only when sifra = 5 I get "Invalid column name 'sifra'."

select ist_id,  ist_opis , CAST(ist_sifra as float ) as sifra
from IZOBRAZBENA_STOPNJA
where ist_aktivno<>0 and sifra = 5
order by sifra

I tryed wraping working sql statement in another select and then using "where sifra = 5" it also fails..


问:
Status of Python 3.7 in Cygwin
Does anyone have a way to install python 3.7 in latest stable Cygwin 32 or 64 bit that works out of the box without hacking? I've noticed that 3.6 works fine but 3.7 libraries don't behave and are missing key functionality.

I have usecases to have Cygwin for various scripts but want to use 3.7 for its improvements with type annotations. The new Linux runtime is not available on my servers so Cygwin is the only decent posix environment I can run in my windows servers.

[Update - 2022-03-30] I recently have successfully gotten Python 3.9 working on Cygwin. It does create proper python3 and pip3 executables out of the box. Only issues need to install cryptography==3.3.2 and pyopenssl<=21.0.0 due to rust dependency.

答:
Although Timothy's answer is correct, the cleaner way to do this is to ensure Cygwins 'alternative' package is installed and run the following commands in order to have your Python versions switchable through the alternative system. This will also switch to the correct pip versions.

```<code>/usr/sbin/update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 0 --slave /usr/bin/pip3 pip3 /usr/bin/pip3.6
/usr/sbin/update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 10 --slave /usr/bin/pip3 pip3 /usr/bin/pip3.7
/usr/sbin/update-alternatives --install /usr/bin/python python /usr/bin/python3 10 --slave /usr/bin/pip pip /usr/bin/pip3
/usr/sbin/update-alternatives --set python3 /usr/bin/python3.7
/usr/sbin/update-alternatives --set python /usr/bin/python3
</code>```

In case you still need deprecated Python 2.x versions you can add these accordingly as an alternative for 'python' via a 'python2' group.

Title: Status of Python 3.7 in Cygwin

Body:
Although Timothy's answer is correct, the cleaner way to do this is to ensure Cygwins 'alternative' package is installed and run the following commands in order to have your Python versions switchable through the alternative system. This will also switch to the correct pip versions.

/usr/sbin/update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 0 --slave /usr/bin/pip3 pip3 /usr/bin/pip3.6
/usr/sbin/update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 10 --slave /usr/bin/pip3 pip3 /usr/bin/pip3.7
/usr/sbin/update-alternatives --install /usr/bin/python python /usr/bin/python3 10 --slave /usr/bin/pip pip /usr/bin/pip3
/usr/sbin/update-alternatives --set python3 /usr/bin/python3.7
/usr/sbin/update-alternatives --set python /usr/bin/python3

In case you still need deprecated Python 2.x versions you can add these accordingly as an alternative for 'python' via a 'python2' group.


问:
The console application code I wrote in Dev-C ++ runs smoothly in the compiler but seems missing when running the .exe application?
I just started learning C++. I made a small console application using the scanf function, when I say compile and run in DevC++ environment, it opens smoothly (even I tried it in the online C++ compiler, there is no problem in the console) but when I close and run the program with the .exe extension I compiled, the last part is missing. It does not appear on the console after a certain location and the console turns off directly. What error, what warning, why might it be, and how can I fix it?

#include <iostream>
#include <stdio.h>

int main() {

    char isminiz[15];
    char soyisminiz[15];
    char yasiniz[3];

    printf ("Isminizi yaziniz: ");
    scanf("%s",isminiz);
    printf ("Soyisminizi yaziniz: ");
    scanf ("%s",soyisminiz);
    printf ("Yasiniz: ");
    scanf("%s",yasiniz);

    return 0;
}
```

答:
Add a system("pause"); before the return 0;.
There is no break point between the last printf() functions and the return. Also, remove the #include <iostream> since it is for C++, and you are not using it (your code is C).


问:
Kendo Upload - CSRF Token with ASP.NET
From what I saw, Kendo upload sends the CSRF token in the POST request body. What am I trying to do is to validate this token when making the request to a Web API method, but can't seem to figure it out.

Does anyone have any ideas? Is there something specific that I should override or change?

Thanks.

答:
see the anser</p>

```<code><meta name="_token" content="csrf_token()" />

<input type="file" name="files" id="photos" />

<script>
  var token = $('meta[name="_token"]').attr('content');

$("#photos").kendoUpload({
async: {
    saveUrl: "http://url/save"
},
upload: onUpload
});

function onUpload(e) {
var xhr = e.XMLHttpRequest;
if (xhr) {
    xhr.addEventListener("readystatechange", function (e) {
        if (xhr.readyState == 1 /* OPENED */) {
            xhr.setRequestHeader("X-CSRF-TOKEN", token);
        }
    });
 }
}
</script>
</code>```

Title: Kendo Upload - CSRF Token with ASP.NET

Body:
see the anser

<meta name="_token" content="csrf_token()" />

<input type="file" name="files" id="photos" />

<script>
  var token = $('meta[name="_token"]').attr('content');

$("#photos").kendoUpload({
async: {
    saveUrl: "http://url/save"
},
upload: onUpload
});

function onUpload(e) {
var xhr = e.XMLHttpRequest;
if (xhr) {
    xhr.addEventListener("readystatechange", function (e) {
        if (xhr.readyState == 1 /* OPENED */) {
            xhr.setRequestHeader("X-CSRF-TOKEN", token);
        }
    });
 }
}
</script>


问:
Angular 8: unable to send Authorization with service
I want to send the following "Authorization" through service.

```<code>Authorization :: Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==
</code>```

In the service I wrote the following code:

```<code>constructor(
        private http: HttpClient
    ) {
        this.header_auth = {
          headers: new HttpHeaders()
            .set('Authorization',  "Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==")
        }
    }

getToken() {
        return this.http.post(this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=XXXXX&username=XX@XXX.com&grant_type=password", this.header_auth);
    }
</code>```

I also used this code:
 public basic: any = 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==';

```<code>getToken() {

        const request = {
             headers: {
               'Authorization': this.basic,
             }
        };

        return this.http.post<any>(
            this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=XXXXX&username=XX@XXX.com&grant_type=password",
            { headers: request.headers }
        );
}
</code>```

When I called the service in my component, it shows me "error: "Unauthorized" But the same API URL is working well in "Postman".

xxx.component.ts:

```<code>this.commService.getToken().subscribe((data: any) => {
  console.log(data);
});
</code>```

In console I see the following error:

POST http://10.X.X.XXX:8089/XXXX/oauth/token?client_id=spring-security-oauth2-read-write-client&password=XXX&username=XX@XXX.com&grant_type=password 401

See postman screen:

答:
```<code>this.http.post(url, null, httpOptions)
</code>```

I did the same as per the post Angular 8: unable to set headers

Body:
I want to send the following "Authorization" through service.

Authorization :: Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==

In the service I wrote the following code:

constructor(
        private http: HttpClient
    ) {
        this.header_auth = {
          headers: new HttpHeaders()
            .set('Authorization',  "Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==")
        }
    }

getToken() {
        return this.http.post(this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=XXXXX&username=XX@XXX.com&grant_type=password", this.header_auth);
    }

I also used this code:
 public basic: any = 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==';

getToken() {

        const request = {
             headers: {
               'Authorization': this.basic,
             }
        };

        return this.http.post<any>(
            this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=XXXXX&username=XX@XXX.com&grant_type=password",
            { headers: request.headers }
        );
}

When I called the service in my component, it shows me "error: "Unauthorized" But the same API URL is working well in "Postman".

xxx.component.ts:

this.commService.getToken().subscribe((data: any) => {
  console.log(data);
});

In console I see the following error:

POST http://10.X.X.XXX:8089/XXXX/oauth/token?client_id=spring-security-oauth2-read-write-client&password=XXX&username=XX@XXX.com&grant_type=password 401

See postman screen:

Body:
this.http.post(url, null, httpOptions)

I did the same as per the post Angular 8: unable to set headers


问:
Angular 8: unable to set headers
I want to call a service from my component:

```<code>getToken() {
  const httpOptions = {headers: new HttpHeaders({ 'Authorization': 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==' })};
  return this.http.post(this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=root1234&username=tarak@bambootv.com&grant_type=password", httpOptions);
}
</code>```

The call not showing the Authorization, check the image below:

答:
You can use HttpInterceptor

It will send token with every request.

```<code>@Injectable()
export class ApiTokenInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    request = request.clone({
      setHeaders: {
        Authorization: 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA=='
      }
     });
    return next.handle(request);
   }
}
</code>```

Title: Angular 8: unable to set headers

Body:
I want to call a service from my component:

getToken() {
  const httpOptions = {headers: new HttpHeaders({ 'Authorization': 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==' })};
  return this.http.post(this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=root1234&username=tarak@bambootv.com&grant_type=password", httpOptions);
}

The call not showing the Authorization, check the image below:

Body:
You can use HttpInterceptor

It will send token with every request.

@Injectable()
export class ApiTokenInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    request = request.clone({
      setHeaders: {
        Authorization: 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA=='
      }
     });
    return next.handle(request);
   }
}


问:
ffmpeg stream videos from two cams have a same device name
There are two cameras have a same device name Microsoft® LifeCam Studio(TM).

ffmpeg -list_deivces true -f dshow -i dummy prints the below output.

```<code>C:\Users\user>ffmpeg -list_devices true -f dshow -i dummy
ffmpeg version git-2020-02-05-e6891d1 Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 9.2.1 (GCC) 20200122
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt --enable-amf
  libavutil      56. 39.100 / 56. 39.100
  libavcodec     58. 67.101 / 58. 67.101
  libavformat    58. 37.100 / 58. 37.100
  libavdevice    58.  9.103 / 58.  9.103
  libavfilter     7. 74.100 /  7. 74.100
  libswscale      5.  6.100 /  5.  6.100
  libswresample   3.  6.100 /  3.  6.100
  libpostproc    55.  6.100 / 55.  6.100
[dshow @ 000001d5c5108dc0] DirectShow video devices (some may be both video and audio devices)
[dshow @ 000001d5c5108dc0]  "Microsoft┬« LifeCam Studio(TM)"
[dshow @ 000001d5c5108dc0]     Alternative name "@device_pnp_\\?\usb#vid_045e&pid_0811&mi_00#8&6ae46e6&0&0000#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\global"
[dshow @ 000001d5c5108dc0]  "Microsoft┬« LifeCam Studio(TM)"
[dshow @ 000001d5c5108dc0]     Alternative name "@device_pnp_\\?\usb#vid_045e&pid_0811&mi_00#8&e544916&0&0000#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\global"
[dshow @ 000001d5c5108dc0] DirectShow audio devices
[dshow @ 000001d5c5108dc0]  "Desktop Microphone (6- Microsoft┬« LifeCam Studio(TM))"
[dshow @ 000001d5c5108dc0]     Alternative name "@device_cm_{33D9A762-90C8-11D0-BD43-00A0C911CE86}\wave_{D5F4881A-6E88-4563-8BA0-081CFD50E353}"
[dshow @ 000001d5c5108dc0]  "Desktop Microphone (5- Microsoft┬« LifeCam Studio(TM))"
[dshow @ 000001d5c5108dc0]     Alternative name "@device_cm_{33D9A762-90C8-11D0-BD43-00A0C911CE86}\wave_{84674B28-DC68-4AC0-8331-D687C7B7D69C}"
[dshow @ 000001d5c5108dc0]  "Digital Audio (S/PDIF) (High Definition Audio Device)"
[dshow @ 000001d5c5108dc0]     Alternative name "@device_cm_{33D9A762-90C8-11D0-BD43-00A0C911CE86}\wave_{CDD24485-59D2-4BED-B6FC-B7447251C7E2}"
</code>```

Because the two cameras have a same device name, I couldn't stream two videos using this simple command at a same time: ffplay -f dshow -i video=Microsoft® LifeCam Studio(TM).

So I used pin names following the ffmpeg dshow example.
The only thing I could check was Could not find video device with name [video=~~pin name~~] among source devices of type video.

What ffplay command makes enable to stream both videos?

答:
try

```<code>ffmpeg \
    -rtbufsize 10MB -f dshow -i video="@device_pnp_\\?\usb#vid_045e&pid_0811&mi_00#8&6ae46e6&0&0000#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\global" \
    -rtbufsize 10MB -f dshow -i video="@device_pnp_\\?\usb#vid_045e&pid_0811&mi_00#8&e544916&0&0000#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\global" \
    -filter_complex hstack,format=yuv420p -f sdl -
</code>```

If you have an error, change another USB Port.

https://ffmpeg.org/ffmpeg-filters.html#hstack

Body:
There are two cameras have a same device name Microsoft® LifeCam Studio(TM).

ffmpeg -list_deivces true -f dshow -i dummy prints the below output.

C:\Users\user>ffmpeg -list_devices true -f dshow -i dummy
ffmpeg version git-2020-02-05-e6891d1 Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 9.2.1 (GCC) 20200122
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt --enable-amf
  libavutil      56. 39.100 / 56. 39.100
  libavcodec     58. 67.101 / 58. 67.101
  libavformat    58. 37.100 / 58. 37.100
  libavdevice    58.  9.103 / 58.  9.103
  libavfilter     7. 74.100 /  7. 74.100
  libswscale      5.  6.100 /  5.  6.100
  libswresample   3.  6.100 /  3.  6.100
  libpostproc    55.  6.100 / 55.  6.100
[dshow @ 000001d5c5108dc0] DirectShow video devices (some may be both video and audio devices)
[dshow @ 000001d5c5108dc0]  "Microsoft┬« LifeCam Studio(TM)"
[dshow @ 000001d5c5108dc0]     Alternative name "@device_pnp_\\?\usb#vid_045e&pid_0811&mi_00#8&6ae46e6&0&0000#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\global"
[dshow @ 000001d5c5108dc0]  "Microsoft┬« LifeCam Studio(TM)"
[dshow @ 000001d5c5108dc0]     Alternative name "@device_pnp_\\?\usb#vid_045e&pid_0811&mi_00#8&e544916&0&0000#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\global"
[dshow @ 000001d5c5108dc0] DirectShow audio devices
[dshow @ 000001d5c5108dc0]  "Desktop Microphone (6- Microsoft┬« LifeCam Studio(TM))"
[dshow @ 000001d5c5108dc0]     Alternative name "@device_cm_{33D9A762-90C8-11D0-BD43-00A0C911CE86}\wave_{D5F4881A-6E88-4563-8BA0-081CFD50E353}"
[dshow @ 000001d5c5108dc0]  "Desktop Microphone (5- Microsoft┬« LifeCam Studio(TM))"
[dshow @ 000001d5c5108dc0]     Alternative name "@device_cm_{33D9A762-90C8-11D0-BD43-00A0C911CE86}\wave_{84674B28-DC68-4AC0-8331-D687C7B7D69C}"
[dshow @ 000001d5c5108dc0]  "Digital Audio (S/PDIF) (High Definition Audio Device)"
[dshow @ 000001d5c5108dc0]     Alternative name "@device_cm_{33D9A762-90C8-11D0-BD43-00A0C911CE86}\wave_{CDD24485-59D2-4BED-B6FC-B7447251C7E2}"

Because the two cameras have a same device name, I couldn't stream two videos using this simple command at a same time: ffplay -f dshow -i video=Microsoft® LifeCam Studio(TM).

So I used pin names following the ffmpeg dshow example.
The only thing I could check was Could not find video device with name [video=~~pin name~~] among source devices of type video.

What ffplay command makes enable to stream both videos?

Body:
try

ffmpeg \
    -rtbufsize 10MB -f dshow -i video="@device_pnp_\\?\usb#vid_045e&pid_0811&mi_00#8&6ae46e6&0&0000#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\global" \
    -rtbufsize 10MB -f dshow -i video="@device_pnp_\\?\usb#vid_045e&pid_0811&mi_00#8&e544916&0&0000#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\global" \
    -filter_complex hstack,format=yuv420p -f sdl -

If you have an error, change another USB Port.

https://ffmpeg.org/ffmpeg-filters.html#hstack