问:
Searching Message For Key Words In Outlook
When sending an email, I want to search the recipients of the email as well as the email body for certain key works, and if found, pop up a message to confirm sending.

I am able to get a pop up when the user hits the send key. I'm unable to access the recipient or message objects to search them.

```<code>Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim xPrompt As String
Dim xOkOrCancel As Integer
On Error Resume Next
xPrompt = "Do you want to continue sending the email?"
xOkOrCancel = MsgBox(xPrompt, vbOKCancel)
If xOkOrCancel <> vbOK Then
    Cancel = True
End If
End Sub
</code>```

I added the following code to try to see the recipient, but it is not returning anything.

```<code>Set myAddressEntry = myRecipient.AddressEntry
xPrompt = Trim(myAddressEntry)
xOkOrCancel = MsgBox(xPrompt, vbOKCancel)
</code>```

答:
You are passing a COM object to a function that expects a string. More than that, you don't need the Recipient.AddressEntry property, just work with the Recipient object since it is resolved.

```<code>xPrompt = Trim(myRecipient.Name)
</code>```

I assume you correctly initialize the myRecipient object from the Item.Recipients collection.

Body:
When sending an email, I want to search the recipients of the email as well as the email body for certain key works, and if found, pop up a message to confirm sending.

I am able to get a pop up when the user hits the send key. I'm unable to access the recipient or message objects to search them.

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim xPrompt As String
Dim xOkOrCancel As Integer
On Error Resume Next
xPrompt = "Do you want to continue sending the email?"
xOkOrCancel = MsgBox(xPrompt, vbOKCancel)
If xOkOrCancel <> vbOK Then
    Cancel = True
End If
End Sub

I added the following code to try to see the recipient, but it is not returning anything.

Set myAddressEntry = myRecipient.AddressEntry
xPrompt = Trim(myAddressEntry)
xOkOrCancel = MsgBox(xPrompt, vbOKCancel)

Body:
You are passing a COM object to a function that expects a string. More than that, you don't need the Recipient.AddressEntry property, just work with the Recipient object since it is resolved.

xPrompt = Trim(myRecipient.Name)

I assume you correctly initialize the myRecipient object from the Item.Recipients collection.


来源: stackexchange

问:
How to make any row fixed at the bottom of screen in flutter?
How to make this highlighted row fixed at the bottom of the screen in flutter?

答:
You can also use bottom app bar to make appbar at the bottom of screen. It is also fixed at the bottom of screen.

```<code>bottomNavigationBar: BottomAppBar(
    shape: CircularNotchedRectangle(),
    child: new Row(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        IconButton(
          icon: Icon(Icons.menu),
          color: Colors.white,
          onPressed: () {},
        ),
        IconButton(
          icon: Icon(Icons.search),
          color: Colors.white,
          onPressed: () {},
        ),
      ],
    ),
    color: Colors.blueGrey,
  ),
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can also use bottom app bar to make appbar at the bottom of screen. It is also fixed at the bottom of screen.

bottomNavigationBar: BottomAppBar(
    shape: CircularNotchedRectangle(),
    child: new Row(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        IconButton(
          icon: Icon(Icons.menu),
          color: Colors.white,
          onPressed: () {},
        ),
        IconButton(
          icon: Icon(Icons.search),
          color: Colors.white,
          onPressed: () {},
        ),
      ],
    ),
    color: Colors.blueGrey,
  ),


问:
SQL query, am I wrong somewhere?
I am trying to pull distinct City names and only one zipcode for any given City.

```<code>zip city    state
00603   AGUADILLA   PR
00604   AGUADILLA   PR
00605   AGUADILLA   PR
</code>```

Query:

```<code>SELECT DISTINCT (city),(zip)
  FROM zips
 WHERE state = 'PR'
</code>```

I tried group by clause as well, let me know where am I wrong here.

答:
```<code>select city, max(zip)
from zips
where state='PR'
group by city
</code>```

ContentLicense: CC BY-SA 3.0

Title: SQL query, am I wrong somewhere?

Body:
I am trying to pull distinct City names and only one zipcode for any given City.

zip city    state
00603   AGUADILLA   PR
00604   AGUADILLA   PR
00605   AGUADILLA   PR

Query:

SELECT DISTINCT (city),(zip)
  FROM zips
 WHERE state = 'PR'

I tried group by clause as well, let me know where am I wrong here.


问:
VueJS/Vuetify - Add some text to focus position on textarea
I try to add somes text (tags) in Vuetify textarea from button.

```<code><v-btn small flat @click.stop="insertTag('{{title}}', <model-name-here>)">+ Title</v-btn>
</code>```

The method insertTag provide this:

```<code>this.$refs[model][0].focus()
</code>```

I don't know how I can insert text to cursor position in textarea...

答:
```<code> <v-textarea label="Текст сообщения" v-model="text_sms" ref="ref_text_sms"></v-textarea>

 methods: {
insert() {
  const el = this.$refs.ref_text_sms.$el.querySelector("textarea");
  let cursorPos = el.selectionEnd;
  this.text_sms = this.text_sms.substring(0, cursorPos) + "my_test" +  this.text_sms.substring(cursorPos);
  cursorPos += this.text_sms.length;
  this.$nextTick(() => el.setSelectionRange(cursorPos, cursorPos));
},
</code>```

Body:
I try to add somes text (tags) in Vuetify textarea from button.

<v-btn small flat @click.stop="insertTag('{{title}}', <model-name-here>)">+ Title</v-btn>

The method insertTag provide this:

this.$refs[model][0].focus()

I don't know how I can insert text to cursor position in textarea...


问:
Accessing private property in PHP Guzzle Response object
I tried to access to statuscode and reasonphrase but the bellow code returns erros like

```<code>die(var_dump($registrant->response->reasonPhrase));
</code>```

error:

"message": "Undefined property:
  MacsiDigital\Zoom\Support\Response::$reasonPhrase",

code: ( RESULT OF var_dump($registrant->getResponse()); )

```<code> object(MacsiDigital\Zoom\Support\Response)#874 (1) {
  ["response":protected]=>
  object(GuzzleHttp\Psr7\Response)#885 (6) {
    ["reasonPhrase":"GuzzleHttp\Psr7\Response":private]=>
    string(7) "Created"
    ["statusCode":"GuzzleHttp\Psr7\Response":private]=>
    int(201)
    ["headers":"GuzzleHttp\Psr7\Response":private]=>
    array(14) {
      ["Date"]=>
      array(1) {
        [0]=>
        string(29) "Sun, 16 Feb 2020 05:56:11 GMT"
      }
      ["Content-Type"]=>
      array(1) {
        [0]=>
        string(30) "application/json;charset=UTF-8"
      }
      ["Content-Length"]=>
      array(1) {
        [0]=>
        string(3) "249"
      }
      ["Connection"]=>
      array(1) {
        [0]=>
        string(10) "keep-alive"
      }
      ["Server"]=>
      array(1) {
        [0]=>
        string(4) "ZOOM"
      }
      ["x-zm-trackingid"]=>
      array(1) {
        [0]=>
        string(36) ""
      }
      ["X-Content-Type-Options"]=>
      array(1) {
        [0]=>
        string(7) "nosniff"
      }
      ["Cache-Control"]=>
      array(1) {
        [0]=>
        string(49) "no-cache, no-store, must-revalidate, no-transform"
      }
      ["Pragma"]=>
      array(1) {
        [0]=>
        string(8) "no-cache"
      }
      ["Expires"]=>
      array(1) {
        [0]=>
        string(29) "Thu, 01 Jan 1970 00:00:00 GMT"
      }
      ["Set-Cookie"]=>
      array(1) {
        [0]=>
        string(63) "cred=; Path=/; Secure; HttpOnly"
      }
      ["Strict-Transport-Security"]=>
      array(1) {
        [0]=>
        string(16) "max-age=31536000"
      }
      ["X-XSS-Protection"]=>
      array(1) {
        [0]=>
        string(13) "1; mode=block"
      }
      ["Referrer-Policy"]=>
      array(1) {
        [0]=>
        string(31) "strict-origin-when-cross-origin"
      }
    }
    ["headerNames":"GuzzleHttp\Psr7\Response":private]=>
    array(14) {
      ["date"]=>
      string(4) "Date"
      ["content-type"]=>
      string(12) "Content-Type"
      ["content-length"]=>
      string(14) "Content-Length"
      ["connection"]=>
      string(10) "Connection"
      ["server"]=>
      string(6) "Server"
      ["x-zm-trackingid"]=>
      string(15) "x-zm-trackingid"
      ["x-content-type-options"]=>
      string(22) "X-Content-Type-Options"
      ["cache-control"]=>
      string(13) "Cache-Control"
      ["pragma"]=>
      string(6) "Pragma"
      ["expires"]=>
      string(7) "Expires"
      ["set-cookie"]=>
      string(10) "Set-Cookie"
      ["strict-transport-security"]=>
      string(25) "Strict-Transport-Security"
      ["x-xss-protection"]=>
      string(16) "X-XSS-Protection"
      ["referrer-policy"]=>
      string(15) "Referrer-Policy"
    }
    ["protocol":"GuzzleHttp\Psr7\Response":private]=>
    string(3) "1.1"
    ["stream":"GuzzleHttp\Psr7\Response":private]=>
    object(GuzzleHttp\Psr7\Stream)#883 (7) {
      ["stream":"GuzzleHttp\Psr7\Stream":private]=>
      resource(650) of type (stream)
      ["size":"GuzzleHttp\Psr7\Stream":private]=>
      NULL
      ["seekable":"GuzzleHttp\Psr7\Stream":private]=>
      bool(true)
      ["readable":"GuzzleHttp\Psr7\Stream":private]=>
      bool(true)
      ["writable":"GuzzleHttp\Psr7\Stream":private]=>
      bool(true)
      ["uri":"GuzzleHttp\Psr7\Stream":private]=>
      string(10) "php://temp"
      ["customMetadata":"GuzzleHttp\Psr7\Stream":private]=>
      array(0) {
      }
    }
  }
}
</code>```

PS. : when I trie to access like this it returns Null

```<code>$registrant->reasonPhrase
</code>```

答:
To inspect the private properties of your MacsiDigital\Zoom\Support\Response Obj, you have no choice but using setter/getter methods.

Try

```<code>dump($registrant->getResponse());
</code>```

Then

```<code>dump(($registrant->getResponse())->getReasonPhrase());
</code>```

Body:
I tried to access to statuscode and reasonphrase but the bellow code returns erros like

die(var_dump($registrant->response->reasonPhrase));

error:

"message": "Undefined property:
  MacsiDigital\Zoom\Support\Response::$reasonPhrase",

code: ( RESULT OF var_dump($registrant->getResponse()); )

 object(MacsiDigital\Zoom\Support\Response)#874 (1) {
  ["response":protected]=>
  object(GuzzleHttp\Psr7\Response)#885 (6) {
    ["reasonPhrase":"GuzzleHttp\Psr7\Response":private]=>
    string(7) "Created"
    ["statusCode":"GuzzleHttp\Psr7\Response":private]=>
    int(201)
    ["headers":"GuzzleHttp\Psr7\Response":private]=>
    array(14) {
      ["Date"]=>
      array(1) {
        [0]=>
        string(29) "Sun, 16 Feb 2020 05:56:11 GMT"
      }
      ["Content-Type"]=>
      array(1) {
        [0]=>
        string(30) "application/json;charset=UTF-8"
      }
      ["Content-Length"]=>
      array(1) {
        [0]=>
        string(3) "249"
      }
      ["Connection"]=>
      array(1) {
        [0]=>
        string(10) "keep-alive"
      }
      ["Server"]=>
      array(1) {
        [0]=>
        string(4) "ZOOM"
      }
      ["x-zm-trackingid"]=>
      array(1) {
        [0]=>
        string(36) ""
      }
      ["X-Content-Type-Options"]=>
      array(1) {
        [0]=>
        string(7) "nosniff"
      }
      ["Cache-Control"]=>
      array(1) {
        [0]=>
        string(49) "no-cache, no-store, must-revalidate, no-transform"
      }
      ["Pragma"]=>
      array(1) {
        [0]=>
        string(8) "no-cache"
      }
      ["Expires"]=>
      array(1) {
        [0]=>
        string(29) "Thu, 01 Jan 1970 00:00:00 GMT"
      }
      ["Set-Cookie"]=>
      array(1) {
        [0]=>
        string(63) "cred=; Path=/; Secure; HttpOnly"
      }
      ["Strict-Transport-Security"]=>
      array(1) {
        [0]=>
        string(16) "max-age=31536000"
      }
      ["X-XSS-Protection"]=>
      array(1) {
        [0]=>
        string(13) "1; mode=block"
      }
      ["Referrer-Policy"]=>
      array(1) {
        [0]=>
        string(31) "strict-origin-when-cross-origin"
      }
    }
    ["headerNames":"GuzzleHttp\Psr7\Response":private]=>
    array(14) {
      ["date"]=>
      string(4) "Date"
      ["content-type"]=>
      string(12) "Content-Type"
      ["content-length"]=>
      string(14) "Content-Length"
      ["connection"]=>
      string(10) "Connection"
      ["server"]=>
      string(6) "Server"
      ["x-zm-trackingid"]=>
      string(15) "x-zm-trackingid"
      ["x-content-type-options"]=>
      string(22) "X-Content-Type-Options"
      ["cache-control"]=>
      string(13) "Cache-Control"
      ["pragma"]=>
      string(6) "Pragma"
      ["expires"]=>
      string(7) "Expires"
      ["set-cookie"]=>
      string(10) "Set-Cookie"
      ["strict-transport-security"]=>
      string(25) "Strict-Transport-Security"
      ["x-xss-protection"]=>
      string(16) "X-XSS-Protection"
      ["referrer-policy"]=>
      string(15) "Referrer-Policy"
    }
    ["protocol":"GuzzleHttp\Psr7\Response":private]=>
    string(3) "1.1"
    ["stream":"GuzzleHttp\Psr7\Response":private]=>
    object(GuzzleHttp\Psr7\Stream)#883 (7) {
      ["stream":"GuzzleHttp\Psr7\Stream":private]=>
      resource(650) of type (stream)
      ["size":"GuzzleHttp\Psr7\Stream":private]=>
      NULL
      ["seekable":"GuzzleHttp\Psr7\Stream":private]=>
      bool(true)
      ["readable":"GuzzleHttp\Psr7\Stream":private]=>
      bool(true)
      ["writable":"GuzzleHttp\Psr7\Stream":private]=>
      bool(true)
      ["uri":"GuzzleHttp\Psr7\Stream":private]=>
      string(10) "php://temp"
      ["customMetadata":"GuzzleHttp\Psr7\Stream":private]=>
      array(0) {
      }
    }
  }
}

PS. : when I trie to access like this it returns Null

$registrant->reasonPhrase

Body:
To inspect the private properties of your MacsiDigital\Zoom\Support\Response Obj, you have no choice but using setter/getter methods.

Try

dump($registrant->getResponse());

Then

dump(($registrant->getResponse())->getReasonPhrase());


问:
Svelte v3 programmatically create a component with props and event listeners
Is it possible to create a component and programmatically attach event listeners to it?

I know that this is easily possible for props using <svelte:component/> by spreading with { ...props }. I wonder if something similar can be achieved to attach event listeners.

E.g., in the following example I would like to programmatically attach on:message to A and on:count to B:

```<code><!-- App.svelte -->
<script>
    import A from './A.svelte';
    import B from './B.svelte';

    let message = 'Hi there ';
    let count = 0;

    const components = [{
        component: A,
        props: { message },
        listeners: { message: (m) => { console.log(`They say "${m}"`); } }
    }, {
        component: B,
        props: { count },
        listeners: { click: () => { count++; } }
    }];
</script>

{#each components as component}
    <div><svelte:component this={component.component} { ...component.props }/></div>
{/each}

<div>
    <p>They say "{message}"!</p>
    <p>They clicked {count} times!</p>
</div>

<!-- A.svelte -->
<script>
    import { createEventDispatcher } from 'svelte';
    const dispatch = createEventDispatcher();
    export let message = '';
    function changeHandler(e) { dispatch('message', message); }
</script>

<input on:change={changeHandler} on:value={message} value={message} />

<!-- B.svelte -->
<script>
    import { createEventDispatcher } from 'svelte';
    const dispatch = createEventDispatcher();
    export let count = 0;
    function clickHandler() { dispatch('count', count); }
</script>

<button on:click={clickHandler}>Click me</button>
</code>```

Here's a live demo: https://svelte.dev/repl/af1bd30ab75b43f19b72a306340b7282?version=3.18.2

I.e., I am hoping there's a way to expand the components array to

```<code><A message={message} on:message={e => { message = e.detail; }}/>
<B count={count} on:count={e => { count = e.detail; }}/>
</code>```

答:
Not sure you can programmatically attach them like you're looking for but you can pass a function, or a callback in the object and account for each of the potential dispatched events in the svelte:component tag like this:

```<code><svelte:component
    this={component.component}
    { ...component.props }
    on:message={ component.function}
    on:count={ component.function}
/>
</code>```

Here's a working example in the REPL that shows both an arrow function in the object and a callback(if a more meaty function is needed) the callback still gets the event detail.

I don't think anything happens if the dispatched event is not present in a component, but if you needed a single component to dispatch multiple events you would need something else.

Body:
Is it possible to create a component and programmatically attach event listeners to it?

I know that this is easily possible for props using <svelte:component/> by spreading with { ...props }. I wonder if something similar can be achieved to attach event listeners.

E.g., in the following example I would like to programmatically attach on:message to A and on:count to B:

{#each components as component}

<svelte:component this={component.component} { ...component.props }/>

{/each}

They say "{message}"!

They clicked {count} times!

<input on:change={changeHandler} on:value={message} value={message} />

<button on:click={clickHandler}>Click me</button>

Here's a live demo: https://svelte.dev/repl/af1bd30ab75b43f19b72a306340b7282?version=3.18.2

I.e., I am hoping there's a way to expand the components array to

 { message = e.detail; }}/>
 { count = e.detail; }}/>

Body:
Not sure you can programmatically attach them like you're looking for but you can pass a function, or a callback in the object and account for each of the potential dispatched events in the svelte:component tag like this:

<svelte:component
    this={component.component}
    { ...component.props }
    on:message={ component.function}
    on:count={ component.function}
/>

Here's a working example in the REPL that shows both an arrow function in the object and a callback(if a more meaty function is needed) the callback still gets the event detail.

I don't think anything happens if the dispatched event is not present in a component, but if you needed a single component to dispatch multiple events you would need something else.


问:
POSTING a custom object with Retrofit2 issue
I'm currently making my first custom Android app for a project and I can't resolve the following issue. (I made a lot of research but didn't find anything like this)

```<code>2020-02-15 11:41:30.075 10337-10337/com.example.quickmatch I/SigninFragmentViewModel: Required value 'surname' missing at $post
</code>```

I'm trying to post this custom object to my backend server online :

```<code>@JsonClass(generateAdapter = true)
data class PlayerObject(
        val id : Int?,
        @Json(name = "surname") val surname : String,
        @Json(name = "first_name") val firstName : String,
        val pseudo : String,
        @Json(name = "mdp") val password : String,
        @Json(name = "mail_address") val mailAddress : String,
        @Json(name = "phone_number") val phoneNumber : String?,
        @Json(name = "scored_goals") val scoredGoals : Int,
        @Json(name = "conceded_goals") val concededGoals : Int,
        @Json(name = "matches_played") val matchesPlayed : Int,
        val victories : Int,
        val avatar : String?,
        val bio : String?
)
</code>```

I'm using Retrofit2 and Moshi with coroutines :

```<code>implementation "com.squareup.retrofit2:retrofit:2.5.0"
implementation "com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2"
implementation "com.squareup.retrofit2:converter-moshi:2.5.0"
</code>```

Here is my Retrofit instance :

```<code>/* Create Moshi object which will parse the responses */
private val moshi = Moshi.Builder()
        .add(KotlinJsonAdapterFactory())
        .build()

/* Retrofit builder with converter for response and base url */
private val retrofit = Retrofit.Builder()
        .addConverterFactory(MoshiConverterFactory.create(moshi))
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .baseUrl(BASE_URL)
        .build()
</code>```

To send my POST request I made this method (It should send me back the player created if successful) :

```<code>@POST("...")
fun addPlayer(@Body player: PlayerObject) : Deferred<PlayerObject>
</code>```

And I call it passing this Object :

```<code>var newPlayerObject = PlayerObject(null, name, firstName, pseudo, password, mailAddress, phoneNumber, 0, 0, 0, 0, null, null )
</code>```

I am getting the non-null values from EditTexts with a basic binding.editText.text.toString()
The big problem is that I logged every value (name, surname, etc...) both in my ViewModel before the request and in my UI in the button onClickListener that triggers the ViewModel and everything looks fine and matches what I type in the Edits but when the app posts it seems that every attribute of the object is set to null. Since surname is not nullable I get the previous error. I tried to make it nullable and it is the same issue with the next attributes.
Also note that passing an object with every attribute null works.

答:
I've found specifying use-site targets helpful for fields in a Kotlin data class.

What happens if you try modifying your annotations to the following format?

@field:Json(name = "surname") val surname : String

Body:
I'm currently making my first custom Android app for a project and I can't resolve the following issue. (I made a lot of research but didn't find anything like this)

2020-02-15 11:41:30.075 10337-10337/com.example.quickmatch I/SigninFragmentViewModel: Required value 'surname' missing at $post

I'm trying to post this custom object to my backend server online :

@JsonClass(generateAdapter = true)
data class PlayerObject(
        val id : Int?,
        @Json(name = "surname") val surname : String,
        @Json(name = "first_name") val firstName : String,
        val pseudo : String,
        @Json(name = "mdp") val password : String,
        @Json(name = "mail_address") val mailAddress : String,
        @Json(name = "phone_number") val phoneNumber : String?,
        @Json(name = "scored_goals") val scoredGoals : Int,
        @Json(name = "conceded_goals") val concededGoals : Int,
        @Json(name = "matches_played") val matchesPlayed : Int,
        val victories : Int,
        val avatar : String?,
        val bio : String?
)

I'm using Retrofit2 and Moshi with coroutines :

implementation "com.squareup.retrofit2:retrofit:2.5.0"
implementation "com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2"
implementation "com.squareup.retrofit2:converter-moshi:2.5.0"

Here is my Retrofit instance :

/* Create Moshi object which will parse the responses */
private val moshi = Moshi.Builder()
        .add(KotlinJsonAdapterFactory())
        .build()

/* Retrofit builder with converter for response and base url */
private val retrofit = Retrofit.Builder()
        .addConverterFactory(MoshiConverterFactory.create(moshi))
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .baseUrl(BASE_URL)
        .build()

To send my POST request I made this method (It should send me back the player created if successful) :

@POST("...")
fun addPlayer(@Body player: PlayerObject) : Deferred<PlayerObject>

And I call it passing this Object :

var newPlayerObject = PlayerObject(null, name, firstName, pseudo, password, mailAddress, phoneNumber, 0, 0, 0, 0, null, null )

I am getting the non-null values from EditTexts with a basic binding.editText.text.toString()
The big problem is that I logged every value (name, surname, etc...) both in my ViewModel before the request and in my UI in the button onClickListener that triggers the ViewModel and everything looks fine and matches what I type in the Edits but when the app posts it seems that every attribute of the object is set to null. Since surname is not nullable I get the previous error. I tried to make it nullable and it is the same issue with the next attributes.
Also note that passing an object with every attribute null works.


问:
Functional, Declarative, and Imperative Programming
What do the terms functional, declarative, and imperative programming mean?</p>

答:
There's not really any non-ambiguous, objective definition for these.  Here is how I would define them:

Imperative - The focus is on what steps the computer should take rather than what the computer will do (ex. C, C++, Java).

Declarative - The focus is on what the computer should do rather than how it should do it (ex. SQL).

Functional - a subset of declarative languages that has heavy focus on recursion

OwnerDisplayName: curiouskitty

OwnerDisplayName: Jason Baker

LastEditorDisplayName: Svante


问:
Read Emails from outlook mailbox
Outlook product version : 16.0.1073020348

So I made an script to read emails and insert them into a DB.

The problem: The script is reading currently from my Inbox(red flag) and not from the shared mailbox(blue flag)

Desired Solution: Check the shared mailbox(blue flag)

Currently my code looks something like this:

```<code>Set objOutlook = CreateObject("Outlook.Application")

Set objNamespace = objOutlook.GetNamespace("MAPI")
'PROBLEM HERE I GUESS
Set objFolder = objNamespace.GetDefaultFolder(6) 'Inbox

Set colItems = objFolder.Items

Set colFilteredItems = colItems.Restrict("[Unread]=true")

Set colFilteredItems = colFilteredItems.Restrict("[Subject] = SUBJECT")

For k = colFilteredItems.Count to 1 step -1
    set objMessage  = colFilteredItems.Item(k)
    '....
next
</code>```

Any help appreciated

Tried the method suggested by @josefZ , but keep struggling with it
1st try(failing on last line):

```<code>Set myRecipient = objNamespace.CreateRecipient("mailbox@mail.com")

myRecipient.Resolve

Set objFolder = objNamespace.GetSharedDefaultFolder(myRecipient,olFolderInbox).Folders("Bandeja de Entrada")
</code>```

答: You can either use GetSharedDefaultFolder or, since the delegate store is already opened in the profile, retrieve the delegate mailbox from the Namespace.Stores collection and use Store.GetDefaultFolder instead of Namespace.GetDefaultFolder.

Title: Read Emails from outlook mailbox

Body:
Outlook product version : 16.0.1073020348

So I made an script to read emails and insert them into a DB.

The problem: The script is reading currently from my Inbox(red flag) and not from the shared mailbox(blue flag)

Desired Solution: Check the shared mailbox(blue flag)

Currently my code looks something like this:

Set objOutlook = CreateObject("Outlook.Application")

Set objNamespace = objOutlook.GetNamespace("MAPI")
'PROBLEM HERE I GUESS
Set objFolder = objNamespace.GetDefaultFolder(6) 'Inbox

Set colItems = objFolder.Items

Set colFilteredItems = colItems.Restrict("[Unread]=true")

Set colFilteredItems = colFilteredItems.Restrict("[Subject] = SUBJECT")

For k = colFilteredItems.Count to 1 step -1
    set objMessage  = colFilteredItems.Item(k)
    '....
next

Any help appreciated

Tried the method suggested by @josefZ , but keep struggling with it
1st try(failing on last line):

Set myRecipient = objNamespace.CreateRecipient("mailbox@mail.com")

myRecipient.Resolve

Set objFolder = objNamespace.GetSharedDefaultFolder(myRecipient,olFolderInbox).Folders("Bandeja de Entrada")


问:
NextJS & Typescript getInitialProps linting error (return type)
I've been stuck with this issue for way too long now and no matter what I try I can't get this to work.

I have a simple page called one.tsx. It looks like this:

I'm getting the following linting error: Missing return type on function.eslint(@typescript-eslint/explicit-function-return-type)

Here is my tsconfig.json file:

```<code>{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": false,
    "checkJs": false,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "noUnusedLocals": true /* Report errors on unused locals. */,
    "noUnusedParameters": true /* Report errors on unused parameters. */,
    "noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
    "noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */
  },
  "exclude": ["node_modules", ".next"],
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
}
</code>```

And here is my .eslintrc.json file:

```<code>{
  "env": {
    "browser": true,
    "es6": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:jest/recommended",
    "prettier",
    "airbnb"
  ],
  "globals": {
    "Atomics": "readonly",
    "SharedArrayBuffer": "readonly"
  },
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 2018,
    "sourceType": "module"
  },
  "plugins": ["react", "@typescript-eslint", "prettier", "jest"],
  "settings": {
    "import/resolver": {
      "node": {
        "extensions": [".js", ".jsx", ".ts", ".tsx"]
      }
    }
  },

  "rules": {
    "react/jsx-one-expression-per-line": "off",
    "jsx-a11y/anchor-is-valid": "off", // <a> tags sometimes have their href attr set in <Link> from NextJS.
    // Turn off this rule for ts and tsx files:
    "react/jsx-filename-extension": [
      1,
      { "extensions": [".js", ".jsx", ".ts", ".tsx"] }
    ],
    "import/extensions": [
      "error",
      "ignorePackages",
      {
        // This is so that we can import non-js files.
        "js": "never",
        "jsx": "never",
        "ts": "never",
        "tsx": "never"
      }
    ],
    // Next.JS Doesn't require the import React statement at the top of its pages
    "react/react-in-jsx-scope": "off"
  }
}
</code>```

Here is my package.json:

```<code>{
  "name": "my_app",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "precommit": "npm run build && lint-staged",
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "eslint './**/*.{js,jsx,ts,tsx}' --max-warnings 0",
    "test": "jest --passWithNoTests",
    "test:watch": "jest --watchAll"
  },
  "lint-staged": {
    "*.json": [
      "prettier --write"
    ],
    "./**/*.{js,jsx,ts,tsx,css,scss}": [
      "prettier --write",
      "npm run lint",
      "npm run test"
    ]
  },
  "dependencies": {
    "@testing-library/jest-dom": "^5.1.1",
    "@testing-library/react": "^9.4.0",
    "@types/jest": "^25.1.2",
    "isomorphic-unfetch": "^3.0.0",
    "jest": "^25.1.0",
    "next": "9.2.1",
    "react": "16.12.0",
    "react-dom": "16.12.0",
    "ts-jest": "^25.2.0"
  },
  "devDependencies": {
    "@types/node": "^13.7.0",
    "@types/react": "^16.9.19",
    "@types/react-dom": "^16.9.5",
    "@typescript-eslint/eslint-plugin": "^2.19.0",
    "@typescript-eslint/parser": "^2.19.0",
    "babel-eslint": "^10.0.3",
    "eslint": "^6.8.0",
    "eslint-config-airbnb": "^18.0.1",
    "eslint-config-prettier": "^6.10.0",
    "eslint-loader": "^3.0.3",
    "eslint-plugin-import": "^2.20.1",
    "eslint-plugin-jest": "^23.7.0",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-prettier": "^3.1.2",
    "eslint-plugin-react": "^7.18.3",
    "eslint-plugin-react-hooks": "^1.7.0",
    "lint-staged": "^10.0.7",
    "prettier": "^1.19.1",
    "typescript": "^3.7.5"
  }
}
</code>```

Here is the error I get in the console:

```<code>frontend    | [ event ] build page: /one
frontend    | [ warn ]  ./pages/one.tsx
frontend    | /usr/src/app/packages/frontend/pages/one.tsx
frontend    |   22:23  warning  Missing return type on function  @typescript-eslint/explicit-function-return-type
frontend    |
frontend    | ✖ 1 problem (0 errors, 1 warning)
frontend    | [ info ]  ready on http://localhost:3000
frontend    | [ warn ]  ./pages/one.tsx
frontend    | /usr/src/app/packages/frontend/pages/one.tsx
frontend    |   22:23  warning  Missing return type on function  @typescript-eslint/explicit-function-return-type
frontend    |
frontend    | ✖ 1 problem (0 errors, 1 warning)
frontend    | [ info ]  ready on http://localhost:3000
</code>```

I can manually give it a return type to clear the error, but NextPage should include the types automatically. Here is the snippet of me manually giving it the return type: TestServer.getInitialProps = async (): Promise<Props> => {

I've confirmed that next-env.d.ts file exists, and my VSCode can code jump to the NextPage type definition file located under node_modules/. However, eslint-typescript doesn't seem to acknowledge it. What am I doing wrong?

Thanks

答: Based on this it's a rule and I think you have to obey it or disable it! and I think your question is a duplicate of this.</p>

Body:
I've been stuck with this issue for way too long now and no matter what I try I can't get this to work.

I have a simple page called one.tsx. It looks like this:

I'm getting the following linting error: Missing return type on function.eslint(@typescript-eslint/explicit-function-return-type)

Here is my tsconfig.json file:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": false,
    "checkJs": false,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "noUnusedLocals": true /* Report errors on unused locals. */,
    "noUnusedParameters": true /* Report errors on unused parameters. */,
    "noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
    "noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */
  },
  "exclude": ["node_modules", ".next"],
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
}

And here is my .eslintrc.json file:

{
  "env": {
    "browser": true,
    "es6": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:jest/recommended",
    "prettier",
    "airbnb"
  ],
  "globals": {
    "Atomics": "readonly",
    "SharedArrayBuffer": "readonly"
  },
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 2018,
    "sourceType": "module"
  },
  "plugins": ["react", "@typescript-eslint", "prettier", "jest"],
  "settings": {
    "import/resolver": {
      "node": {
        "extensions": [".js", ".jsx", ".ts", ".tsx"]
      }
    }
  },

  "rules": {
    "react/jsx-one-expression-per-line": "off",
    "jsx-a11y/anchor-is-valid": "off", //  tags sometimes have their href attr set in <Link> from NextJS.
    // Turn off this rule for ts and tsx files:
    "react/jsx-filename-extension": [
      1,
      { "extensions": [".js", ".jsx", ".ts", ".tsx"] }
    ],
    "import/extensions": [
      "error",
      "ignorePackages",
      {
        // This is so that we can import non-js files.
        "js": "never",
        "jsx": "never",
        "ts": "never",
        "tsx": "never"
      }
    ],
    // Next.JS Doesn't require the import React statement at the top of its pages
    "react/react-in-jsx-scope": "off"
  }
}

Here is my package.json:

{
  "name": "my_app",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "precommit": "npm run build && lint-staged",
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "eslint './**/*.{js,jsx,ts,tsx}' --max-warnings 0",
    "test": "jest --passWithNoTests",
    "test:watch": "jest --watchAll"
  },
  "lint-staged": {
    "*.json": [
      "prettier --write"
    ],
    "./**/*.{js,jsx,ts,tsx,css,scss}": [
      "prettier --write",
      "npm run lint",
      "npm run test"
    ]
  },
  "dependencies": {
    "@testing-library/jest-dom": "^5.1.1",
    "@testing-library/react": "^9.4.0",
    "@types/jest": "^25.1.2",
    "isomorphic-unfetch": "^3.0.0",
    "jest": "^25.1.0",
    "next": "9.2.1",
    "react": "16.12.0",
    "react-dom": "16.12.0",
    "ts-jest": "^25.2.0"
  },
  "devDependencies": {
    "@types/node": "^13.7.0",
    "@types/react": "^16.9.19",
    "@types/react-dom": "^16.9.5",
    "@typescript-eslint/eslint-plugin": "^2.19.0",
    "@typescript-eslint/parser": "^2.19.0",
    "babel-eslint": "^10.0.3",
    "eslint": "^6.8.0",
    "eslint-config-airbnb": "^18.0.1",
    "eslint-config-prettier": "^6.10.0",
    "eslint-loader": "^3.0.3",
    "eslint-plugin-import": "^2.20.1",
    "eslint-plugin-jest": "^23.7.0",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-prettier": "^3.1.2",
    "eslint-plugin-react": "^7.18.3",
    "eslint-plugin-react-hooks": "^1.7.0",
    "lint-staged": "^10.0.7",
    "prettier": "^1.19.1",
    "typescript": "^3.7.5"
  }
}

Here is the error I get in the console:

frontend    | [ event ] build page: /one
frontend    | [ warn ]  ./pages/one.tsx
frontend    | /usr/src/app/packages/frontend/pages/one.tsx
frontend    |   22:23  warning  Missing return type on function  @typescript-eslint/explicit-function-return-type
frontend    |
frontend    | ✖ 1 problem (0 errors, 1 warning)
frontend    | [ info ]  ready on http://localhost:3000
frontend    | [ warn ]  ./pages/one.tsx
frontend    | /usr/src/app/packages/frontend/pages/one.tsx
frontend    |   22:23  warning  Missing return type on function  @typescript-eslint/explicit-function-return-type
frontend    |
frontend    | ✖ 1 problem (0 errors, 1 warning)
frontend    | [ info ]  ready on http://localhost:3000

I can manually give it a return type to clear the error, but NextPage should include the types automatically. Here is the snippet of me manually giving it the return type: TestServer.getInitialProps = async (): Promise<Props> => {

I've confirmed that next-env.d.ts file exists, and my VSCode can code jump to the NextPage type definition file located under node_modules/. However, eslint-typescript doesn't seem to acknowledge it. What am I doing wrong?

Thanks


问:
Print Not Matching With An Array I'm Appending To
I'm trying to make a function that takes an array of numbers and gives you every combination those numbers can be in, in two arrays.

My problem is that I can print the exact results that I want, but when I try to save the results into a variable, for some reason, I get the same sub-array spammed in my array.

Here is the code:

```<code>test = []
def partitioner(array1, array2):
    a = array1
    b = array2
    for _ in range(len(b)):
        a.append(b[0])
        del b[0]

        if(len(b) >= 1 and len(a) >= 1):
            print([a, b])       # This part right here, I'm printing the expected
            test.append([a, b]) # But this array is getting the actual
        partitioner(a, b)
        b.append(a[-1])
        del a[-1]

partitioner([], [x for x in range(3)])
print(test)
</code>```

Expected:

```<code>[
[[0], [1, 2]],
[[0, 1], [2]],
[[0, 2], [1]],
[[1], [2, 0]],
[[1, 2], [0]],
[[1, 0], [2]],
[[2], [0, 1]],
[[2, 0], [1]],
[[2, 1], [0]]]
</code>```

Actual:

```<code>[
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]]]
</code>```

答:
a and b are lists, so when they are overridden every iteration of the recursion with the last value it changes the values in test as well. Append a copy of a and b instead

```<code>test.append([a[:], b[:]])
</code>```

Body:
I'm trying to make a function that takes an array of numbers and gives you every combination those numbers can be in, in two arrays.

My problem is that I can print the exact results that I want, but when I try to save the results into a variable, for some reason, I get the same sub-array spammed in my array.

Here is the code:

test = []
def partitioner(array1, array2):
    a = array1
    b = array2
    for _ in range(len(b)):
        a.append(b[0])
        del b[0]

        if(len(b) >= 1 and len(a) >= 1):
            print([a, b])       # This part right here, I'm printing the expected
            test.append([a, b]) # But this array is getting the actual
        partitioner(a, b)
        b.append(a[-1])
        del a[-1]

partitioner([], [x for x in range(3)])
print(test)

Expected:

[
[[0], [1, 2]],
[[0, 1], [2]],
[[0, 2], [1]],
[[1], [2, 0]],
[[1, 2], [0]],
[[1, 0], [2]],
[[2], [0, 1]],
[[2, 0], [1]],
[[2, 1], [0]]]

Actual:

[
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]]]

Body:
a and b are lists, so when they are overridden every iteration of the recursion with the last value it changes the values in test as well. Append a copy of a and b instead

test.append([a[:], b[:]])


问:
is it possible to enable or disable geo tagging feature in Android camera programmatically
I'm trying read the location from images which is taken from the camera api which I included in my project.

But

```<code>exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE)
</code>```

gives null.

I know I need to enable save location(geo tagging) in settings.
But I don't like to do that, as I need it to be done programmatically.

Is it possible to enable or disable geo tagging?

答:
GPS information is not directly related to Android Camera API. The way geo tagging works is:

Android Camera App gets Geo Location permissions and before the capture gets the coordinates (lat, long) and either give it to camera 2 api to be added in exif of final jpeg (if using JPEG) or encode it itself into final jpeg.

Assuming you have an app that invokes camera api to capture image, what you could do is:

Have geo permissions in your app.

Invoke camera api for capturing image.

Once the image is returned, get coordinates from geo location
APIs.

Use it the way you wish to.

Body:
I'm trying read the location from images which is taken from the camera api which I included in my project.

But

exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE)

gives null.

I know I need to enable save location(geo tagging) in settings.
But I don't like to do that, as I need it to be done programmatically.

Is it possible to enable or disable geo tagging?


问:
What is a Descendant operator? Is it in javascript Or in any other language?
I came across a question stating:
Which on of the following is a Descendant operator:

A) ..

B) ...

C) &

D) *

WHICH IS IT? AND PLEASE EXPLAIN WHY OR REFER ANY ARTICLE OR LINK

答:
The answer is A.

The .. operator is the descendant operator; you can use it in place of the normal . member-access operator :

```<code>var names = pt..name;
</code>```

Body:
The answer is A.

The .. operator is the descendant operator; you can use it in place of the normal . member-access operator :

var names = pt..name;


问:
How to assign value to a variable that's 'Get-Only'?
I'm new to Swift and SwiftUI. Currently when a user pinch zooms, the image goes back to regular position when finished. I'd like to have it so that when the user stops zooming in the picture, it stays zoomed in.

```<code>struct ContentView: View {
   @GestureState var magnifyBy = CGFloat(1.0)
   @State var zoomIn = CGFloat(1.0)

    var magnification: some Gesture {
           MagnificationGesture()
               .updating($magnifyBy) { currentState, gestureState, transaction in
                gestureState = currentState
           }.onEnded{value in
               magnifyBy = value
        }
    }

    var body: some View {
           Circle()
               .frame(width: 100 * magnifyBy,
                      height: 100 * magnifyBy,
                      alignment: .center)
       }
}
</code>```

magnifyBy = value

Throws me an error:
Cannot assign to property: 'magnifyBy' is a get-only property

What can I do to fix this?

答:
GestureState is alive while gesture is active and must be used only inside this time-frame, updating correspondingly. After gesture finished the corresponding gesture state is reset to initial value. So to have changes persistent we need to store it separately.

Here is possible approach (tested & works with Xcode 11.2 / iOS 13.2)

```<code>struct ContentView: View {
    @GestureState var magnifyBy = CGFloat(1.0)
    @State var zoomIn = CGFloat(1.0)

    var magnification: some Gesture {
        MagnificationGesture()
            .updating($magnifyBy) { value, gestureState, transaction in
                gestureState = value // gestureState is magnifyBy
        }.onEnded{ value in
            self.zoomIn *= value // < preserve last changes
        }
    }

    var body: some View {
        Circle()
            .frame(width: 100 * magnifyBy * zoomIn, //after onEnded magnifyBy=1 again
                   height: 100 * magnifyBy * zoomIn,
                   alignment: .center)
            .gesture(magnification)
    }
}
</code>```

Please see for details on GestureState in official Apple article, Adding Interactivity with Gestures. That rare case when documentation is full and good.

Body:
I'm new to Swift and SwiftUI. Currently when a user pinch zooms, the image goes back to regular position when finished. I'd like to have it so that when the user stops zooming in the picture, it stays zoomed in.

struct ContentView: View {
   @GestureState var magnifyBy = CGFloat(1.0)
   @State var zoomIn = CGFloat(1.0)

    var magnification: some Gesture {
           MagnificationGesture()
               .updating($magnifyBy) { currentState, gestureState, transaction in
                gestureState = currentState
           }.onEnded{value in
               magnifyBy = value
        }
    }

    var body: some View {
           Circle()
               .frame(width: 100 * magnifyBy,
                      height: 100 * magnifyBy,
                      alignment: .center)
       }
}

magnifyBy = value

Throws me an error:
Cannot assign to property: 'magnifyBy' is a get-only property

What can I do to fix this?

Body:
GestureState is alive while gesture is active and must be used only inside this time-frame, updating correspondingly. After gesture finished the corresponding gesture state is reset to initial value. So to have changes persistent we need to store it separately.

Here is possible approach (tested & works with Xcode 11.2 / iOS 13.2)

struct ContentView: View {
    @GestureState var magnifyBy = CGFloat(1.0)
    @State var zoomIn = CGFloat(1.0)

    var magnification: some Gesture {
        MagnificationGesture()
            .updating($magnifyBy) { value, gestureState, transaction in
                gestureState = value // gestureState is magnifyBy
        }.onEnded{ value in
            self.zoomIn *= value // < preserve last changes
        }
    }

    var body: some View {
        Circle()
            .frame(width: 100 * magnifyBy * zoomIn, //after onEnded magnifyBy=1 again
                   height: 100 * magnifyBy * zoomIn,
                   alignment: .center)
            .gesture(magnification)
    }
}

Please see for details on GestureState in official Apple article, Adding Interactivity with Gestures. That rare case when documentation is full and good.


问:
Adding a product to a Stripe charge?
I know we can add the product id to a stripe charge using metadata.  Is it possible to add it directly to one of the charge attributes?

For example we can put the customer id in the customer attribute on the charge.

Is there a product attribute that we can assign the product id to?  I don't see one mentioned in the API docs.

答:
No,. a product is not a part of the charge entity in Stripe, there for there's no such field.

You can only add it to the metadata

Title: Adding a product to a Stripe charge?


问:
Error: Unable to find @SpringBootConfiguration when doing @WebMvcTest for Spring Controller
I am testing my controller given below

```<code>@Controller
public class MasterController {

@GetMapping("/")
public String goLoginPage(){
    return "index";
}
}
</code>```

I am following this Spring documentation to test my controller.
Now, I want to test my controller by just instantiating the web layer and not the whole Spring context as given in the documentation. Below is my code for the same.

```<code>@RunWith(SpringRunner.class)
@WebMvcTest
public class MasterControllerTestWithWebLayer {

@Autowired
MockMvc mockMvc;

@Autowired
MasterController masterController;

@Before
public void setUp() throws Exception {
}

@After
public void tearDown() throws Exception {
}

@Test
public void testLoginHome() throws Exception{
    mockMvc.perform(get("/"))
    .andExpect(status().isOk())
    .andExpect(view().name("index"));
}

}
</code>```

When I run this test I get the error Unable to find @SpringBootConfiguration,...etc. But I am confused why it is asking for Spring configuration when we do not want it to instantiate it but want to use only the web layer. Kindly point me to the right direction what is happening here. And also how to fix this. Thanks

答:
check if src/test/java has same package name as the main class package.
src/test/java/com/example/abc is same as src/test/java/com/example/abc</p>

Body:
I am testing my controller given below

@Controller
public class MasterController {

@GetMapping("/")
public String goLoginPage(){
    return "index";
}
}

I am following this Spring documentation to test my controller.
Now, I want to test my controller by just instantiating the web layer and not the whole Spring context as given in the documentation. Below is my code for the same.

@RunWith(SpringRunner.class)
@WebMvcTest
public class MasterControllerTestWithWebLayer {

@Autowired
MockMvc mockMvc;

@Autowired
MasterController masterController;

@Before
public void setUp() throws Exception {
}

@After
public void tearDown() throws Exception {
}

@Test
public void testLoginHome() throws Exception{
    mockMvc.perform(get("/"))
    .andExpect(status().isOk())
    .andExpect(view().name("index"));
}

}

When I run this test I get the error Unable to find @SpringBootConfiguration,...etc. But I am confused why it is asking for Spring configuration when we do not want it to instantiate it but want to use only the web layer. Kindly point me to the right direction what is happening here. And also how to fix this. Thanks


问:
break a user inputted sentence in c using strtok and put the sentences in a 2d array
Hello I am trying to break up a series of strings by spaces in a sentence and display it line by line via a 2d array but am only getting the first word inputted in a sentence. I am using strtok_r but seem to find what I'm doing wrong.
    int split(char *s)</p>

```<code>{
int count=0;

printf("the code is here");
char *rest;

char* token=strtok_r(s," ", &rest);

while(token != NULL){
    count++;
    printf("token \s\n ", token);
    token=strtok_r(NULL," ",&rest);

    if(count==0){
        printf("problem \n");
        exit(-1);
    }

     char ** twod=(char**)calloc((count+1),sizeof(char*));
     token=strtok_r(s," ",&rest);
     int x=0;
     while(token !=NULL){
        twod[x]=(char*)calloc(strlen(token+1),sizeof(char));
        strcpy(twod[x],token);
        x++;
        token=strtok_r(NULL," ", &rest);
        for(x=0;x<count;x++){
            printf("%s  ", twod[x]);
        }

    }
}
</code>```

答:
the following proposed code:

is missing the main() function

corrects the signature for function: split()

documents why each header file is included

performs the desired functionality

cleanly compiles, except maybe on windows

does not use the function: strtok_r()

If compiled on Windows, will need a statement at the top of the code similar to: #define _CRT_SECURE_NO_WARNINGS 1

places all the extracted strings into the 2 dimensional array, rather than skipping the first 2

expands the amount of memory for twod[], as needed, so as to avoid undefined behavior

checks for errors and handles them properly, including freeing the allocated memory before exiting.  Checks for errors from realloc() and strdup()

frees the allocated memory before exiting, so as to avoid any memory leaks

Note: it is ok to pass NULL to free()

and now, the proposed code:

```<code>#include <string.h>   // strdup(), strtok()
#include <stdlib.h>   // realloc(), exit(), EXIT_FAILURE, free()
#include <stdio.h>    // printf(), perror()

void split( char *s )
{
    size_t  count=0;
    char ** twod = NULL;

    char*   token = strtok( s, " " );

    while( token )
    {
        count++;
        printf("token %s\n ", token);

        char ** temp = realloc( twod, count * sizeof( char * ) );
        if( ! temp )
        {
            perror( "malloc failed" );
            for( size_t i = 0; i < count; i++ )
            {
                free( twod[i] );
            }
            free( twod );
            exit( EXIT_FAILURE );
        }

        twod = temp;

        twod[ count -1 ] = strdup( token );
        if( ! twod[ count -1 ] )
        {
            perror( "strdup failed" );
            for( size_t i = 0; i < count; i++ )
            {
                free( twod[i] );
            }
            free( twod );
            exit( EXIT_FAILURE );
        }

        token = strtok( NULL," " );
    }

    for( size_t x=0; x < count; x++ )
    {
        printf("%s  ", twod[x]);
    }

    for( size_t i = 0; i < count; i++ )
    {
        free( twod[i] );
    }
    free( twod );
}
</code>```

Body:
Hello I am trying to break up a series of strings by spaces in a sentence and display it line by line via a 2d array but am only getting the first word inputted in a sentence. I am using strtok_r but seem to find what I'm doing wrong.
    int split(char *s)

{
int count=0;

printf("the code is here");
char *rest;

char* token=strtok_r(s," ", &rest);

while(token != NULL){
    count++;
    printf("token \s\n ", token);
    token=strtok_r(NULL," ",&rest);

    if(count==0){
        printf("problem \n");
        exit(-1);
    }

     char ** twod=(char**)calloc((count+1),sizeof(char*));
     token=strtok_r(s," ",&rest);
     int x=0;
     while(token !=NULL){
        twod[x]=(char*)calloc(strlen(token+1),sizeof(char));
        strcpy(twod[x],token);
        x++;
        token=strtok_r(NULL," ", &rest);
        for(x=0;x<count;x++){
            printf("%s  ", twod[x]);
        }

    }
}

Body:
the following proposed code:

is missing the main() function

corrects the signature for function: split()

documents why each header file is included

performs the desired functionality

cleanly compiles, except maybe on windows

does not use the function: strtok_r()

If compiled on Windows, will need a statement at the top of the code similar to: #define _CRT_SECURE_NO_WARNINGS 1

places all the extracted strings into the 2 dimensional array, rather than skipping the first 2

expands the amount of memory for twod[], as needed, so as to avoid undefined behavior

checks for errors and handles them properly, including freeing the allocated memory before exiting.  Checks for errors from realloc() and strdup()

frees the allocated memory before exiting, so as to avoid any memory leaks

Note: it is ok to pass NULL to free()

and now, the proposed code:

#include <string.h>   // strdup(), strtok()
#include <stdlib.h>   // realloc(), exit(), EXIT_FAILURE, free()
#include <stdio.h>    // printf(), perror()

void split( char *s )
{
    size_t  count=0;
    char ** twod = NULL;

    char*   token = strtok( s, " " );

    while( token )
    {
        count++;
        printf("token %s\n ", token);

        char ** temp = realloc( twod, count * sizeof( char * ) );
        if( ! temp )
        {
            perror( "malloc failed" );
            for( size_t i = 0; i < count; i++ )
            {
                free( twod[i] );
            }
            free( twod );
            exit( EXIT_FAILURE );
        }

        twod = temp;

        twod[ count -1 ] = strdup( token );
        if( ! twod[ count -1 ] )
        {
            perror( "strdup failed" );
            for( size_t i = 0; i < count; i++ )
            {
                free( twod[i] );
            }
            free( twod );
            exit( EXIT_FAILURE );
        }

        token = strtok( NULL," " );
    }

    for( size_t x=0; x < count; x++ )
    {
        printf("%s  ", twod[x]);
    }

    for( size_t i = 0; i < count; i++ )
    {
        free( twod[i] );
    }
    free( twod );
}


问:
Brighten Image(JLabel) on a JFrame on hover
I have a JLabel image on a JFrame that I want too brighten upon hovering, have tried a few things however nothing seems to be working, here's my current code:

```<code>public class DivinationLogo extends JLabel {
private BufferedImage logo;
public DivinationLogo() {

    super();
    try {
        logo = ImageIO.read(getClass().getResourceAsStream("/assets/images/logo.png"));
    } catch (IOException e) {
        e.printStackTrace();
    }
   // setIcon(new ImageIcon(logo));
    setIconTextGap(0);
    setBorder(null);
    setText(null);

    addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            Functions.openWebPage(Config.website);
        }

        @Override
        public void mouseEntered(MouseEvent e) {
           Functions.brightnessControl(logo, .3F);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            Functions.brightnessControl(logo, 1.0F);
        }
    });
    setBounds(-5, 1, 247, 106);
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(logo, -5, 1, null);
 }
}
</code>```

Functions.brightnessControl:

```<code>public static Image brightnessControl(Image image, float brightness) {
    BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    Graphics bg = bi.getGraphics();

    if (bi.getColorModel().hasAlpha()) {
        System.out.println("Image has got an alpha channel");
    }

    bg.drawImage(image, 0, 0, null);
    bg.dispose();
    RescaleOp rescaleOp = new RescaleOp(brightness, 0, null);
    rescaleOp.filter(bi, bi);
    image = bi;
    return bi;
}
</code>```

Currently, it does nothing which confuses me. If anyone knows how this is achieved, please feel free too let me know :)

答:
Arguments in java are passed by value so your the function you have to brighten the image doesn't have an effect on the image you passed to it.

You're missing the repaint() call after changing the image.

You definitely don't want to prepare the hover image every time you hover over the image. Pre-calculate the hover in the constructor and assign it to a separate image.

Create a member variable for if hover is true and use that in the paint method to figure out which image to paint.

Body:
I have a JLabel image on a JFrame that I want too brighten upon hovering, have tried a few things however nothing seems to be working, here's my current code:

public class DivinationLogo extends JLabel {
private BufferedImage logo;
public DivinationLogo() {

    super();
    try {
        logo = ImageIO.read(getClass().getResourceAsStream("/assets/images/logo.png"));
    } catch (IOException e) {
        e.printStackTrace();
    }
   // setIcon(new ImageIcon(logo));
    setIconTextGap(0);
    setBorder(null);
    setText(null);

    addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            Functions.openWebPage(Config.website);
        }

        @Override
        public void mouseEntered(MouseEvent e) {
           Functions.brightnessControl(logo, .3F);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            Functions.brightnessControl(logo, 1.0F);
        }
    });
    setBounds(-5, 1, 247, 106);
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(logo, -5, 1, null);
 }
}

Functions.brightnessControl:

public static Image brightnessControl(Image image, float brightness) {
    BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    Graphics bg = bi.getGraphics();

    if (bi.getColorModel().hasAlpha()) {
        System.out.println("Image has got an alpha channel");
    }

    bg.drawImage(image, 0, 0, null);
    bg.dispose();
    RescaleOp rescaleOp = new RescaleOp(brightness, 0, null);
    rescaleOp.filter(bi, bi);
    image = bi;
    return bi;
}

Currently, it does nothing which confuses me. If anyone knows how this is achieved, please feel free too let me know :)


答:
Well, In PHP, you can not access private property outside the class. You can access protected property in the subclasses of a class. But if they are needed to access by clients/you (meaning who is using the object/code) developers of that kind of classes use getters and setters method to access them. So you can use them as the following if you need them.

```<code>$registrant->getResponse()->getResponse()->getReasonPhrase();
</code>```

Actually this method comes from this Guzzle's class GuzzleHttp\Psr7\Response. If you want you can find it here

Title: Accessing private property in PHP Guzzle Response object

Body:
I tried to access to statuscode and reasonphrase but the bellow code returns erros like

die(var_dump($registrant->response->reasonPhrase));

error:

"message": "Undefined property:
  MacsiDigital\Zoom\Support\Response::$reasonPhrase",

code: ( RESULT OF var_dump($registrant->getResponse()); )

 object(MacsiDigital\Zoom\Support\Response)#874 (1) {
  ["response":protected]=>
  object(GuzzleHttp\Psr7\Response)#885 (6) {
    ["reasonPhrase":"GuzzleHttp\Psr7\Response":private]=>
    string(7) "Created"
    ["statusCode":"GuzzleHttp\Psr7\Response":private]=>
    int(201)
    ["headers":"GuzzleHttp\Psr7\Response":private]=>
    array(14) {
      ["Date"]=>
      array(1) {
        [0]=>
        string(29) "Sun, 16 Feb 2020 05:56:11 GMT"
      }
      ["Content-Type"]=>
      array(1) {
        [0]=>
        string(30) "application/json;charset=UTF-8"
      }
      ["Content-Length"]=>
      array(1) {
        [0]=>
        string(3) "249"
      }
      ["Connection"]=>
      array(1) {
        [0]=>
        string(10) "keep-alive"
      }
      ["Server"]=>
      array(1) {
        [0]=>
        string(4) "ZOOM"
      }
      ["x-zm-trackingid"]=>
      array(1) {
        [0]=>
        string(36) ""
      }
      ["X-Content-Type-Options"]=>
      array(1) {
        [0]=>
        string(7) "nosniff"
      }
      ["Cache-Control"]=>
      array(1) {
        [0]=>
        string(49) "no-cache, no-store, must-revalidate, no-transform"
      }
      ["Pragma"]=>
      array(1) {
        [0]=>
        string(8) "no-cache"
      }
      ["Expires"]=>
      array(1) {
        [0]=>
        string(29) "Thu, 01 Jan 1970 00:00:00 GMT"
      }
      ["Set-Cookie"]=>
      array(1) {
        [0]=>
        string(63) "cred=; Path=/; Secure; HttpOnly"
      }
      ["Strict-Transport-Security"]=>
      array(1) {
        [0]=>
        string(16) "max-age=31536000"
      }
      ["X-XSS-Protection"]=>
      array(1) {
        [0]=>
        string(13) "1; mode=block"
      }
      ["Referrer-Policy"]=>
      array(1) {
        [0]=>
        string(31) "strict-origin-when-cross-origin"
      }
    }
    ["headerNames":"GuzzleHttp\Psr7\Response":private]=>
    array(14) {
      ["date"]=>
      string(4) "Date"
      ["content-type"]=>
      string(12) "Content-Type"
      ["content-length"]=>
      string(14) "Content-Length"
      ["connection"]=>
      string(10) "Connection"
      ["server"]=>
      string(6) "Server"
      ["x-zm-trackingid"]=>
      string(15) "x-zm-trackingid"
      ["x-content-type-options"]=>
      string(22) "X-Content-Type-Options"
      ["cache-control"]=>
      string(13) "Cache-Control"
      ["pragma"]=>
      string(6) "Pragma"
      ["expires"]=>
      string(7) "Expires"
      ["set-cookie"]=>
      string(10) "Set-Cookie"
      ["strict-transport-security"]=>
      string(25) "Strict-Transport-Security"
      ["x-xss-protection"]=>
      string(16) "X-XSS-Protection"
      ["referrer-policy"]=>
      string(15) "Referrer-Policy"
    }
    ["protocol":"GuzzleHttp\Psr7\Response":private]=>
    string(3) "1.1"
    ["stream":"GuzzleHttp\Psr7\Response":private]=>
    object(GuzzleHttp\Psr7\Stream)#883 (7) {
      ["stream":"GuzzleHttp\Psr7\Stream":private]=>
      resource(650) of type (stream)
      ["size":"GuzzleHttp\Psr7\Stream":private]=>
      NULL
      ["seekable":"GuzzleHttp\Psr7\Stream":private]=>
      bool(true)
      ["readable":"GuzzleHttp\Psr7\Stream":private]=>
      bool(true)
      ["writable":"GuzzleHttp\Psr7\Stream":private]=>
      bool(true)
      ["uri":"GuzzleHttp\Psr7\Stream":private]=>
      string(10) "php://temp"
      ["customMetadata":"GuzzleHttp\Psr7\Stream":private]=>
      array(0) {
      }
    }
  }
}

PS. : when I trie to access like this it returns Null

$registrant->reasonPhrase

Body:
Well, In PHP, you can not access private property outside the class. You can access protected property in the subclasses of a class. But if they are needed to access by clients/you (meaning who is using the object/code) developers of that kind of classes use getters and setters method to access them. So you can use them as the following if you need them.

$registrant->getResponse()->getResponse()->getReasonPhrase();

Actually this method comes from this Guzzle's class GuzzleHttp\Psr7\Response. If you want you can find it here


问:
How do I access an XML file that is included in the project?
I have added an XML file (File.xml) into a project (I can see it in the Solution Explorer), it resides at the root directory level of the project i.e. the same level as the VB program (.vb), the bin directory and the References directory etc..

I try accessing it using XmlDocument.Load("File.xml") ... but it doesn't find it.  I get

A first chance exception of type 'System.IO.FileNotFoundException' occurred in System.Xml.dll

Any idea where the file is or how I 'address' it?

Thanks for any help

Oliver

答: Is the file copied to the output directory? Click on the file, look at the properties in the VS editor, and set the "Build Action" to Content and "Copy to Output Directory" to either "Copy always" or "Copy if newer" (depending on what you need).</p>


问:
Connecting server and client socket over wifi
Here Is The server code

```<code>   void bind(String ip,int port)
   {
    socket=ServerSocketChannel.open();
    socket.configureBlocking(false);

    socket.register(acceptChannel=Selector.open(),SelectionKey.OP_ACCEPT);//Since Non Blocking Create Selector
    socket.bind(new InetSocketAddress(ip,port));//Binding To Specified IP,Port So clients can connect

    accept=threadService.scheduleAtFixedRate(this,100,interval,TimeUnit.MILLISECONDS);
   }

    void run()//Just Loops And Checks For New Clients
    {
     try
     {
      if(acceptChannel.selectNow()==0){return;}

      Set<SelectionKey> channels=acceptChannel.selectedKeys();
      Iterator<SelectionKey> iterator=channels.iterator();

      while(iterator.hasNext())
      {
       SelectionKey key=iterator.next();
       ServerSocketChannel server=(ServerSocketChannel)key.channel();

       SocketChannel client=server.accept();
       client.configureBlocking(false);

       //Do Stuff With Client

       iterator.remove();
      }
      channels.clear();
     }
     catch(Exception ex){errors.newClientError(ex,mainSocket,client);}
   }
</code>```

And Here Is The Client Code

```<code>    SocketChannel clientSocket;
    void connect(String IP,int port)throws IOException
     {
      clientSocket=SocketChannel.open();
      clientSocket.configureBlocking(false);

      clientSocket.register(connectChannel,SelectionKey.OP_CONNECT);//Non Blocking So Loop to check for status
      clientSocket.connect(new InetSocketAddress(IP,port));//Do Actual Connection Here

      waiting=threadService.scheduleAtFixedRate(this,100,10,TimeUnit.MILLISECONDS);
     }

     public void run()//Loops and checks for successful connection
     {
      try
      {
       if(connectChannel.selectNow()==0){return;}

       Set<SelectionKey> channels=connectChannel.selectedKeys();
       Iterator<SelectionKey> iterator=channels.iterator();

       while(iterator.hasNext())
       {
        SelectionKey client=iterator.next();
        SocketChannel channel=(SocketChannel)client.channel();

        if(channel.finishConnect())
        {
         client.cancel();

         iterator.remove();
         channels.clear();

         //Yeah we are connected job done

         return;
        }

        iterator.remove();
       }
       channels.clear();
      }
      catch(Exception ex)
      {

      }
     }
</code>```

As You Can See Both my client and server must be in non blocking mode for project specific purposes.

Now This Code Works When

1)Both client and server are in same computer and IP parameter of both client & server is "localhost"

2)Both client and server are in same computer and IP parameter of both client & server is my router's network address[Im in windows so I go to cmd type ipconfig and pass the IPV4 address into both these methods]

The problem is that My Client cannot connect to my server when he is on an different system connected over wifi/lan.

I Bind My Server To My Router's IPV4 Address And Give That same address to My Client's connect() method on an different machine but he gets "ConnectionTimedOutException"

The port parameter is same for both client & server which is 8001

Both the systems firewalls are disabled for this test.

Any idea on what's going wrong?

答:
I had to use Port forwarding to solve my problem

I undertook the following steps

1)Client uses my global[not local ipv4] address which I got from the net[whatsmyip.com] in the connect() method

2)In my server I call bind() using my local ipv4 address[from ipconfig]

3)The common port I used was 8001 which I had to configure for port forwarding in my router settings so it forwards all packets from my global ip:port XXX.XXX.XXX.XXX:8001 to my local ipv4 address:port 192.168.xxx.xxx:8001

This approach works but is not efficient as my IP changes when I disconnect and reconnect. If anyone knows of a better solution to connect to an server without configuring an static IP please do share. Thank u

Body:
Here Is The server code

   void bind(String ip,int port)
   {
    socket=ServerSocketChannel.open();
    socket.configureBlocking(false);

    socket.register(acceptChannel=Selector.open(),SelectionKey.OP_ACCEPT);//Since Non Blocking Create Selector
    socket.bind(new InetSocketAddress(ip,port));//Binding To Specified IP,Port So clients can connect

    accept=threadService.scheduleAtFixedRate(this,100,interval,TimeUnit.MILLISECONDS);
   }

    void run()//Just Loops And Checks For New Clients
    {
     try
     {
      if(acceptChannel.selectNow()==0){return;}

      Set<SelectionKey> channels=acceptChannel.selectedKeys();
      Iterator<SelectionKey> iterator=channels.iterator();

      while(iterator.hasNext())
      {
       SelectionKey key=iterator.next();
       ServerSocketChannel server=(ServerSocketChannel)key.channel();

       SocketChannel client=server.accept();
       client.configureBlocking(false);

       //Do Stuff With Client

       iterator.remove();
      }
      channels.clear();
     }
     catch(Exception ex){errors.newClientError(ex,mainSocket,client);}
   }

And Here Is The Client Code

    SocketChannel clientSocket;
    void connect(String IP,int port)throws IOException
     {
      clientSocket=SocketChannel.open();
      clientSocket.configureBlocking(false);

      clientSocket.register(connectChannel,SelectionKey.OP_CONNECT);//Non Blocking So Loop to check for status
      clientSocket.connect(new InetSocketAddress(IP,port));//Do Actual Connection Here

      waiting=threadService.scheduleAtFixedRate(this,100,10,TimeUnit.MILLISECONDS);
     }

     public void run()//Loops and checks for successful connection
     {
      try
      {
       if(connectChannel.selectNow()==0){return;}

       Set<SelectionKey> channels=connectChannel.selectedKeys();
       Iterator<SelectionKey> iterator=channels.iterator();

       while(iterator.hasNext())
       {
        SelectionKey client=iterator.next();
        SocketChannel channel=(SocketChannel)client.channel();

        if(channel.finishConnect())
        {
         client.cancel();

         iterator.remove();
         channels.clear();

         //Yeah we are connected job done

         return;
        }

        iterator.remove();
       }
       channels.clear();
      }
      catch(Exception ex)
      {

      }
     }

As You Can See Both my client and server must be in non blocking mode for project specific purposes.

Now This Code Works When

1)Both client and server are in same computer and IP parameter of both client & server is "localhost"

2)Both client and server are in same computer and IP parameter of both client & server is my router's network address[Im in windows so I go to cmd type ipconfig and pass the IPV4 address into both these methods]

The problem is that My Client cannot connect to my server when he is on an different system connected over wifi/lan.

I Bind My Server To My Router's IPV4 Address And Give That same address to My Client's connect() method on an different machine but he gets "ConnectionTimedOutException"

The port parameter is same for both client & server which is 8001

Both the systems firewalls are disabled for this test.

Any idea on what's going wrong?


答:
You can directly divide  on level = 1 after dropping the unnecessary multiindex column from B:

```<code>final1 = A.div(B.droplevel(0,1).astype(float),level=1)
</code>```

```<code>                  43        210
                  p1        p1
2019-12-01  0.001447  0.001447
</code>```

To get all elements in B even if it isnt present in A, you can stack the df A , then divide and unstack back with swaplevel and sort index for a multiindex view:

```<code>final2 = (A.stack(0).div(B.droplevel(0,1).astype(float),level=0).unstack()
                            .swaplevel(axis=1).sort_index(axis=1))
</code>```

```<code>                  43            210
                  p1  p2        p1  p2
2019-12-01  0.001447 NaN  0.001447 NaN
</code>```

Title: Dividing 2 Multi-Index Data frames while retaining structure

Body:
I have 2 MultiIndex data frames

The first looks like this:

v                         40                ...           200
                 p1       p2         p3     ...      p2        p3       p4
dates                                       ...
2019-12-01  0.031827  0.030943    0.027203  ...  0.014557    0.012797  0.010334
2019-12-02  0.027271  0.024006    0.022646  ...  0.011294    0.010654  0.010174

.to_dict() -->

A =
{
  (43, 'p1'):
     {
       '2019-12-01': 0.0318271824,
       '2019-12-02': 0.0272707268,
     },
  (43, 'p2'):
     {
       ( ... )
      },
  (43, 'p3'):
      {
        ( ... )
      },
  (210, 'p1'):
      {
         ( ... )
       }
}

The 2nd of looks like this:

           section1                 section2  ... section3  section3
                p1   p2   p3   p4    p1     ...   p4      p1   p2   p3   p4
dates                                       ...
2019-12-01  22.00  0.03  0.03  0.03  0.111  ...  0.03     0.03  0.03  0.03  0.03
2019-12-02   0.03  0.03  1.00  0.03  0.030  ...  0.03     0.03  0.03  0.03  0.03

.to_dict() -->

B =
{
  ('section1', 'p1'):
     {
       '2019-12-01': '22',
       '2019-12-02': '0.03',
     },
  ('section1', 'p2'):
     {
       ( ... )
     },
}

I would like to divide these 2 data frames together (A/B) and return the same structure as A. So like this:

v                         40                                     ...           200
                   p1               p2               p3                 ...      p2        p3       p4
dates                                                            ...
2019-12-01  0.031827 / 22.00   0.030943 / 0.03   0.027203 / 0.03  ...  0.014557    0.012797  0.010334
2019-12-02  0.027271  0.024006    0.022646       ...  0.011294    0.010654  0.010174

I am trying to handle the data as quickly as possible ...

** EDIT

to make it clearer I would like to create a dataframe that does divides A by B and keep the strcture of A... i.E:

 A = {
        (43, 'p1'):
             {
               '2019-12-01': 0.0318271824
             },
        (210, 'p1'):
              {
                 '2019-12-01': 0.0318271824
               }
   }

B = {
        ('section1', 'p1'):
             {
               '2019-12-01': '22',
             },
        ('section1', 'p2'):
            {
                 '2019-12-01': '22'
            },
    }

C = {
        (43, 'p1'):
             {
               '2019-12-01': 22 / 0.0318271824
             },
        (210, 'p1'):
              {
                 '2019-12-01': 22 / 0.0318271824
               }
   }

Body:
You can directly divide  on level = 1 after dropping the unnecessary multiindex column from B:

final1 = A.div(B.droplevel(0,1).astype(float),level=1)

                  43        210
                  p1        p1
2019-12-01  0.001447  0.001447

To get all elements in B even if it isnt present in A, you can stack the df A , then divide and unstack back with swaplevel and sort index for a multiindex view:

final2 = (A.stack(0).div(B.droplevel(0,1).astype(float),level=0).unstack()
                            .swaplevel(axis=1).sort_index(axis=1))

                  43            210
                  p1  p2        p1  p2
2019-12-01  0.001447 NaN  0.001447 NaN


问:
How to get group id in subtask instance while work with celery Group?
When work with Celery 4.3.0 Chains,
Code like this:

```<code>class BaseTask(Task):
    def on_success(self, retval, task_id, args, kwargs):
        pass

@app.task(bind=True, base=BaseTask)
def add(self, x, y):
    return x+y

@app.task(bind=True, base=baseTask)
def add_1(self,x, y):
    return x+y

task = group(add.s(1,3), add_1.s(2,4))()
group_id = task.id

</code>```

I can get group_id by taks.children[0]._cache.get("group"),

How can I get group_id in BaseTask on_success functions?

答:
You can find the id of the task’s group inside the app.task.Request object, made available through the Task object, like so:

class BaseTask(Task):
    def on_success(self, retval, task_id, args, kwargs):
        group_id = self.request.group
        # rest of your code
```

Body:
When work with Celery 4.3.0 Chains,
Code like this:

class BaseTask(Task):
    def on_success(self, retval, task_id, args, kwargs):
        pass

@app.task(bind=True, base=BaseTask)
def add(self, x, y):
    return x+y

@app.task(bind=True, base=baseTask)
def add_1(self,x, y):
    return x+y

task = group(add.s(1,3), add_1.s(2,4))()
group_id = task.id

I can get group_id by taks.children[0]._cache.get("group"),

How can I get group_id in BaseTask on_success functions?


问:
Parent Selector of Several Elements Back
I can not figure out how to select an element (several elements back) from a specific element that has a certain title attribute.

For example, using the following example code, I am trying to target the first <renderer> element...

```<code><renderer class="scope">
   <div id="content" class="scope">
      <renderer class="scope">
         <div class="scope">
            <div id="details" class="scope">
               <a title="Foo Bar" href="#">LINK TEXT</a>
            </div>
         </div>
      </renderer>
   </div>
</renderer>
</code>```

I have tried many variation including this...

```<code>renderer:has a[title*="Foo Bar"] {
    opacity: 0.2 !important;
}
</code>```

Other things that I have tried don't even come close to working either (even JavaScript).... But possibly because every answer I found on here or other sites are not related to this issue enough to solve the problem.

How can I target and style the first <renderer> element (or at least 2 levels back) if the link title has specific text in it?

答:
There is no way to select parent element in CSS. You can use javascript to achieve desired results.

You can do something like this

```<code>let anchor = document.querySelector('a[title="Foo Bar"]');
anchor.closest('renderer').style.opacity = 0.2;
</code>```

If you want to select all elements in the document you can use querySelectorAll like:

```<code>let anchors = document.querySelectorAll('a[title="Foo Bar"]');
anchors.forEach(function (anchor) {
    anchor.closest('renderer').style.opacity = 0.2;
});
</code>```

Note: closest() will not work in IE, so you might have to add its polyfill or use parentNode instead.

Body:
I can not figure out how to select an element (several elements back) from a specific element that has a certain title attribute.

For example, using the following example code, I am trying to target the first <renderer> element...

<renderer class="scope">

      <renderer class="scope">

               LINK TEXT

      </renderer>

</renderer>

I have tried many variation including this...

renderer:has a[title*="Foo Bar"] {
    opacity: 0.2 !important;
}

Other things that I have tried don't even come close to working either (even JavaScript).... But possibly because every answer I found on here or other sites are not related to this issue enough to solve the problem.

How can I target and style the first <renderer> element (or at least 2 levels back) if the link title has specific text in it?

Body:
There is no way to select parent element in CSS. You can use javascript to achieve desired results.

You can do something like this

let anchor = document.querySelector('a[title="Foo Bar"]');
anchor.closest('renderer').style.opacity = 0.2;

If you want to select all elements in the document you can use querySelectorAll like:

let anchors = document.querySelectorAll('a[title="Foo Bar"]');
anchors.forEach(function (anchor) {
    anchor.closest('renderer').style.opacity = 0.2;
});

Note: closest() will not work in IE, so you might have to add its polyfill or use parentNode instead.


问:
When upload file: Curl return "Empty reply from server" only on Linux but Windows
when I upload a file to Mediafire Hosting by use CURL, i get "Empty reply from server" on Ubuntu, CentOs
but with same code ,I can upload that file on Windows.
What Linux difference from Windows ? How can i solve this matter ?</p>

答:
Try changing the user agent to see if that makes a difference.  For example:</p>

```<code>curl --user-agent "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.68 Safari/534.24"
</code>```

Body:
Try changing the user agent to see if that makes a difference.  For example:

curl --user-agent "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.68 Safari/534.24"


问:
Can you attach Amazon EBS to multiple instances?
We currently  use multiple webservers accessing one mysql server and fileserver.  Looking at moving to the cloud, can I use this same setup and attach the EBS to multiple machine instances or what's another solution? </p>

答: EBS just announced this is possible: https://aws.amazon.com/about-aws/whats-new/2020/02/ebs-multi-attach-available-provisioned-iops-ssd-volumes/</p>

ContentLicense: CC BY-SA 2.5


问:
create hyperlink that open in new tab/window using external javascript
How can I create a link that opens in a new window/tab to my HTML menu item (Try, Trying, TryTry) using external javascript? (and not edit anything from the HTML file)

Html file:

```<code><div id="highlights" class="container">
    <div id="menu">
        <ul>
            <li id="Try">Try!</li>
            <li id="Trying">Trying!</li>
            <li id="TryTry">TryTry!</li>
        </ul>
    </div>
</div>
</code>```

答:
Just put the path you want each link to go to as the href.

Here is a link to it in JSFiddle as StackOverflow snippets do not allow popups / new tabs to be opened.

Try!!

Trying!!

TryTry!!

```

Body:
How can I create a link that opens in a new window/tab to my HTML menu item (Try, Trying, TryTry) using external javascript? (and not edit anything from the HTML file)

Html file:

Try!

Trying!

TryTry!

Body:
Just put the path you want each link to go to as the href.

Here is a link to it in JSFiddle as StackOverflow snippets do not allow popups / new tabs to be opened.

<div id="highlights" class="container">
  <div id="menu">
    <ul>
      <li id="Try"><a href="link/to/try" target="_blank">Try!</a>!</li>
      <li id="Trying"><a href="link/to/trying" target="_blank">Trying!</a>!</li>
      <li id="TryTry"><a href="link/to/trytry" target="_blank">TryTry!</a>!</li>
    </ul>
  </div>
</div>


问:
Groupby and selecting max row within groupby result
Is it possible to groupby and sort results within each groupby result in Python/Pandas? </p>

<p>Trying to find the top Genere in each year in below given data.Tried a lot using groupby and sort but no luck. </p>

```<code>Input::

release_year    Genere      Count

1997            Action      46
1997            Adventure   7
1997            Animation   2
1997            Children's  12
1997            Comedy      73
1997            Crime       22
1997            Documentary 6
1997            Drama       81
1997            Horror      6
1997            Mystery     5
1997            Romance     15
1997            Sci-Fi      1
1997            Thriller    9
1997            War         1

1998            Action      12
1998            Adventure   2
1998            Comedy      24
1998            Crime       6
1998            Documentary 2
1998            Drama       21
1998            Film-Noir   2
1998            Horror      3
1998            Romance     4
1998            Thriller    1

Expected Output:

release_year    Genere      Count
1997            Drama       81
1998            Comedy      24
</code>```

答:
Here is my solution:

df_res = df.groupby(['release_year','Genere'])['Count'].sum().reset_index()
indexs = []
for year in df_res['release_year'].unique():
    df_temp = df_res[df_res.release_year==year]
    indexs += list(df_temp[df_temp['Count']==df_temp['Count'].max()].index)
df_res = df_res.loc[indexs]
```

I don't use 'sort()'. I use 'max()' instead.

Body:
Is it possible to groupby and sort results within each groupby result in Python/Pandas?

Trying to find the top Genere in each year in below given data.Tried a lot using groupby and sort but no luck.

Input::

release_year    Genere      Count

1997            Action      46
1997            Adventure   7
1997            Animation   2
1997            Children's  12
1997            Comedy      73
1997            Crime       22
1997            Documentary 6
1997            Drama       81
1997            Horror      6
1997            Mystery     5
1997            Romance     15
1997            Sci-Fi      1
1997            Thriller    9
1997            War         1

1998            Action      12
1998            Adventure   2
1998            Comedy      24
1998            Crime       6
1998            Documentary 2
1998            Drama       21
1998            Film-Noir   2
1998            Horror      3
1998            Romance     4
1998            Thriller    1

Expected Output:

release_year    Genere      Count
1997            Drama       81
1998            Comedy      24

Body:
Here is my solution:

df_res = df.groupby(['release_year','Genere'])['Count'].sum().reset_index()
indexs = []
for year in df_res['release_year'].unique():
    df_temp = df_res[df_res.release_year==year]
    indexs += list(df_temp[df_temp['Count']==df_temp['Count'].max()].index)
df_res = df_res.loc[indexs]

I don't use 'sort()'. I use 'max()' instead.


答: Use the target="_blank" to opens the linked document in a new window or tab.

Title: create hyperlink that open in new tab/window using external javascript


问:
How to scale svg background for react.js app?
I have a problem with scaling my background svg image. I would expect it to scale to every browser window size, but right now it doesn't scale vertically no matter what params I set. I already tried removing width and height directly in svg file as stated in Why don't my SVG images scale using the CSS "width" property? and attempted to adjust viewBox and preserveAspectRatio manually, but the image at some point of scaling always ends up with messed up height (for example 1/3 of the full height for mobile devices). Am I doing something wrong with the image or should I simply create another one for different ratios?

My SVG background

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 960 560" enable-background="new 0 0 960 560" xml:space="preserve">
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="162.3691" y1="646.5293" x2="893.0117" y2="646.5293" gradientTransform="matrix(0.8443 -0.5359 0.5359 0.8443 -42.54 93.5288)">
    <stop  offset="0" style="stop-color:#4C0082"/>
    <stop  offset="0.385" style="stop-color:#4C0382"/>
    <stop  offset="0.6165" style="stop-color:#4D0B81"/>
    <stop  offset="0.8074" style="stop-color:#4F1980"/>
    <stop  offset="0.9753" style="stop-color:#522D7E"/>
    <stop  offset="1" style="stop-color:#52317E"/>
    <stop  offset="1" style="stop-color:#52317E"/>
</linearGradient>
<polyline fill="url(#SVGID_1_)" points="822.948,62.45 1303.946,548.438 674.11,919.56 259.071,124.032 "/>
<polyline fill="none" points="111.374,570.263 560.868,-4.484 -31.051,-20.646 -66.404,551.071 -30.041,569.253 111.374,570.263
    -338.119,1145.007 "/>
<polyline fill="#11102F" points="1398,-193 696,-193 258.103,-46.896 763.579,458.579 1008.067,314.586 "/>
<polyline fill="#410069" points="1035.566,291.588 334.097,701.066 1301.061,943.584 1213.131,524.346 "/>
<linearGradient id="SVGID_2_" gradientUnits="userSpaceOnUse" x1="-247.6929" y1="273.7153" x2="482.9502" y2="273.7153" gradientTransform="matrix(0.8443 -0.5359 0.5359 0.8443 -42.54 93.5288)">
    <stop  offset="0" style="stop-color:#4C0082"/>
    <stop  offset="0.385" style="stop-color:#4C0382"/>
    <stop  offset="0.6165" style="stop-color:#4D0B81"/>
    <stop  offset="0.8074" style="stop-color:#4F1980"/>
    <stop  offset="0.9753" style="stop-color:#522D7E"/>
    <stop  offset="1" style="stop-color:#52317E"/>
    <stop  offset="1" style="stop-color:#52317E"/>
</linearGradient>
<polyline fill="url(#SVGID_2_)" points="276.948,-32.55 757.946,453.438 128.11,824.56 -286.929,29.032 "/>
</svg>
</code>```

Body:
I have a problem with scaling my background svg image. I would expect it to scale to every browser window size, but right now it doesn't scale vertically no matter what params I set. I already tried removing width and height directly in svg file as stated in Why don't my SVG images scale using the CSS "width" property? and attempted to adjust viewBox and preserveAspectRatio manually, but the image at some point of scaling always ends up with messed up height (for example 1/3 of the full height for mobile devices). Am I doing something wrong with the image or should I simply create another one for different ratios?

My SVG background

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 960 560" enable-background="new 0 0 960 560" xml:space="preserve">
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="162.3691" y1="646.5293" x2="893.0117" y2="646.5293" gradientTransform="matrix(0.8443 -0.5359 0.5359 0.8443 -42.54 93.5288)">
    <stop  offset="0" style="stop-color:#4C0082"/>
    <stop  offset="0.385" style="stop-color:#4C0382"/>
    <stop  offset="0.6165" style="stop-color:#4D0B81"/>
    <stop  offset="0.8074" style="stop-color:#4F1980"/>
    <stop  offset="0.9753" style="stop-color:#522D7E"/>
    <stop  offset="1" style="stop-color:#52317E"/>
    <stop  offset="1" style="stop-color:#52317E"/>
</linearGradient>
<polyline fill="url(#SVGID_1_)" points="822.948,62.45 1303.946,548.438 674.11,919.56 259.071,124.032 "/>
<polyline fill="none" points="111.374,570.263 560.868,-4.484 -31.051,-20.646 -66.404,551.071 -30.041,569.253 111.374,570.263
    -338.119,1145.007 "/>
<polyline fill="#11102F" points="1398,-193 696,-193 258.103,-46.896 763.579,458.579 1008.067,314.586 "/>
<polyline fill="#410069" points="1035.566,291.588 334.097,701.066 1301.061,943.584 1213.131,524.346 "/>
<linearGradient id="SVGID_2_" gradientUnits="userSpaceOnUse" x1="-247.6929" y1="273.7153" x2="482.9502" y2="273.7153" gradientTransform="matrix(0.8443 -0.5359 0.5359 0.8443 -42.54 93.5288)">
    <stop  offset="0" style="stop-color:#4C0082"/>
    <stop  offset="0.385" style="stop-color:#4C0382"/>
    <stop  offset="0.6165" style="stop-color:#4D0B81"/>
    <stop  offset="0.8074" style="stop-color:#4F1980"/>
    <stop  offset="0.9753" style="stop-color:#522D7E"/>
    <stop  offset="1" style="stop-color:#52317E"/>
    <stop  offset="1" style="stop-color:#52317E"/>
</linearGradient>
<polyline fill="url(#SVGID_2_)" points="276.948,-32.55 757.946,453.438 128.11,824.56 -286.929,29.032 "/>
</svg>

Body:
Take a look at preserveAspectRatio and ensure your html, body, and svg elements are all taking up 100% height of the viewport.

html {
  height: 100%;
}

body {
  margin: 0;
  background: #4C0082;
  height: 100%;
}

svg {
  height: 100%;
  width: 100%;
}

<svg preserveAspectRatio="xMidYMid meet" viewBox="0 0 960 560">
 <linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="162.3691" y1="646.5293" x2="893.0117" y2="646.5293" gradientTransform="matrix(0.8443 -0.5359 0.5359 0.8443 -42.54 93.5288)">    <stop  offset="0" style="stop-color:#4C0082"/>    <stop  offset="0.385" style="stop-color:#4C0382"/>    <stop  offset="0.6165" style="stop-color:#4D0B81"/>    <stop  offset="0.8074" style="stop-color:#4F1980"/>    <stop  offset="0.9753" style="stop-color:#522D7E"/>    <stop  offset="1" style="stop-color:#52317E"/>    <stop  offset="1" style="stop-color:#52317E"/></linearGradient><polyline fill="url(#SVGID_1_)" points="822.948,62.45 1303.946,548.438 674.11,919.56 259.071,124.032 "/><polyline fill="none" points="111.374,570.263 560.868,-4.484 -31.051,-20.646 -66.404,551.071 -30.041,569.253 111.374,570.263     -338.119,1145.007 "/><polyline fill="#11102F" points="1398,-193 696,-193 258.103,-46.896 763.579,458.579 1008.067,314.586 "/><polyline fill="#410069" points="1035.566,291.588 334.097,701.066 1301.061,943.584 1213.131,524.346 "/><linearGradient id="SVGID_2_" gradientUnits="userSpaceOnUse" x1="-247.6929" y1="273.7153" x2="482.9502" y2="273.7153" gradientTransform="matrix(0.8443 -0.5359 0.5359 0.8443 -42.54 93.5288)">    <stop  offset="0" style="stop-color:#4C0082"/>    <stop  offset="0.385" style="stop-color:#4C0382"/>    <stop  offset="0.6165" style="stop-color:#4D0B81"/>    <stop  offset="0.8074" style="stop-color:#4F1980"/>    <stop  offset="0.9753" style="stop-color:#522D7E"/>    <stop  offset="1" style="stop-color:#52317E"/>    <stop  offset="1" style="stop-color:#52317E"/></linearGradient><polyline fill="url(#SVGID_2_)" points="276.948,-32.55 757.946,453.438 128.11,824.56 -286.929,29.032 "/>
</svg>


问:
how do you get back sum('amount') for a paginated eloquent query In laravel 5?
I have a model Logbook for pilot and my controller Return

$this->log_book->orderBy('flight_date','asc')->paginate(18);

I want to sum total flight time in each page.

total flight time for first page calculate from DB but for second page and next page , $previous_total_page_time should be total time of first page and for next page too.

I don't know how can save a variable temporary $page_previous_total_time and use it in second and next pages

flight time is saved as A Int (minutes in integer)

request is Get

in this image you see my view

答:
You can calculate the total flight time on each request. This is not tested but hypothetically it should work.

```<code>$logBook = $this->log_book->orderBy('flight_date','asc');

$logBookPagination = $logBook->paginate(18);

// change the offset value to a value that makes sense for you
$logBookFlightTime = $logBook->offset(0)->limit($logBookPagination->perPage() * $logBookPagination->currentPage())->sum('id'); // replace with your column

return [
   'logBook' => $logBookPagination,
   'totalFlightTime' => $logBookFlightTime
];
</code>```

To explain what i am doing is, i am taking a slice of models from 0 - the current page and then adding the flight time of all those models.

Body:
You can calculate the total flight time on each request. This is not tested but hypothetically it should work.

$logBook = $this->log_book->orderBy('flight_date','asc');

$logBookPagination = $logBook->paginate(18);

// change the offset value to a value that makes sense for you
$logBookFlightTime = $logBook->offset(0)->limit($logBookPagination->perPage() * $logBookPagination->currentPage())->sum('id'); // replace with your column

return [
   'logBook' => $logBookPagination,
   'totalFlightTime' => $logBookFlightTime
];

To explain what i am doing is, i am taking a slice of models from 0 - the current page and then adding the flight time of all those models.