问:
How to combine multiple arrays with same amount of items in php
Is there a way to combine multiple arrays with same amount of items? See below the 4 arrays with 5 items inside:

```<code>$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');
</code>```

Expected Results:

```<code>[0] => Array
    (
        [0] => Type 1
        [1] => Description 1
        [2] => Brand 1
        [3] => Model 1
    )

[1] => Array
    (
        [0] => Type 2
        [1] => Description 2
        [2] => Brand 2
        [3] => Model 2
    )

[2] => Array
    (
        [0] => Type 3
        [1] => Description 3
        [2] => Brand 3
        [3] => Model 3
    )

[3] => Array
    (
        [0] => Type 4
        [1] => Description 4
        [2] => Brand 4
        [3] => Model 4
    )

[4] => Array
    (
        [0] => Type 5
        [1] => Description 5
        [2] => Brand 5
        [3] => Model 5
    )
</code>```

I'm not PHP expert please help me :)

Thank you.

答:
Simple loop through any array, Use that array's key to get ither array data and create new array

```<code>$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');

foreach($type as $key=>$type_val){ // Loop though one array
    $desc_val = $desc[$key] ?? "";
    $brand_val = $brand[$key] ?? "";
    $model_val = $model[$key] ?? "";
    $result[$key] = array($type_val,$desc_val,$brand_val,$model_val); // combine
}

print_r($result);
</code>```

Note : ?? will only work for php 7 + for older version change $desc[$key] ?? "" to isset($desc[$key]) ? $desc[$key] : ""

DEMO

Body:
Is there a way to combine multiple arrays with same amount of items? See below the 4 arrays with 5 items inside:

$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');

Expected Results:

[0] => Array
    (
        [0] => Type 1
        [1] => Description 1
        [2] => Brand 1
        [3] => Model 1
    )

[1] => Array
    (
        [0] => Type 2
        [1] => Description 2
        [2] => Brand 2
        [3] => Model 2
    )

[2] => Array
    (
        [0] => Type 3
        [1] => Description 3
        [2] => Brand 3
        [3] => Model 3
    )

[3] => Array
    (
        [0] => Type 4
        [1] => Description 4
        [2] => Brand 4
        [3] => Model 4
    )

[4] => Array
    (
        [0] => Type 5
        [1] => Description 5
        [2] => Brand 5
        [3] => Model 5
    )

I'm not PHP expert please help me :)

Thank you.

Body:
Simple loop through any array, Use that array's key to get ither array data and create new array

$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');

foreach($type as $key=>$type_val){ // Loop though one array
    $desc_val = $desc[$key] ?? "";
    $brand_val = $brand[$key] ?? "";
    $model_val = $model[$key] ?? "";
    $result[$key] = array($type_val,$desc_val,$brand_val,$model_val); // combine
}

print_r($result);

Note : ?? will only work for php 7 + for older version change $desc[$key] ?? "" to isset($desc[$key]) ? $desc[$key] : ""

DEMO


来源: stackexchange

问:
Laravel Socialite Facebook Login Error: The parameter app_id is required
Trying to get socialite to work on my app. Facebook returns the The parameter app_id is required error.

Routes:

```<code>Route::get('/login/facebook', '\CommendMe\Http\Controllers\AuthController@redirectToProvider');

Route::get('/login/facebook/callback', '\CommendMe\Http\Controllers\AuthController@handleProviderCallback');
</code>```

services.php:

```<code>'facebook' => [
    'client_id' => env('426129694395672'),
    'client_secret' => env('840fca14fc9fac4b592cd49f285c2ee9'),
    'redirect' => 'http://localhost/login/facebook/callback',
],
</code>```

AuthController.php

```<code>public function redirectToProvider() {
    return Socialite::driver('facebook')->redirect();
}

public function handleProviderCallback() {
    $user = Socialite::driver('facebook')->user();

    $user->name;
}
</code>```

When trying the /login/facebook route, facebook returns this error.
Why is this happening?

答:
Either use as

```<code>'client_id' => '426129694395672',
</code>```

Or

```<code>'client_id' => env("FB_APP",'426129694395672'),
</code>```

and use FB_APP = '426129694395672'  in .env file

Instead

```<code>'client_id' => env('426129694395672'),
</code>```

Using env('VarName')  is to get value of environment variable named as VarName in .env file

ContentLicense: CC BY-SA 3.0

Body:
Trying to get socialite to work on my app. Facebook returns the The parameter app_id is required error.

Routes:

Route::get('/login/facebook', '\CommendMe\Http\Controllers\AuthController@redirectToProvider');

Route::get('/login/facebook/callback', '\CommendMe\Http\Controllers\AuthController@handleProviderCallback');

services.php:

'facebook' => [
    'client_id' => env('426129694395672'),
    'client_secret' => env('840fca14fc9fac4b592cd49f285c2ee9'),
    'redirect' => 'http://localhost/login/facebook/callback',
],

AuthController.php

public function redirectToProvider() {
    return Socialite::driver('facebook')->redirect();
}

public function handleProviderCallback() {
    $user = Socialite::driver('facebook')->user();

    $user->name;
}

When trying the /login/facebook route, facebook returns this error.
Why is this happening?

Body:
Either use as

'client_id' => '426129694395672',

Or

'client_id' => env("FB_APP",'426129694395672'),

and use FB_APP = '426129694395672'  in .env file

Instead

'client_id' => env('426129694395672'),

Using env('VarName')  is to get value of environment variable named as VarName in .env file


问:
yowsup-cli: registration procedure failing, something unknown is "missing"
I am using yowsup-cli, and it prints the following when I run "yowsup-cli version" ...

```<code>yowsup-cli v2.0.13
Using yowsup v2.4
</code>```

I am trying to perform the registration as specified in the yowsup documentation, as follows. However, it fails.

First, I entered this command, and I indeed got a code back via SMS ...

```<code>yowsup-cli registration --requestcode sms --phone 1XXXXXXXXXX --cc 1 --mcc 310 --mnc 260
</code>```

I then entered this command using the code I got back (shown as "AAA-BBB"), but it failed ...

```<code>yowsup-cli registration --register AAA-BBB --phone 1XXXXXXXXXX --cc 1
</code>```

This is the error message I received ...

```<code>status: fail
reason: missing
</code>```

What I did above is exactly what is described in the yowsup documentation, here: https://github.com/tgalal/yowsup/wiki/yowsup-cli-2.0#yowsup-cli-registration%29 (see the commands listed under "Example:").

Note that I get the same failure when I add the MNC and MCC info to the "--register" command.

Does anyone know why this registration procedure is failing, and what might be "missing" in what I'm doing?

Note that the MCC and MNC I specified are what I found when looking up my cell provider (T-Mobile, USA).

Also, note that I am able to run WhatsApp with no problems from my mobile device, as well as via their web interface.

Thanks for any help and suggestions.

答:
you do not have to put "-" in your otp/code. it will be a plain sms code

```<code>yowsup-cli registration --register AAABBB --phone 1XXXXXXXXXX --cc 1
</code>```

i hope it works

Body:
I am using yowsup-cli, and it prints the following when I run "yowsup-cli version" ...

yowsup-cli v2.0.13
Using yowsup v2.4

I am trying to perform the registration as specified in the yowsup documentation, as follows. However, it fails.

First, I entered this command, and I indeed got a code back via SMS ...

yowsup-cli registration --requestcode sms --phone 1XXXXXXXXXX --cc 1 --mcc 310 --mnc 260

I then entered this command using the code I got back (shown as "AAA-BBB"), but it failed ...

yowsup-cli registration --register AAA-BBB --phone 1XXXXXXXXXX --cc 1

This is the error message I received ...

status: fail
reason: missing

What I did above is exactly what is described in the yowsup documentation, here: https://github.com/tgalal/yowsup/wiki/yowsup-cli-2.0#yowsup-cli-registration%29 (see the commands listed under "Example:").

Note that I get the same failure when I add the MNC and MCC info to the "--register" command.

Does anyone know why this registration procedure is failing, and what might be "missing" in what I'm doing?

Note that the MCC and MNC I specified are what I found when looking up my cell provider (T-Mobile, USA).

Also, note that I am able to run WhatsApp with no problems from my mobile device, as well as via their web interface.

Thanks for any help and suggestions.

Body:
you do not have to put "-" in your otp/code. it will be a plain sms code

yowsup-cli registration --register AAABBB --phone 1XXXXXXXXXX --cc 1

i hope it works


问:
Updating a single value in a sorted data structure
I need a data structure that is able to:

Add one value

Get the lowest value

Update one value

I can achieve this using std::multiset, where the operations are imlemented as:

multiset::insert()

multiset::begin()

first remove the item using multiset::erase() then add updated item using multiset::insert()

One thing I don't like with multiset is that an iterator is required to update an item. It would be nice if a pointer was enough.

I wonder if it would be better to use std::priority_queue, std heap algorithms or anything else for the operations required and how to do it. The first two operations are straightforward for the std::priority_queue or the heap algorithms, but the third operation (updating) is a problem. Are there any other structures that can be used? What are their performance benefits over multiset?

答: std::priority_queue will give you efficient insertions and lowest value queries, but updates will be slow. You can make updates efficient by storing pointers in both a PQ and a std::vector and using the vector to perform updates. To perform an update, mark the entry as stale and insert a new updated copy. Then when querying the lowest value, ignore stale entries.

ContentLicense: CC BY-SA 2.5


问:
Routing exclusion laravel 5.4
I have a problem here that needs your help. how to send the form without {{csrf_field()}} to laravel 5.4.

Added his file to the file VerifyCsrfToken.php in the field $except = []; but it does not work. Help please.

答:
Add you from route in VerifyCsrfToken Middleware file in protected except array

like this

```<code>protected $except = [
        'stripe/*',
    ];
</code>```

further more info check lavarel csrf

hope it will help you.

Title: Routing exclusion laravel 5.4

Body:
Add you from route in VerifyCsrfToken Middleware file in protected except array

like this

protected $except = [
        'stripe/*',
    ];

further more info check lavarel csrf

hope it will help you.


问:
Swift 4 Codable Array's
So I have an API route that returns a JSON array of objects. For example:

```<code>[
    {"firstname": "Tom", "lastname": "Smith", "age": 31},
    {"firstname": "Bob", "lastname": "Smith", "age": 28}
]
</code>```

I'm trying to envision how to use the new codable feature in Swift for to convert those into two objects in a class. So if I have a person class that is codable I would want to take that response and have it give me two person objects.

I'm also using Alamofire to handle the requests.

How can I do this? So far everything I've seen related to the codable stuff only allows 1 object. And I haven't seen any integration with Alamofire or a web framework.

答:
I managed to serialize data response to codable objects.

As all you may have been familiar with converting json object [String: String] for example. That json object need to be converted to Data by using json.data(using: .utf8)!.

With Alamofire, it is easy to get that data (or at least this kind of data worked for me, already compatible with .utf8 thing), I can just use this already available function

```<code>func responseData(queue: DispatchQueue?, completionHandler: @escaping (DataResponse<Data>) -> Void) -> Self
</code>```

Then just use that data as input for the Decoder in the completionHandler

```<code>let objek = try JSONDecoder().decode(T.self, from: data)
</code>```

You can also make this to some generic serialization function, with a little tweak, from the documentation

Generic Response Object Serialization

to this modification

```<code>func responseCodable<T: Codable>(
    queue: DispatchQueue? = nil,
    completionHandler: @escaping (DataResponse<T>) -> Void)
    -> Self
{
    let responseSerializer = DataResponseSerializer<T> { request, response, data, error in
        guard error == nil else { return .failure(BackendError.network(error: error!)) }

        guard let data = data else {
            return .failure(BackendError.objectSerialization(reason: "data is not valid"))
        }

        do{
            let objek = try JSONDecoder().decode(T.self, from: data!)
            return .success(objek)
        } catch let e {
            return .failure(BackendError.codableSerialization(error: e))
        }

    }

    return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
}
</code>```

Sample struct

```<code>struct Fids: Codable {

   var Status: Status?
   var Airport: Airport?
   var Record: [FidsRecord]
}
</code>```

Use the function this way

```<code>    Alamofire.request("http://whatever.com/zzz").responseCodable { (response: DataResponse<Fids>) in
        switch response.result{
        case .success(let value):
            print(value.Airport)
        // MARK: do whatever you want
        case .failure(let error):
            print(error)
            self.showToast(message: error.localizedDescription)
        }
    }
</code>```

Title: Swift 4 Codable Array's

Body:
So I have an API route that returns a JSON array of objects. For example:

[
    {"firstname": "Tom", "lastname": "Smith", "age": 31},
    {"firstname": "Bob", "lastname": "Smith", "age": 28}
]

I'm trying to envision how to use the new codable feature in Swift for to convert those into two objects in a class. So if I have a person class that is codable I would want to take that response and have it give me two person objects.

I'm also using Alamofire to handle the requests.

How can I do this? So far everything I've seen related to the codable stuff only allows 1 object. And I haven't seen any integration with Alamofire or a web framework.

Body:
I managed to serialize data response to codable objects.

As all you may have been familiar with converting json object [String: String] for example. That json object need to be converted to Data by using json.data(using: .utf8)!.

With Alamofire, it is easy to get that data (or at least this kind of data worked for me, already compatible with .utf8 thing), I can just use this already available function

func responseData(queue: DispatchQueue?, completionHandler: @escaping (DataResponse<Data>) -> Void) -> Self

Then just use that data as input for the Decoder in the completionHandler

let objek = try JSONDecoder().decode(T.self, from: data)

You can also make this to some generic serialization function, with a little tweak, from the documentation

Generic Response Object Serialization

to this modification

func responseCodable<T: Codable>(
    queue: DispatchQueue? = nil,
    completionHandler: @escaping (DataResponse<T>) -> Void)
    -> Self
{
    let responseSerializer = DataResponseSerializer<T> { request, response, data, error in
        guard error == nil else { return .failure(BackendError.network(error: error!)) }

        guard let data = data else {
            return .failure(BackendError.objectSerialization(reason: "data is not valid"))
        }

        do{
            let objek = try JSONDecoder().decode(T.self, from: data!)
            return .success(objek)
        } catch let e {
            return .failure(BackendError.codableSerialization(error: e))
        }

    }

    return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
}

Sample struct

struct Fids: Codable {

   var Status: Status?
   var Airport: Airport?
   var Record: [FidsRecord]
}

Use the function this way

    Alamofire.request("http://whatever.com/zzz").responseCodable { (response: DataResponse<Fids>) in
        switch response.result{
        case .success(let value):
            print(value.Airport)
        // MARK: do whatever you want
        case .failure(let error):
            print(error)
            self.showToast(message: error.localizedDescription)
        }
    }


问:
Find the value property of an object that is inside of a linked list, using recursive function
This is a JavaScript practice exercise.

Suppose I have a linked list object as follow:

```<code>   var list = {value: 10, rest: {value: 20, rest: {value: 30, rest: null}}}
</code>```

I need to write a recursive method to find the value of a certain sub-listed object.

For example, the method "nth":

```<code>   console.log(nth(list, 1));
</code>```

Should return value 20.

This is easy to accomplish if I change it to an array first.

However, I cannot change it to an array, the method "nth" has to be recursive.

If my method has to eventually return the value property, how do I make it recursive to the next sub-list? Doesn't the method has to return the next linked list in order to get to the object I desire?

Here's a hint that the question gave:

The recursive version of nth will, similarly, look at an ever smaller part of the “tail” of the list and at the same time count down the index until it reaches zero, at which point it can return the value property of the node it is looking at. To get the zeroeth element of a list, you simply take the value property of its head node. To get element N + 1, you take the Nth element of the list that’s in this list’s rest property.

答:
Here's one way you can do it

```<code>const listRef = ( i , xs ) =>
  xs === null
    ? undefined
    : i === 0
      ? xs.value
      : listRef ( i - 1 , xs.rest )

const myList =
  { value : 10
  , rest : { value: 20
           , rest : { value : 30
                    , rest : null
                    }
           }
  }

console.log ( listRef ( 0 , myList ) ) // 10
console.log ( listRef ( 1 , myList ) ) // 20
console.log ( listRef ( 2 , myList ) ) // 30
console.log ( listRef ( 3 , myList ) ) // undefined
</code>```

But you have a decision to make here – what kind of result should you get when listRef ( 0 , [ undefined ] ) is called? How does that differ from listRef ( 0 , [] )?

listRef ( 0 , [] ) should probably have the same behavior as head ( [] ) – but I'll leave that up to you

Body:
This is a JavaScript practice exercise.

Suppose I have a linked list object as follow:

   var list = {value: 10, rest: {value: 20, rest: {value: 30, rest: null}}}

I need to write a recursive method to find the value of a certain sub-listed object.

For example, the method "nth":

   console.log(nth(list, 1));

Should return value 20.

This is easy to accomplish if I change it to an array first.

However, I cannot change it to an array, the method "nth" has to be recursive.

If my method has to eventually return the value property, how do I make it recursive to the next sub-list? Doesn't the method has to return the next linked list in order to get to the object I desire?

Here's a hint that the question gave:

The recursive version of nth will, similarly, look at an ever smaller part of the “tail” of the list and at the same time count down the index until it reaches zero, at which point it can return the value property of the node it is looking at. To get the zeroeth element of a list, you simply take the value property of its head node. To get element N + 1, you take the Nth element of the list that’s in this list’s rest property.

Body:
Here's one way you can do it

const listRef = ( i , xs ) =>
  xs === null
    ? undefined
    : i === 0
      ? xs.value
      : listRef ( i - 1 , xs.rest )

const myList =
  { value : 10
  , rest : { value: 20
           , rest : { value : 30
                    , rest : null
                    }
           }
  }

console.log ( listRef ( 0 , myList ) ) // 10
console.log ( listRef ( 1 , myList ) ) // 20
console.log ( listRef ( 2 , myList ) ) // 30
console.log ( listRef ( 3 , myList ) ) // undefined

But you have a decision to make here – what kind of result should you get when listRef ( 0 , [ undefined ] ) is called? How does that differ from listRef ( 0 , [] )?

listRef ( 0 , [] ) should probably have the same behavior as head ( [] ) – but I'll leave that up to you


问:
Does a rule without passing a variable against the philosophy of declarative programming or prolog?
```<code>cancer():-
   pain(strong),
   mood(depressed),
   fever(mild),
   bowel(bloody),
   miscellaneous(giddy).

diagnose():-
   nl,
   cancer()->write("has cancer").
</code>```

for example, dog(X) says that X is a dog but my cancer statement just checks whether the following conditions meet. Is there a better way to do that?

答:
cancer() isn't legal syntax, but the idea's perfectly fine.

Just do the call as

```<code>cancer
</code>```

and define it as a fact or rule.

```<code>cancer.   % fact

cancer :- blah blah  %rule
</code>```

in fact, you use a system predicate with no args in your program -

nl is a predicate that always succeeds, and prints a newline.

There are many reasons to have a predicate with no arguments. Suppose you have a server that runs in a slightly different configuration in production than in development. Developer access  API is off in production.

```<code>my_handler(Request) :-
      development,
      blah blah
</code>```

development only succeeds if we're in development environment

or you might have a side effect set off, or be using state.

Body:
cancer():-
   pain(strong),
   mood(depressed),
   fever(mild),
   bowel(bloody),
   miscellaneous(giddy).

diagnose():-
   nl,
   cancer()->write("has cancer").

for example, dog(X) says that X is a dog but my cancer statement just checks whether the following conditions meet. Is there a better way to do that?

Body:
cancer() isn't legal syntax, but the idea's perfectly fine.

Just do the call as

cancer

and define it as a fact or rule.

cancer.   % fact

cancer :- blah blah  %rule

in fact, you use a system predicate with no args in your program -

nl is a predicate that always succeeds, and prints a newline.

There are many reasons to have a predicate with no arguments. Suppose you have a server that runs in a slightly different configuration in production than in development. Developer access  API is off in production.

my_handler(Request) :-
      development,
      blah blah

development only succeeds if we're in development environment

or you might have a side effect set off, or be using state.


问:
The Meaning of @override in Android Studio
I am completely new to Android Studio and I want to know the purpose of the @Override statement in Android Studio.

答:
Its a Java annotation (not Android-specific). You use it to mean for this method to override a method.

The reason to use it is to catch errors when you create a method you intend to override a method, but through some error, it does not, e.g. typo in the method name, an error in the method signature, etc..  For example, sometimes developers to this:

```<code>class Foo {
    public boolean equals(Foo other) {
       ...
</code>```

The author intended this to override the superclass' equals method, but it does not (The parameter type should be Object).  The program will compile fine, but will not use Foo.equals as the author intended.

```<code>class Foo {
    @Override
    public boolean equals(Foo other) {
       ...
</code>```

The compile will now give an error because the method does not override another method.  This points out the problem early and hopefully saves some debugging time tracking down the problem.

ContentLicense: CC BY-SA 4.0

Body:
Its a Java annotation (not Android-specific). You use it to mean for this method to override a method.

The reason to use it is to catch errors when you create a method you intend to override a method, but through some error, it does not, e.g. typo in the method name, an error in the method signature, etc..  For example, sometimes developers to this:

class Foo {
    public boolean equals(Foo other) {
       ...

The author intended this to override the superclass' equals method, but it does not (The parameter type should be Object).  The program will compile fine, but will not use Foo.equals as the author intended.

class Foo {
    @Override
    public boolean equals(Foo other) {
       ...

The compile will now give an error because the method does not override another method.  This points out the problem early and hopefully saves some debugging time tracking down the problem.


问:
Force quotes in yaml.dump Python
Before I go in, yes I've looked into it already and know that YAML doesn't differentiate quotes and non-quotes and just takes the types as they are. Frankly I think it's nicer without the quotes, but unfortunately that's not what I need. So please try and understand that I have looked into the matter but still do need the quotes around my string objects.

In my code I have a dictionary:

```<code>data = {dic:[{A:''}, {B:''}, {C:''}, {D:''},...]}
</code>```

the 'var*' are constructed through the PyQt4 QLineEdit class which the line of code extract the line looks like this:

```<code>var* = str(QtGui.QLineEdit().displayText())
</code>```

So when I do data['dic'][index]['A'-'Z'] = var*

it becomes data = {dic:[{A: 'var1'}, {B:'var2'}, {C:'var3'}, {D:'var4'},...]}

then I dump all my data:

```<code>prettyData = yaml.dump(data, default_flow_style=False, width=10000000)
</code>```

and print prettyData I get this:

```<code>dic:
  - A: var1
  - B: var2
  - C: var3
  - D: var4
  ...
</code>```

I've tried many things to make them appear:

```<code>dic:
  - A: 'var1'
  - B: 'var2'
  - C: 'var3'
  - D: 'var4'
  ...
</code>```

but haven't been successful yet. I've heard different opinions on the matter ranging from "not possible" to "just put quotes around them", which as you can see, in my case, I cannot do.

Any ideas on how to go about this?

答:
```<code>#!/usr/bin/env python2
# quoting_example.py
import yaml
import yaml.representer

def literal_presenter(dumper, data):
  if isinstance(data, str) and "\n" in data:
      return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
  return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='"')

yaml.add_representer(str, literal_presenter)
print yaml.dump({"key": "value", "multiline": "foo\nbar"}, default_flow_style=False)
</code>```

And the result is:

```<code>$ python2 quoting_example.py
"key": "value"
"multiline": |-
  foo
  bar
</code>```

Similarly, you can add representers for unicode, dicts (think sorted dicts), etc.

Title: Force quotes in yaml.dump Python

Body:
Before I go in, yes I've looked into it already and know that YAML doesn't differentiate quotes and non-quotes and just takes the types as they are. Frankly I think it's nicer without the quotes, but unfortunately that's not what I need. So please try and understand that I have looked into the matter but still do need the quotes around my string objects.

In my code I have a dictionary:

data = {dic:[{A:''}, {B:''}, {C:''}, {D:''},...]}

the 'var*' are constructed through the PyQt4 QLineEdit class which the line of code extract the line looks like this:

var* = str(QtGui.QLineEdit().displayText())

So when I do data['dic'][index]['A'-'Z'] = var*

it becomes data = {dic:[{A: 'var1'}, {B:'var2'}, {C:'var3'}, {D:'var4'},...]}

then I dump all my data:

prettyData = yaml.dump(data, default_flow_style=False, width=10000000)

and print prettyData I get this:

dic:
  - A: var1
  - B: var2
  - C: var3
  - D: var4
  ...

I've tried many things to make them appear:

dic:
  - A: 'var1'
  - B: 'var2'
  - C: 'var3'
  - D: 'var4'
  ...

but haven't been successful yet. I've heard different opinions on the matter ranging from "not possible" to "just put quotes around them", which as you can see, in my case, I cannot do.

Any ideas on how to go about this?

Body:
#!/usr/bin/env python2
# quoting_example.py
import yaml
import yaml.representer

def literal_presenter(dumper, data):
  if isinstance(data, str) and "\n" in data:
      return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
  return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='"')

yaml.add_representer(str, literal_presenter)
print yaml.dump({"key": "value", "multiline": "foo\nbar"}, default_flow_style=False)

And the result is:

$ python2 quoting_example.py
"key": "value"
"multiline": |-
  foo
  bar

Similarly, you can add representers for unicode, dicts (think sorted dicts), etc.


问:
How do i add extra dimensions to a screenshot?
I currently have the code below.. and it takes the screenshot just fine.. but it cuts off the left and right side of the screenshot

How do i add another 10 pixels all around possible?

```<code>print "Taking SS..."
focusWindow = App.focusedWindow()
regionINFO = capture(App.focusedWindow())
shutil.move(regionINFO, os.path.join(r'C:\Screenshots', 'Dummy1.png'))
print "SS Done..."
</code>```

答:
It looks like you're taking a screenshot of a specific app. Try the whole screen.</p>

```<code>import shutil # once at beginning of script
img = capture(SCREEN)
shutil.move(img, 'path')
</code>```

Body:
I currently have the code below.. and it takes the screenshot just fine.. but it cuts off the left and right side of the screenshot

How do i add another 10 pixels all around possible?

print "Taking SS..."
focusWindow = App.focusedWindow()
regionINFO = capture(App.focusedWindow())
shutil.move(regionINFO, os.path.join(r'C:\Screenshots', 'Dummy1.png'))
print "SS Done..."

Body:
It looks like you're taking a screenshot of a specific app. Try the whole screen.

import shutil # once at beginning of script
img = capture(SCREEN)
shutil.move(img, 'path')


问:
Beautiful Soup find_all wraps together instead of individually
Long story short, I'm trying to use Beautiful Soup to replace b tags with strong tags.
Soup takes some input that includes

```<code><b>Words:</b> attributes
<b>Other Words:</b> other attributes
</code>```

I have the following python3 code:

```<code>strong_tag = soup.new_tag("strong")
if(soup.find('b')):
    for b_tag in soup.find_all('b'):
        b_tag.wrap(strong_tag)
</code>```

This outputs

```<code>attributes
<strong><b>Words:</b><b>Other Words:</b></strong> other attributes
</code>```

instead of

```<code><strong><b>Words:</b></strong> attributes
<strong><b>Other Words:</b></strong> other attributes
</code>```

How do I fix this?

I'm assuming that once I can fix this, I can extract() the contents from the b tags, leaving just the strong tags behind.

答:
<em> simple one hope you would like it</em>   </p>

```<code>from BeautifulSoup import BeautifulSoup, Tag
    mes=""" <b>Words:</b> attributes
    <b>Other Words:</b> other attributes"""
    soup = BeautifulSoup(mes)

    for a in soup.findAll('b'):
          p = Tag(soup, 'strong')
          a.replaceWith(p)
          p.insert(0, a)

    print soup
</code>```

Body:
Long story short, I'm trying to use Beautiful Soup to replace b tags with strong tags.
Soup takes some input that includes

Words: attributes
Other Words: other attributes

I have the following python3 code:

strong_tag = soup.new_tag("strong")
if(soup.find('b')):
    for b_tag in soup.find_all('b'):
        b_tag.wrap(strong_tag)

This outputs

attributes
Words:Other Words: other attributes

instead of

Words: attributes
Other Words: other attributes

How do I fix this?

I'm assuming that once I can fix this, I can extract() the contents from the b tags, leaving just the strong tags behind.

Body:
 simple one hope you would like it

from BeautifulSoup import BeautifulSoup, Tag
    mes=""" <b>Words:</b> attributes
    <b>Other Words:</b> other attributes"""
    soup = BeautifulSoup(mes)

    for a in soup.findAll('b'):
          p = Tag(soup, 'strong')
          a.replaceWith(p)
          p.insert(0, a)

    print soup


答:
This is perfect and tested code:</p>

```<code><?php
$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');

$result = array();

foreach ($type as $id => $key) {
    $result[$id] = array($key,$desc[$id],$brand[$id],$model[$id]);
}
echo "```";print_r($result);
?>
</code>```

Title: How to combine multiple arrays with same amount of items in php

Body:
Is there a way to combine multiple arrays with same amount of items? See below the 4 arrays with 5 items inside:

$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');

Expected Results:

[0] => Array
    (
        [0] => Type 1
        [1] => Description 1
        [2] => Brand 1
        [3] => Model 1
    )

[1] => Array
    (
        [0] => Type 2
        [1] => Description 2
        [2] => Brand 2
        [3] => Model 2
    )

[2] => Array
    (
        [0] => Type 3
        [1] => Description 3
        [2] => Brand 3
        [3] => Model 3
    )

[3] => Array
    (
        [0] => Type 4
        [1] => Description 4
        [2] => Brand 4
        [3] => Model 4
    )

[4] => Array
    (
        [0] => Type 5
        [1] => Description 5
        [2] => Brand 5
        [3] => Model 5
    )

I'm not PHP expert please help me :)

Thank you.

Body:
This is perfect and tested code:

<?php
$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');

$result = array();

foreach ($type as $id => $key) {
    $result[$id] = array($key,$desc[$id],$brand[$id],$model[$id]);
}
echo "<pre>";print_r($result);
?>


问:
Angular2: how to get custom response headers (CORS issue)
Why can't I access ALL headers in Angular2 from the response?

I have a legacy webservice which I can't modify.
It sends some i,mportant information back to the client in the Response headers. Don't ask me why. this is crap.

my code is this:

```<code>      .subscribe((r: Response) => {
      var customHeader = r.headers.get("Database-Deleted");
      var allHeadersAsString = JSON.stringify(r.headers);
</code>```

but seems the response contains only a few headers, not all of them.

Can someone tell me this is by design and there is no way to access them?
(or even better: tell me how to make it work)

UPDATE

Thanks top the comments I was able to identify it as a CORS issue. The accepted answers of other questions did not give me the right clue.

THANKS!

答:
In case your back-end is ASP.net WebAPI Core, you have to do the following way</p>

```<code>  public void ConfigureServices(IServiceCollection services)
    {

        services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader().WithExposedHeaders("X-Pagination");
        }));
</code>```

Body:
Why can't I access ALL headers in Angular2 from the response?

I have a legacy webservice which I can't modify.
It sends some i,mportant information back to the client in the Response headers. Don't ask me why. this is crap.

my code is this:

      .subscribe((r: Response) => {
      var customHeader = r.headers.get("Database-Deleted");
      var allHeadersAsString = JSON.stringify(r.headers);

but seems the response contains only a few headers, not all of them.

Can someone tell me this is by design and there is no way to access them?
(or even better: tell me how to make it work)

UPDATE

Thanks top the comments I was able to identify it as a CORS issue. The accepted answers of other questions did not give me the right clue.

THANKS!

Body:
In case your back-end is ASP.net WebAPI Core, you have to do the following way

  public void ConfigureServices(IServiceCollection services)
    {

        services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader().WithExposedHeaders("X-Pagination");
        }));


问:
Why un-moduled JAR can access non exposes packaged of a moduled JAR?
I'm playing around with Java 9 in intelliJ:
I've created 4 modules (all modules depended on module1):

module1: exports packages pkg1 and exports pkg2 to module 2.

module2: requires module1 and able to access both packages

module3: requires module1 and able to access only pkg1

module4: does not have the module-info.class, able to access both packages of module1

I thought that automatic modules should require all exposed packaged but not the ones which are not exposed.

I don't understand what is the point of encapsulation, if it works only on explicitly moduled JARs.

What am I missing?

答:
To Eliminate IntelliJ logic, I've built 3 JARs from my modules(1, 2 & 4) and started playing around with them using java in the command line.

When I tried to execute the code using only -cp option it had the same behavior of module4 being able to access pkg2 -> this brings me to the conclusion that if there is no module-info.java file in an IntelliJ module it uses the classpath.

Here is the tricky part:
I've used --list-modules option to ensure the automatic name for module4 is module4.
Then I've executed something like:

```<code>java -p "<module1 path>;<module4 path>" -m module4/<MainClass>
</code>```

I've got a ClassNotFoundException on a class from pkg1 (the exported package).

if I execute:

```<code>java -p "<module1 path>;<module2 path>" -m module2/<MainClass>
</code>```

then everything works.

So it seems like if we want to use the module path the main class must be from a moduled JAR.

Looks like, automatic JARs are for backward compatibility, so that we will be able to use them as dependencies of our new modules.

However if want to execute a module using the module path, Java assumes that the JAR we are executing is a moduled JAR, otherwise we should keep using the classpath.

In other words, if we execute an un-moduled JAR using the -p (modulepath) option it will not require other modules in the path.

All these conclusions came from playing around with the Java, can someone point me to the exact parts of theory behind it?

Body:
To Eliminate IntelliJ logic, I've built 3 JARs from my modules(1, 2 & 4) and started playing around with them using java in the command line.

When I tried to execute the code using only -cp option it had the same behavior of module4 being able to access pkg2 -> this brings me to the conclusion that if there is no module-info.java file in an IntelliJ module it uses the classpath.

Here is the tricky part:
I've used --list-modules option to ensure the automatic name for module4 is module4.
Then I've executed something like:

java -p "<module1 path>;<module4 path>" -m module4/<MainClass>

I've got a ClassNotFoundException on a class from pkg1 (the exported package).

if I execute:

java -p "<module1 path>;<module2 path>" -m module2/<MainClass>

then everything works.

So it seems like if we want to use the module path the main class must be from a moduled JAR.

Looks like, automatic JARs are for backward compatibility, so that we will be able to use them as dependencies of our new modules.

However if want to execute a module using the module path, Java assumes that the JAR we are executing is a moduled JAR, otherwise we should keep using the classpath.

In other words, if we execute an un-moduled JAR using the -p (modulepath) option it will not require other modules in the path.

All these conclusions came from playing around with the Java, can someone point me to the exact parts of theory behind it?


问:
I cannot find a plugin in Android Studio
I wanted to add a builder generator plugin into android studio and I found this:
https://plugins.jetbrains.com/plugin/6585?pr=idea

But that isn't showing up inside Android Studio's plugin area. So then I thought maybe it had to be an Android Studio plugin so I found this:
https://plugins.jetbrains.com/plugin/7568?pr=androidstudio

I still can't find that inside the plugin list.

So, I guess I have two questions. Do some plugins not show up inside Android Studio? And how can I add one of those plugins to my IDE?

Edit: Here's a screenshot when I search for Builder Generator, it's not there for some reason:

答:
This might be helpful for some people.

For Android Studio 3.0:

I installed Genymotion plugin and it's launcher icon is supposed to come in the toolbar(where other icons present like run). But it was not there after some digging I found that in Studio 3.0 the toolbar menu is disabled by default and the main icons(run, debug etc) are integrated in the next toolbar(just below it navigation menu toolbar).

So, to get the toolbar back click.

View -> Toolbar


问:
Oracle - Need advice on multiple counts, on table with large amounts of data
Table with large data, does anyone know how to optimize the count statement?

Eg: table Booking(id, email, mobile,....) (about 30 fields).

```<code>Function GetBookingCount(p_email, p_mobile) return number
    Select count(id)
    from Booking
    Where email = p_email
    or mobile = p_mobile

Function GetBookingStatus3Count(p_email, p_mobile) return number
    Select count(id)
    from Booking
    Where (email = p_email or mobile = p_mobile)
    and status = 3;
</code>```

Final select:

```<code>Select GetBookingCount(email, mobile) as BookingCount
      , GetBookingStatus3Count(email, mobile) as BookingStatus3Count
      , ...
From Booking
where ....
</code>```

solution1: Set the field column index what in where clause to count as email column, mobile, status column.

solution2: create a new table with few columns to count.
new table: Booking_Stats(id, email, mobile, status).

Thanks for any suggestion.

答:
```<code>select count(*) count_all, count( case when status=3 then 1 else null end ) count_status_3
from Booking
where email = p_email and mobile = p_mobile
</code>```

//NOTE: Query is written from head, not tested

You would consider creating an index on (email,mobile) or on (email,mobile,status) depending how many lines for given (email,mobile) you get and would you pay the cost of update of the index for status change (if allowed). In case of many updates of status for the same line, you might prefer indexing only (email,mobile) [read/write cost trade off].

Email is likely very discriminant (one value filters out most of the columns). If that is not the case, consider changing order to (mobile,email) if mobile column is better candidate.

Body:
Table with large data, does anyone know how to optimize the count statement?

Eg: table Booking(id, email, mobile,....) (about 30 fields).

Function GetBookingCount(p_email, p_mobile) return number
    Select count(id)
    from Booking
    Where email = p_email
    or mobile = p_mobile

Function GetBookingStatus3Count(p_email, p_mobile) return number
    Select count(id)
    from Booking
    Where (email = p_email or mobile = p_mobile)
    and status = 3;

Final select:

Select GetBookingCount(email, mobile) as BookingCount
      , GetBookingStatus3Count(email, mobile) as BookingStatus3Count
      , ...
From Booking
where ....

solution1: Set the field column index what in where clause to count as email column, mobile, status column.

solution2: create a new table with few columns to count.
new table: Booking_Stats(id, email, mobile, status).

Thanks for any suggestion.

Body:
select count(*) count_all, count( case when status=3 then 1 else null end ) count_status_3
from Booking
where email = p_email and mobile = p_mobile

//NOTE: Query is written from head, not tested

You would consider creating an index on (email,mobile) or on (email,mobile,status) depending how many lines for given (email,mobile) you get and would you pay the cost of update of the index for status change (if allowed). In case of many updates of status for the same line, you might prefer indexing only (email,mobile) [read/write cost trade off].

Email is likely very discriminant (one value filters out most of the columns). If that is not the case, consider changing order to (mobile,email) if mobile column is better candidate.


答:
How about replace?

```<code>from bs4 import BeautifulSoup
div_test="""<b>Words:</b> attributes
<b>Other Words:</b> other attributes"""
soup = BeautifulSoup(div_test,'lxml')

str(soup).replace("b>","strong>")
</code>```

Output:

```<code><html><body><strong>Words:</strong> attributes
<strong>Other Words:</strong> other attributes
</body></html>
</code>```

Title: Beautiful Soup find_all wraps together instead of individually

Body:
How about replace?

from bs4 import BeautifulSoup
div_test="""<b>Words:</b> attributes
<b>Other Words:</b> other attributes"""
soup = BeautifulSoup(div_test,'lxml')

str(soup).replace("b>","strong>")

Output:

<html><body><strong>Words:</strong> attributes
<strong>Other Words:</strong> other attributes
</body></html>


问:
MYSQL create table, constraint, foreign key
I am following along with a UDEMY course about SQL. The instructor is working in postgresql.  I am working in MySQL workbench. Our corporate development is in MySQL 5.6 on the AWS platform. So I want to learn in MySQL.

There is a lecture about "creating tables" and using constraint and foreign key commands to link the primary keys in two different tables. This is something I want to do with my data, so the challenge is relevant. The instructor's code does not compile for me. I get "error code 1215. Cannot add foreign key constraint".

I have read here that the variables must have the exact same definition.  So I changed the instructor's tables from "serial" to int.  I am still getting the error. I have tried simplifying the code. I'm still not getting anywhere. Can anybody help me understand why it is not executing?

```<code>create table if not exists accounts(

user_id INT auto_increment not null,
username varchar(50) unique not null,
password varchar(50) not null,
email varchar(350) unique not null,
created_on timestamp not null,
last_login timestamp,
primary key (user_id)
);

create table if not exists role(
role_id INT auto_increment not null,
role_name varchar(250) unique not null,
PRIMARY KEY (role_id)
);

create table accounts_role(
user_id INT,
role_id INT,
grant_date timestamp,
primary key (user_id, role_id),

constraint accounts_role_role_id_fkey foreign key (role_id)
    references role(role_id) match simple
    on update no action
    on delete no action,

constraint accounts_role_user_id_fkey foreign key (user_id)
    references account (user_id) MATCH SIMPLE
    on update no action
    on delete no action
);
</code>```

答:
good grief.

Thanks Caius, i was implementing your suggestion and I found the answer to my problem.

i realized that my table is named "accounts" and i was creating a constraint on "account" ...

```<code>create table accounts_role(
user_id INT,
role_id INT,
grant_date timestamp,
primary key (user_id, role_id),

constraint accounts_role_role_id_fkey foreign key (role_id)
    references role(role_id) match simple
    on update no action
    on delete no action,

constraint accounts_role_user_id_fkey foreign key (user_id)
    references accounts(user_id) MATCH SIMPLE
    on update no action
    on delete no action
);
</code>```

Body:
I am following along with a UDEMY course about SQL. The instructor is working in postgresql.  I am working in MySQL workbench. Our corporate development is in MySQL 5.6 on the AWS platform. So I want to learn in MySQL.

There is a lecture about "creating tables" and using constraint and foreign key commands to link the primary keys in two different tables. This is something I want to do with my data, so the challenge is relevant. The instructor's code does not compile for me. I get "error code 1215. Cannot add foreign key constraint".

I have read here that the variables must have the exact same definition.  So I changed the instructor's tables from "serial" to int.  I am still getting the error. I have tried simplifying the code. I'm still not getting anywhere. Can anybody help me understand why it is not executing?

create table if not exists accounts(

user_id INT auto_increment not null,
username varchar(50) unique not null,
password varchar(50) not null,
email varchar(350) unique not null,
created_on timestamp not null,
last_login timestamp,
primary key (user_id)
);

create table if not exists role(
role_id INT auto_increment not null,
role_name varchar(250) unique not null,
PRIMARY KEY (role_id)
);

create table accounts_role(
user_id INT,
role_id INT,
grant_date timestamp,
primary key (user_id, role_id),

constraint accounts_role_role_id_fkey foreign key (role_id)
    references role(role_id) match simple
    on update no action
    on delete no action,

constraint accounts_role_user_id_fkey foreign key (user_id)
    references account (user_id) MATCH SIMPLE
    on update no action
    on delete no action
);

Body:
good grief.

Thanks Caius, i was implementing your suggestion and I found the answer to my problem.

i realized that my table is named "accounts" and i was creating a constraint on "account" ...

create table accounts_role(
user_id INT,
role_id INT,
grant_date timestamp,
primary key (user_id, role_id),

constraint accounts_role_role_id_fkey foreign key (role_id)
    references role(role_id) match simple
    on update no action
    on delete no action,

constraint accounts_role_user_id_fkey foreign key (user_id)
    references accounts(user_id) MATCH SIMPLE
    on update no action
    on delete no action
);


问:
Custom container unnecessarily creating new elements instances when space is reserved
For my own education, I am trying to learn how to implement efficient custom containers in C++. I have now a basic working version of a my custom vector type. However, for some reason, when the vector has to be expanded to fit more elements (in which case a call to its inner 'reserve' function is made), it creates extra copies of elements.

To help explaining what I mean, I show below a minimum reproducible example. Let a minimum version of CustomVector class look like the following:

```<code>template<class T>
class CustomVector
{
private:
    size_t m_size = 0;
    size_t m_capacity = 1;
    T *m_data = nullptr;

public:
CustomVector()
{
}

CustomVector(const size_t new_capacity)
{
    m_capacity = new_capacity;
    m_size = 0;
    m_data = new T[m_capacity]();
}

~CustomVector()
{
    if (m_data != nullptr)
        delete[] m_data;
}

void reserve(size_t new_capacity)
{
    if (m_data == nullptr)
    {
        m_capacity = new_capacity;
        m_size = 0;
        m_data = new T[m_capacity]();
    }
    else if (new_capacity > m_capacity)
    {
        T* new_data = new T[new_capacity]();
        memmove(new_data, m_data, (m_size) * sizeof(T));
        delete[] m_data;
        m_capacity = new_capacity;
        m_data = new_data;
    }
}

void push_back(const T & value)
{
    if (m_data == nullptr)
    {
        m_capacity = 1;
        m_size = 0;
        m_data = new T[m_capacity]();
        m_data[0] = value;
    }
    else if (m_size + 1 >= m_capacity)
    {
        reserve(m_capacity*2);
    }
    else
    {
        m_data[m_size-1] = value;
        m_size++;
    }
}
</code>```

};

Now, to facilitate seeing the problem, I also create a class called Object. Each new instance of such class that is created automatically receives an unique id number:

```<code>class Object
{
private:
    static int idCounter;
public:
    int id;
    Object()
    {
        id = idCounter;
        idCounter++;
    }
};
int Object::idCounter = 0;
</code>```

Lastly, here is how the main function of this example looks like:

```<code>int main()
{
    CustomVector<Object> objects; //comment this line...
    //std::vector<Object> objects; //...and uncomment this to try with std::vector
Object x;
printf("%d\n", x.id);
objects.push_back(x);

Object y;
printf("%d\n", y.id);
objects.push_back(y);

Object z;
printf("%d ", z.id);

system("Pause");
return 0;
</code>```

}

The output, using my CustomVector as the container, is:

0 2 5

While the output using a std::vector as the container is:

0 1 2

The desirable behavior for me is exactly that of std::vector, that is, pushing back instances of classes should create full new temporary instances of such class.

Could someone help me understand what am I doing wrong?

答:
The problem is most likely this line in the push_back function:

```<code>m_data = new T[m_capacity]();
</code>```

This will cause the creation of m_capacity number of T objects, and therefore m_capacity calls to the T constructor. This is bad if the T constructor is expensive (not to mention some beginners do input and other things in the constructor).

What std::vector most likely does is keeping a buffer of bytes, and then when pushing back it does placement new to construct an object in place in some position in the buffer.

Body:
For my own education, I am trying to learn how to implement efficient custom containers in C++. I have now a basic working version of a my custom vector type. However, for some reason, when the vector has to be expanded to fit more elements (in which case a call to its inner 'reserve' function is made), it creates extra copies of elements.

To help explaining what I mean, I show below a minimum reproducible example. Let a minimum version of CustomVector class look like the following:

template<class T>
class CustomVector
{
private:
    size_t m_size = 0;
    size_t m_capacity = 1;
    T *m_data = nullptr;

public:
CustomVector()
{
}

CustomVector(const size_t new_capacity)
{
    m_capacity = new_capacity;
    m_size = 0;
    m_data = new T[m_capacity]();
}

~CustomVector()
{
    if (m_data != nullptr)
        delete[] m_data;
}

void reserve(size_t new_capacity)
{
    if (m_data == nullptr)
    {
        m_capacity = new_capacity;
        m_size = 0;
        m_data = new T[m_capacity]();
    }
    else if (new_capacity > m_capacity)
    {
        T* new_data = new T[new_capacity]();
        memmove(new_data, m_data, (m_size) * sizeof(T));
        delete[] m_data;
        m_capacity = new_capacity;
        m_data = new_data;
    }
}

void push_back(const T & value)
{
    if (m_data == nullptr)
    {
        m_capacity = 1;
        m_size = 0;
        m_data = new T[m_capacity]();
        m_data[0] = value;
    }
    else if (m_size + 1 >= m_capacity)
    {
        reserve(m_capacity*2);
    }
    else
    {
        m_data[m_size-1] = value;
        m_size++;
    }
}

};

Now, to facilitate seeing the problem, I also create a class called Object. Each new instance of such class that is created automatically receives an unique id number:

class Object
{
private:
    static int idCounter;
public:
    int id;
    Object()
    {
        id = idCounter;
        idCounter++;
    }
};
int Object::idCounter = 0;

Lastly, here is how the main function of this example looks like:

int main()
{
    CustomVector<Object> objects; //comment this line...
    //std::vector<Object> objects; //...and uncomment this to try with std::vector
Object x;
printf("%d\n", x.id);
objects.push_back(x);

Object y;
printf("%d\n", y.id);
objects.push_back(y);

Object z;
printf("%d ", z.id);

system("Pause");
return 0;

}

The output, using my CustomVector as the container, is:

0 2 5

While the output using a std::vector as the container is:

0 1 2

The desirable behavior for me is exactly that of std::vector, that is, pushing back instances of classes should create full new temporary instances of such class.

Could someone help me understand what am I doing wrong?

Body:
The problem is most likely this line in the push_back function:

m_data = new T[m_capacity]();

This will cause the creation of m_capacity number of T objects, and therefore m_capacity calls to the T constructor. This is bad if the T constructor is expensive (not to mention some beginners do input and other things in the constructor).

What std::vector most likely does is keeping a buffer of bytes, and then when pushing back it does placement new to construct an object in place in some position in the buffer.


问:
Java: Parsing nested array in Jackson
I am trying to parse the following json into Java objects. It has an outer object called BaseCategory.  BaseCategory has a Set of Category objects.  A Category has a set of SubCategory Objects.

```<code>{
   "name":"base",
   "categories":[
        {
            "name":"category1",
            "subCategories": [
                   {
                       "name":"subCategory1"
                   },
                   {
                        "name": "subCategory2"
                   }
             ]
        },
        {
              "name":"category2",
              "subCategories": [
                    {
                          "name":"subCategory3"
                    },
                    {
                          "name": "subCategory4"
                    }
              ]

        }
   ]
}
</code>```

The POJO classes are below.  Stripped down to show just the relevant info.  Could you please provide some help to parse this.

```<code>public class BaseCategory {
    private String name;
    private Set<Category> categories = new HashSet<Category>();
    //setters and getters
}

public class Category {
    private String name;
    private Set<SubCategory> subCategories = new HashSet<SubCategory>();
    //setters and getters
}

public class SubCategory {
     private String name;
     //setters and getters
}
</code>```

答: Use the following website, it will create your POJO's and you can use it directly. Link</p>

Title: Java: Parsing nested array in Jackson

Body:
I am trying to parse the following json into Java objects. It has an outer object called BaseCategory.  BaseCategory has a Set of Category objects.  A Category has a set of SubCategory Objects.

{
   "name":"base",
   "categories":[
        {
            "name":"category1",
            "subCategories": [
                   {
                       "name":"subCategory1"
                   },
                   {
                        "name": "subCategory2"
                   }
             ]
        },
        {
              "name":"category2",
              "subCategories": [
                    {
                          "name":"subCategory3"
                    },
                    {
                          "name": "subCategory4"
                    }
              ]

        }
   ]
}

The POJO classes are below.  Stripped down to show just the relevant info.  Could you please provide some help to parse this.

public class BaseCategory {
    private String name;
    private Set<Category> categories = new HashSet<Category>();
    //setters and getters
}

public class Category {
    private String name;
    private Set<SubCategory> subCategories = new HashSet<SubCategory>();
    //setters and getters
}

public class SubCategory {
     private String name;
     //setters and getters
}


问:
How to set Total Price with a quantity option list using Jquery
I'm just trying to adjust the total price dynamically when a quantity from 1-5 is selected. I am new to using Jquery so any help is greatly appreciated, thank you!

HTML:

```<code><table>
    <thead>
        <tr>
            <th>Quantity</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <select id="quantity">
                    <option data-quantity="1">1</option>
                    <option data-quantity="2">2</option>
                    <option data-quantity="3">3</option>
                    <option data-quantity="4">4</option>
                </select>
            </td>
            <td id="price" data-price="@i.Price">$@i.Price</td>
        </tr>
    </tbody>
</table>

<p>Total Price: $<span id="total></span></p>
</code>```

JAVASCRIPT:

```<code><script>
    $(document).ready(function () {

        var p = $("#price").find("[data-price]")

        $("#quantity").change(function () {
            var q = $(this).find(':selected').data('quantity');
            var total = p * q;
            $("#total").text(total);
        });
    });
</script>
</code>```

答:
The issue seems to be with this line var p = $("#price").find("[data-price]"), You may need the quantity

Change to

```<code>var p = $("#price").data("price");
</code>```

Body:
I'm just trying to adjust the total price dynamically when a quantity from 1-5 is selected. I am new to using Jquery so any help is greatly appreciated, thank you!

HTML:

            Quantity
            Price

                <select id="quantity">
                    <option data-quantity="1">1</option>
                    <option data-quantity="2">2</option>
                    <option data-quantity="3">3</option>
                    <option data-quantity="4">4</option>
                </select>

            $@i.Price

Total Price: $

JAVASCRIPT:

Body:
The issue seems to be with this line var p = $("#price").find("[data-price]"), You may need the quantity

Change to

var p = $("#price").data("price");


问:
How to Set An HTML SELECT element value to php variable ONSELECT
I am Using an HTML dropdown on a page, my requirement is to when i select any value from dropdown, it want to be store in an PHP variable on the same page without submitting form or without refreshing the page.

my code is:

Script:

```<code>    <script type="text/javascript">
    $("#bank_name").change(function(){

    var data=$(this).val();
    alert(data);

    $.ajax({
        url:"transaction.php",
        type:"POST",
        data: ({"bank_code": data}),
        sucess: function(response){
        console.log("Success");
        alert(data);
    },

    error: function(response){
        console.log("Error");
        alert(data);
    }
    });
    <script>
</code>```

PHP Code:

```<code>    $bank_code=$_POST["bank_code"];
    echo "Bank Code is:",$bank_code;
</code>```

it gets the value of selected option and also alerts the value but after alert it doesn't echo the value in PHP.

答:
The echo will be received as response in the success callback

```<code>$("#bank_name").change(function() {

      var data = $(this).val();
      alert(data);

      $.ajax({
       ....,
        success: function(response) {
          console.log("Success");
          // alert response instead
          alert(response);

        },

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

Body:
The echo will be received as response in the success callback

$("#bank_name").change(function() {

      var data = $(this).val();
      alert(data);

      $.ajax({
       ....,
        success: function(response) {
          console.log("Success");
          // alert response instead
          alert(response);

        },

       ......
      });


问:
Search for the original date - MYSQL
I need to find the original date of a pedimento (CUSTOMS document)
I have 2 tables DS_551 (The details table) and DS_701 the rectified pedimentos table.

And the structure of the tables are similar to this

DS_551

Patente

Pedimento

Aduana

Fecha Pago

Value

DS_701

Patente

Pedimento

Aduana

Fecha Pago

PatenteAnterior

PedimentoAnterior

AduanaAnterior

FechaAnterior

And i need to find the original date per example:

Format: (Patente-Pedimento-Aduana)

Original pedimento: 4020-8000001-400

1st rectification: 4020-8009005-400

2nd rectification: 4020-9001003-400

In all the cases i would have on my table (DS_551) only the last rectification in this case the 2nd (4020-9001003-400) but i need to update the row with the original pedimento date a.k.a fecha (4020-8000001-400)

on my table DS_701 the rows are similar to this

```<code>Patente|Pedimento|Aduana|Fecha Pago|PatenteAnterior|PedimentoAnterior|AduanaAnterior|FechaAnterior|
4020|9001003|400|2017-11-17|4020|8009005|400|2017-10-17|
4020|8009005|400|2017-10-17|4020|8000001|400|2016-01-01|
</code>```

In the example above the 1st row references to the data of the 2nd rectification and the previus document (the 1st rectification) and the 2nd row references to the data of the 1st rectification and the original document in the tables the word at the end "Anterior" references to the previus document data, so only having the data 4020|9001003|400 i need to find the date (fecha) of the document 4020|8000001|400

```<code>SELECT * FROM DS_551 WHERE CONCAT(Patente, Pedimento, Aduana) IN (SELECT CONCAT(Patente, Pedimento, Aduana) FROM DS_701)
</code>```

the above query returns the list of the documents that i need to find the original date or the documents that have an rectification.

given the above list of documents how i can loop over each item to find the original date of them?? each document can have infinite number of rectifications.

I'm doing this on a stored procedure on MYSQL

Fiddle: http://sqlfiddle.com/#!9/64f0a5/12

答:
Edit:
Try this instead http://sqlfiddle.com/#!9/64f0a5/45

```<code>SELECT a.original_pedimento, a.original_fecha, b.*
FROM
    (
    SELECT  patente,
            aduana,
            MIN(CAST(pedimentoanterior AS UNSIGNED)) AS original_pedimento,
            MIN(CAST(fechaanterior AS DATE)) AS original_fecha
    FROM ds_701
    GROUP BY patente , aduana
    ) a INNER JOIN ds_701 b
            ON  a.patente = b.patente
            AND a.aduana = b.aduana
</code>```

Deleted / Ignore:

```
<code><s>SELECT *
FROM DS_701
WHERE Patente = '4020' and Aduana = '400'
ORDER BY CAST(PedimentoAnterior as unsigned) ASC
LIMIT 1;
</s></code>```

Title: Search for the original date - MYSQL

Body:
I need to find the original date of a pedimento (CUSTOMS document)
I have 2 tables DS_551 (The details table) and DS_701 the rectified pedimentos table.

And the structure of the tables are similar to this

DS_551

Patente

Pedimento

Aduana

Fecha Pago

Value

DS_701

Patente

Pedimento

Aduana

Fecha Pago

PatenteAnterior

PedimentoAnterior

AduanaAnterior

FechaAnterior

And i need to find the original date per example:

Format: (Patente-Pedimento-Aduana)

Original pedimento: 4020-8000001-400

1st rectification: 4020-8009005-400

2nd rectification: 4020-9001003-400

In all the cases i would have on my table (DS_551) only the last rectification in this case the 2nd (4020-9001003-400) but i need to update the row with the original pedimento date a.k.a fecha (4020-8000001-400)

on my table DS_701 the rows are similar to this

Patente|Pedimento|Aduana|Fecha Pago|PatenteAnterior|PedimentoAnterior|AduanaAnterior|FechaAnterior|
4020|9001003|400|2017-11-17|4020|8009005|400|2017-10-17|
4020|8009005|400|2017-10-17|4020|8000001|400|2016-01-01|

In the example above the 1st row references to the data of the 2nd rectification and the previus document (the 1st rectification) and the 2nd row references to the data of the 1st rectification and the original document in the tables the word at the end "Anterior" references to the previus document data, so only having the data 4020|9001003|400 i need to find the date (fecha) of the document 4020|8000001|400

SELECT * FROM DS_551 WHERE CONCAT(Patente, Pedimento, Aduana) IN (SELECT CONCAT(Patente, Pedimento, Aduana) FROM DS_701)

the above query returns the list of the documents that i need to find the original date or the documents that have an rectification.

given the above list of documents how i can loop over each item to find the original date of them?? each document can have infinite number of rectifications.

I'm doing this on a stored procedure on MYSQL

Fiddle: http://sqlfiddle.com/#!9/64f0a5/12

Body:
Edit:
Try this instead http://sqlfiddle.com/#!9/64f0a5/45

SELECT a.original_pedimento, a.original_fecha, b.*
FROM
    (
    SELECT  patente,
            aduana,
            MIN(CAST(pedimentoanterior AS UNSIGNED)) AS original_pedimento,
            MIN(CAST(fechaanterior AS DATE)) AS original_fecha
    FROM ds_701
    GROUP BY patente , aduana
    ) a INNER JOIN ds_701 b
            ON  a.patente = b.patente
            AND a.aduana = b.aduana

Deleted / Ignore:

<s>SELECT *
FROM DS_701
WHERE Patente = '4020' and Aduana = '400'
ORDER BY CAST(PedimentoAnterior as unsigned) ASC
LIMIT 1;
</s>


问:
Laravel Socialite Facebook Login Error: The parameter app_id is required
Trying to get socialite to work on my app. Facebook returns the The parameter app_id is required error.

Routes:

```<code>Route::get('/login/facebook', '\CommendMe\Http\Controllers\AuthController@redirectToProvider');

Route::get('/login/facebook/callback', '\CommendMe\Http\Controllers\AuthController@handleProviderCallback');
</code>```

services.php:

```<code>'facebook' => [
    'client_id' => env('426129694395672'),
    'client_secret' => env('840fca14fc9fac4b592cd49f285c2ee9'),
    'redirect' => 'http://localhost/login/facebook/callback',
],
</code>```

AuthController.php

```<code>public function redirectToProvider() {
    return Socialite::driver('facebook')->redirect();
}

public function handleProviderCallback() {
    $user = Socialite::driver('facebook')->user();

    $user->name;
}
</code>```

When trying the /login/facebook route, facebook returns this error.
Why is this happening?

答:
Assuming that you have the following in your .env file:

```<code>CLIENT_ID=426129694395672
CLIENT_SECRET=840fca14fc9fac4b592cd49f285c2ee9
</code>```

The facebook[] in your services.php should be like this:

```<code>'facebook' => [
    'client_id' => env('CLIENT_ID'),
    'client_secret' => env('CLIENT_SECRET'),
    'redirect' => 'http://localhost/login/facebook/callback',
],
</code>```

Body:
Trying to get socialite to work on my app. Facebook returns the The parameter app_id is required error.

Routes:

Route::get('/login/facebook', '\CommendMe\Http\Controllers\AuthController@redirectToProvider');

Route::get('/login/facebook/callback', '\CommendMe\Http\Controllers\AuthController@handleProviderCallback');

services.php:

'facebook' => [
    'client_id' => env('426129694395672'),
    'client_secret' => env('840fca14fc9fac4b592cd49f285c2ee9'),
    'redirect' => 'http://localhost/login/facebook/callback',
],

AuthController.php

public function redirectToProvider() {
    return Socialite::driver('facebook')->redirect();
}

public function handleProviderCallback() {
    $user = Socialite::driver('facebook')->user();

    $user->name;
}

When trying the /login/facebook route, facebook returns this error.
Why is this happening?

Body:
Assuming that you have the following in your .env file:

CLIENT_ID=426129694395672
CLIENT_SECRET=840fca14fc9fac4b592cd49f285c2ee9

The facebook[] in your services.php should be like this:

'facebook' => [
    'client_id' => env('CLIENT_ID'),
    'client_secret' => env('CLIENT_SECRET'),
    'redirect' => 'http://localhost/login/facebook/callback',
],


问:
How to refresh an id_token
In the OpenID Connect Core 1.0 incorporating errata set 1 Section 12.2 is says:

```<code>12.2.  Successful Refresh Response

Upon successful validation of the Refresh Token, the response body is the Token Response of Section 3.1.3.3 except that it might not contain an id_token.
</code>```

Originally when the id_token is acquired, it is a signed, and perhaps encrypted, JWT.
The id_token is then forward to other services within the same security domain.
These other services require an assurance that the end-user has authenticated the request.
This works well on the original request.
However, in the refresh scenario, and if the id_token is expired, the "other services" have no method to confirm the user.

Sure the same information is available at the user info endpoint but this requires the "other services" to obtain the access token.
Based on the least principle principals the Access Token has more privileges  than the id_token being forwarded.

The only other option I am aware of is to copy the id_token into another JWT and send it but this is of course more "make work".

It seems to me that NOT returning an id_token is an issue if there were not scope changes from the original request.

答:
OpenID Connect protocol leaves some implementation decisions to the implementer. This scenario you described is one such thing. But I see several options you can try out,

prompt=none

This allows a SSO behavior between authorization server

If the mentioned dependent services can consume the same shared session with authorization server, they can use prompt=none to obtain an interaction free id token.

The Authorization Server MUST NOT interact with the End-User in the following case:

The Authentication Request contains the prompt parameter with the
value none. In this case, the Authorization Server MUST return an
error if an End-User is not already Authenticated or could not be
silently Authenticated.

Also, the authorization request can be sent with a minimal scope values if these dependent services have such requirement.

Session sharing

What if mentioned services reside inside the same domain and share the same session. Won't that make them to share the same principal.? This means you won't have to share id token with dependent services at all.

Title: How to refresh an id_token

Body:
In the OpenID Connect Core 1.0 incorporating errata set 1 Section 12.2 is says:

12.2.  Successful Refresh Response

Upon successful validation of the Refresh Token, the response body is the Token Response of Section 3.1.3.3 except that it might not contain an id_token.

Originally when the id_token is acquired, it is a signed, and perhaps encrypted, JWT.
The id_token is then forward to other services within the same security domain.
These other services require an assurance that the end-user has authenticated the request.
This works well on the original request.
However, in the refresh scenario, and if the id_token is expired, the "other services" have no method to confirm the user.

Sure the same information is available at the user info endpoint but this requires the "other services" to obtain the access token.
Based on the least principle principals the Access Token has more privileges  than the id_token being forwarded.

The only other option I am aware of is to copy the id_token into another JWT and send it but this is of course more "make work".

It seems to me that NOT returning an id_token is an issue if there were not scope changes from the original request.


问:
SCSS for a top bar
I want to put a background gradient topbar behind a link but I'm not able to figure out the styling. There is empty space around the topbar although the padding is 0px and the link is not coming out as white.

This should be very simple but apparently not so for a styling newbie like me
:-(
Thanks!

```<code><main class="col-md-9 float-left col px-5 pl-md-2 pt-2 main">
    <div class="topbar">
        <a href="#" data-target="#sidebar" data-toggle="collapse">
            <i class="fa fa-navicon fa-2x py-2 p-1"></i>
        </a>
    </div>
    <router-outlet></router-outlet>
</main>

.topbar {
  background: linear-gradient(#004812, #0B7225, #3A9250);
  padding : 0px;
  &::a {
    color:white
  }
}
</code>```

答:
your code is working correctly. I can't find any problem. If your styles doesn't work, try to check other styles that you have and set to parent or divs

```<code>.topbar {
    width:100px;
    height:100px;
    background: -webkit-linear-gradient(#004812, #0B7225, #3A9250);
    background: -moz-linear-gradient(#004812, #0B7225, #3A9250);
    background: -o-linear-gradient(#004812, #0B7225, #3A9250);
    background: linear-gradient(#004812, #0B7225, #3A9250);
    padding : 0px;
    a {
        color:white
      }
    }
</code>```

jsfiddle

Title: SCSS for a top bar

Body:
I want to put a background gradient topbar behind a link but I'm not able to figure out the styling. There is empty space around the topbar although the padding is 0px and the link is not coming out as white.

This should be very simple but apparently not so for a styling newbie like me
:-(
Thanks!

    <router-outlet></router-outlet>

.topbar {
  background: linear-gradient(#004812, #0B7225, #3A9250);
  padding : 0px;
  &::a {
    color:white
  }
}

Body:
your code is working correctly. I can't find any problem. If your styles doesn't work, try to check other styles that you have and set to parent or divs

.topbar {
    width:100px;
    height:100px;
    background: -webkit-linear-gradient(#004812, #0B7225, #3A9250);
    background: -moz-linear-gradient(#004812, #0B7225, #3A9250);
    background: -o-linear-gradient(#004812, #0B7225, #3A9250);
    background: linear-gradient(#004812, #0B7225, #3A9250);
    padding : 0px;
    a {
        color:white
      }
    }

jsfiddle


问:
Wrong date when using SQL Server stored procedure with Dapper
I am using a stored procedure with Dapper to retrieve data from a table. The stored procedure works fine when executed in SQL Server and returns the required information.

But when I use Dapper to run the stored procedure and retrieve a Date, the Date is returned as 01/01/0001.

Here is my stored procedure  which works perfectly in SQL Server:

```<code>ALTER PROCEDURE [dbo].[spRankings_GetByEventAndGender]
   @Event varchar(50),
   @Gender varchar(10)
AS
BEGIN
    DECLARE @event_factor INT = CASE
                                   WHEN @Event IN ('Javelin', 'Discus', 'Shot Put', 'Hammer', 'Long Jump', 'High Jump', 'Triple Jump', 'Pole Vault')
                                      THEN -1 /* reverse ranking = highest value is best */
                                      ELSE 1  /* normal ranking = lowest value is best */
                                END;

    SELECT
        CASE
           WHEN a.mark = ABS(b.mark)
              THEN CAST(b.rank AS VARCHAR)
              ELSE ''
        END AS [Rank],
        /*
         ,a.athleteid
         ,a.teamid
         ,a.eventid
        */
        CASE
           WHEN @event_factor = -1
              THEN LTRIM(STR(a.mark, 10, 2))
              ELSE FORMAT(DATEADD(SECOND, FLOOR(a.mark), 0),case when a.mark<60 then '' else 'm:' end+'ss')
                 +substring(ltrim((str(cast(a.mark as decimal(12,5))%1,10,2))),2,10)
          end as Mark
         ,a.wind as Wind
         ,d.eventname as [Event]
         ,c.firstname+' '+c.lastname as Athlete
         --,Convert(varchar(10),c.BirthDate,103) as [Birth Date]
         ,c.BirthDate as [BirthDate]

         ,e.teamname as [Team]
         ,a.venue as Venue
         --, Convert(varchar(10),a.PerformanceDate,103) as [Performance Date]
         ,a.PerformanceDate as [Performance Date]
     from dbo.Performances as a
          inner join (select a.PersonId
                            ,a.eventid
                            ,min(a.mark*@event_factor) as mark
                            ,rank() over(partition by a.eventid order by min(a.mark*@event_factor)) as [rank]
                            ,avg(a.mark) as avg_mark
                        from dbo.Performances as a
                             inner join dbo.Persons as b
                                     on b.PersonId=a.PersonId
                             inner join dbo.[Events] as c
                                     on c.eventid=a.eventid
                             inner join dbo.Meets as d
                                    on d.MeetId = a.MeetId
                       where b.gender=@Gender
                         and c.eventname=@Event
                       group by a.PersonId
                               ,a.eventid
                     ) as b
                  on b.eventid=a.eventid
                 and b.PersonId=a.PersonId
          inner join dbo.Persons as c
                  on c.PersonId=a.PersonId
          inner join dbo.events as d
                  on d.eventid=a.eventid
          inner join dbo.teams as e
                  on e.teamid=a.teamid
            inner join dbo.Meets as m
                on m.MeetId = a.MeetId

    order by a.eventid
            ,a.mark*@event_factor
            ,b.[rank]
/*
            ,b.avg_mark
            ,a.athleteid
*/
end
</code>```

The results in SQL Server:

The method that uses Dapper to get the results:

```<code>public List<RankingsModel> GetRankingsByEventAndGender(string eventName, string gender) {
    using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.GetConString("GARanks"))) {
        var output = connection.Query<RankingsModel>($"dbo.spRankings_GetByEventAndGender @Event, @Gender", new { Event=eventName, Gender=gender}).ToList();
        return output;
    }
}
</code>```

The results in my application:

答:
You can probably break the problem down into pieces. First make sure that Dapper is returning the right result set. You could

```<code>connection.Query<Object>
</code>```

or

```<code>connection.Query<dynamic>
</code>```

and inspect the result to see if it has the right DateTime value in it, in debug mode. If it does, then the problem isn't dapper retrieving the results from the database, it's that it can't map it to your POCO/class.

If the result dataset doesn't have the right value of Performance Date, then the problem is with the sql generation that Dapper is doing, and you could look into renaming the column to be without spaces, or pursue that avenue.
Good luck!

Body:
I am using a stored procedure with Dapper to retrieve data from a table. The stored procedure works fine when executed in SQL Server and returns the required information.

But when I use Dapper to run the stored procedure and retrieve a Date, the Date is returned as 01/01/0001.

Here is my stored procedure  which works perfectly in SQL Server:

ALTER PROCEDURE [dbo].[spRankings_GetByEventAndGender]
   @Event varchar(50),
   @Gender varchar(10)
AS
BEGIN
    DECLARE @event_factor INT = CASE
                                   WHEN @Event IN ('Javelin', 'Discus', 'Shot Put', 'Hammer', 'Long Jump', 'High Jump', 'Triple Jump', 'Pole Vault')
                                      THEN -1 /* reverse ranking = highest value is best */
                                      ELSE 1  /* normal ranking = lowest value is best */
                                END;

    SELECT
        CASE
           WHEN a.mark = ABS(b.mark)
              THEN CAST(b.rank AS VARCHAR)
              ELSE ''
        END AS [Rank],
        /*
         ,a.athleteid
         ,a.teamid
         ,a.eventid
        */
        CASE
           WHEN @event_factor = -1
              THEN LTRIM(STR(a.mark, 10, 2))
              ELSE FORMAT(DATEADD(SECOND, FLOOR(a.mark), 0),case when a.mark<60 then '' else 'm:' end+'ss')
                 +substring(ltrim((str(cast(a.mark as decimal(12,5))%1,10,2))),2,10)
          end as Mark
         ,a.wind as Wind
         ,d.eventname as [Event]
         ,c.firstname+' '+c.lastname as Athlete
         --,Convert(varchar(10),c.BirthDate,103) as [Birth Date]
         ,c.BirthDate as [BirthDate]

         ,e.teamname as [Team]
         ,a.venue as Venue
         --, Convert(varchar(10),a.PerformanceDate,103) as [Performance Date]
         ,a.PerformanceDate as [Performance Date]
     from dbo.Performances as a
          inner join (select a.PersonId
                            ,a.eventid
                            ,min(a.mark*@event_factor) as mark
                            ,rank() over(partition by a.eventid order by min(a.mark*@event_factor)) as [rank]
                            ,avg(a.mark) as avg_mark
                        from dbo.Performances as a
                             inner join dbo.Persons as b
                                     on b.PersonId=a.PersonId
                             inner join dbo.[Events] as c
                                     on c.eventid=a.eventid
                             inner join dbo.Meets as d
                                    on d.MeetId = a.MeetId
                       where b.gender=@Gender
                         and c.eventname=@Event
                       group by a.PersonId
                               ,a.eventid
                     ) as b
                  on b.eventid=a.eventid
                 and b.PersonId=a.PersonId
          inner join dbo.Persons as c
                  on c.PersonId=a.PersonId
          inner join dbo.events as d
                  on d.eventid=a.eventid
          inner join dbo.teams as e
                  on e.teamid=a.teamid
            inner join dbo.Meets as m
                on m.MeetId = a.MeetId

    order by a.eventid
            ,a.mark*@event_factor
            ,b.[rank]
/*
            ,b.avg_mark
            ,a.athleteid
*/
end

The results in SQL Server:

The method that uses Dapper to get the results:

public List<RankingsModel> GetRankingsByEventAndGender(string eventName, string gender) {
    using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.GetConString("GARanks"))) {
        var output = connection.Query<RankingsModel>($"dbo.spRankings_GetByEventAndGender @Event, @Gender", new { Event=eventName, Gender=gender}).ToList();
        return output;
    }
}

The results in my application:

Body:
You can probably break the problem down into pieces. First make sure that Dapper is returning the right result set. You could

connection.Query<Object>

or

connection.Query<dynamic>

and inspect the result to see if it has the right DateTime value in it, in debug mode. If it does, then the problem isn't dapper retrieving the results from the database, it's that it can't map it to your POCO/class.

If the result dataset doesn't have the right value of Performance Date, then the problem is with the sql generation that Dapper is doing, and you could look into renaming the column to be without spaces, or pursue that avenue.
Good luck!