问:
Tablesorter does not sanitize spaces when filtering, PHP syntax error?
Context :
When I use a PHP echo <?= &var ?> in HTML, it causes white space in my HTML element.
I have already tried to modify the file with another IDE to be sure that it is not an issue of indents but I have the same result. Same result on Chrome or Firefox...

Problem :
The filter of the plugin tablesorter also filters the white spaces and that does not return me the expected result. It works if I manually remove spaces

Question :
Is this a PHP syntax error or something else?

My PHP code :

```<code><td class="hidden-sm hidden-xs date">
    <?php if ($approval['STACODEM'] == '200'):?>
    <span data-toggle="popover" data-placement="top" data-trigger="hover focus" data-container="body" data-content="<?= $imgDuesDaysPopover ?>">
        <img src="<?= $imgDueDays ?>" alt="" name="imgDueDays"/>
    </span>
    <?php endif ?>
    <?= $dueDate ?>
</td>
</code>```

In the Chrome viewer :

The line with a date :

If I filter, no results found :

答:
It's because of your html layout. You can inline your code to solve this.

```<code><td class="hidden-sm hidden-xs date">Everything in here</td>
</code>```

Or you can customize how the tablesorter orders your rows.

Easiest inlining would be by assigning the result of your if clause to a variable.

```<code><?php
$img = '';
if ($approval['STACODEM'] == '200') {
    $img = <<<IMG
    <span data-toggle="popover" data-placement="top" data-trigger="hover focus" data-container="body" data-content="{$imgDuesDaysPopover}">
        <img src="{$imgDueDays}" alt="" name="imgDueDays"/>
    </span>
IMG;
}
?>
<td class="hidden-sm hidden-xs date"><?= $img.$dueDate ?></td>
</code>```

PS: But be careful, your $img variable will also have spaces if you don't inline it. (Don't know if your tablesorter completely ignores the html.)

Body:
Context :
When I use a PHP echo <?= &var ?> in HTML, it causes white space in my HTML element.
I have already tried to modify the file with another IDE to be sure that it is not an issue of indents but I have the same result. Same result on Chrome or Firefox...

Problem :
The filter of the plugin tablesorter also filters the white spaces and that does not return me the expected result. It works if I manually remove spaces

Question :
Is this a PHP syntax error or something else?

My PHP code :

    <?php if ($approval['STACODEM'] == '200'):?>
    <span data-toggle="popover" data-placement="top" data-trigger="hover focus" data-container="body" data-content="<?= $imgDuesDaysPopover ?>">
        <img src="<?= $imgDueDays ?>" alt="" name="imgDueDays"/>

    <?php endif ?>
    <?= $dueDate ?>

In the Chrome viewer :

The line with a date :

If I filter, no results found :

Body:
It's because of your html layout. You can inline your code to solve this.

<td class="hidden-sm hidden-xs date">Everything in here</td>

Or you can customize how the tablesorter orders your rows.

Easiest inlining would be by assigning the result of your if clause to a variable.

<?php
$img = '';
if ($approval['STACODEM'] == '200') {
    $img = <<<IMG
    <span data-toggle="popover" data-placement="top" data-trigger="hover focus" data-container="body" data-content="{$imgDuesDaysPopover}">
        <img src="{$imgDueDays}" alt="" name="imgDueDays"/>
    </span>
IMG;
}
?>
<td class="hidden-sm hidden-xs date"><?= $img.$dueDate ?></td>

PS: But be careful, your $img variable will also have spaces if you don't inline it. (Don't know if your tablesorter completely ignores the html.)


来源: stackexchange

问:
How to press key and do a function in the background of tkinter GUI?
I'm making a program that make a optional copy, for example when pressing a key like num 1 which paste something you chose in program  or num 2 which paste something you chose in program..
but that program should work in background (minimized) but it doesn't work..

```<code>from tkinter import *
from tkinter import ttk

first = ''
second = ''

root = Tk()
#root.withdraw()
ttk.Label(root, text="1st copy").grid(row=0, column=0, padx=3, sticky='w')

copy1 = ttk.Entry(root, width=36)
copy1.grid(row=0, column=1, columnspan=2)

ttk.Label(root, text="2nd copy").grid(row=1, column=0, padx=3, sticky='w')

copy2 = ttk.Entry(root, width=36)
copy2.grid(row=1, column=1, columnspan=2)

savebutton = ttk.Button(root, text='save')
savebutton.grid(row=2, column=2, sticky='e')
savebutton.config(command=lambda:save())

def save():
    global first, second
    first = copy1.get()
    second = copy2.get()

def BuClick(x):
    global first, second

    root.clipboard_clear()
    if x == 1:
        root.clipboard_append(first)
    else:
        root.clipboard_append(second)
    root.update()

root.bind('1', lambda x = 1:BuClick(1))
root.bind('2', lambda y = 2:BuClick(2))
</code>```

so how I can make it work in background ??
Thanks in advance..

答:
You can use keyboard like this.

```<code>import keyboard as kb
def call_back():
    pass
kb.add_hotkey("shift+1",call_back,args)
kb.wait()
</code>```

This, however, would get called even if the focus is not on your app(if you were using a different one).

ContentLicense: CC BY-SA 4.0

Body:
I'm making a program that make a optional copy, for example when pressing a key like num 1 which paste something you chose in program  or num 2 which paste something you chose in program..
but that program should work in background (minimized) but it doesn't work..

from tkinter import *
from tkinter import ttk

first = ''
second = ''

root = Tk()
#root.withdraw()
ttk.Label(root, text="1st copy").grid(row=0, column=0, padx=3, sticky='w')

copy1 = ttk.Entry(root, width=36)
copy1.grid(row=0, column=1, columnspan=2)

ttk.Label(root, text="2nd copy").grid(row=1, column=0, padx=3, sticky='w')

copy2 = ttk.Entry(root, width=36)
copy2.grid(row=1, column=1, columnspan=2)

savebutton = ttk.Button(root, text='save')
savebutton.grid(row=2, column=2, sticky='e')
savebutton.config(command=lambda:save())

def save():
    global first, second
    first = copy1.get()
    second = copy2.get()

def BuClick(x):
    global first, second

    root.clipboard_clear()
    if x == 1:
        root.clipboard_append(first)
    else:
        root.clipboard_append(second)
    root.update()

root.bind('1', lambda x = 1:BuClick(1))
root.bind('2', lambda y = 2:BuClick(2))

so how I can make it work in background ??
Thanks in advance..

Body:
You can use keyboard like this.

import keyboard as kb
def call_back():
    pass
kb.add_hotkey("shift+1",call_back,args)
kb.wait()

This, however, would get called even if the focus is not on your app(if you were using a different one).


问:
Laravel upgrade 5.5 Error "Method getPath does not exist."
I have upgraded Laravel from 5.2 to 5.5. All seems ok except one error Method getPath does not exist.. I can't see any trace hence unable to figure out why and where it is throwing this error. This is not coming everytime but sometimes.

Any help will be appreciated.

答:
Change

```<code>Route::getCurrentRoute()->getRoute();
</code>```

To

```<code>Route::getCurrentRoute()->uri();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Change

Route::getCurrentRoute()->getRoute();

To

Route::getCurrentRoute()->uri();


问:
Terraform 0.9.6 remote config outdated
I have been trying to update some of the terraform scripts from version 0.6.13 to 0.9.6. In my scripts I had before

```<code>     terraform remote config -backend=s3 \
      -backend-config="bucket=my_bucker" \
      -backend-config="access_key=my_access_key" \
      -backend-config="secret_key=my_secret" \
      -backend-config="region=my_region" \
      -backend-config="key=my_state_key"
</code>```

and then

```<code>     terraform/terraform remote pull
</code>```

Which was pulling the remote state from aws. Upon running terraform apply it will give me the exact resources that needed to be updated/ created based on the remote tfstate that is stored in an s3 bucket.

Now the issue I'm facing is that remote pull and remote config commands are outdated and don't work anymore.

I tried to follow the instructions on https://www.terraform.io/docs/backends/types/remote.html
    however it was not much helpful.

From what I understand I would have to do an init first with a partial configuration which presumably would automatically pull the remote state as following:

```<code>`terraform init -var-file="terraform.tfvars"\
 -backend=true \
 -backend-config="bucket=my_bucker" \
  -backend-config="access_key=my_access_key" \
  -backend-config="secret_key=my_secret" \
  -backend-config="region=my_region" \
  -backend-config="key=my_state_key"`
</code>```

However it doesn't really pull the remote state as it was doing before.

Would anyone be able to guide me into the right direction?

答: You don't need terraform remote pull any more. Terraform by default will automatically based on the refresh flag which defaults to true.

Title: Terraform 0.9.6 remote config outdated

Body:
I have been trying to update some of the terraform scripts from version 0.6.13 to 0.9.6. In my scripts I had before

     terraform remote config -backend=s3 \
      -backend-config="bucket=my_bucker" \
      -backend-config="access_key=my_access_key" \
      -backend-config="secret_key=my_secret" \
      -backend-config="region=my_region" \
      -backend-config="key=my_state_key"

and then

     terraform/terraform remote pull

Which was pulling the remote state from aws. Upon running terraform apply it will give me the exact resources that needed to be updated/ created based on the remote tfstate that is stored in an s3 bucket.

Now the issue I'm facing is that remote pull and remote config commands are outdated and don't work anymore.

I tried to follow the instructions on https://www.terraform.io/docs/backends/types/remote.html
    however it was not much helpful.

From what I understand I would have to do an init first with a partial configuration which presumably would automatically pull the remote state as following:

`terraform init -var-file="terraform.tfvars"\
 -backend=true \
 -backend-config="bucket=my_bucker" \
  -backend-config="access_key=my_access_key" \
  -backend-config="secret_key=my_secret" \
  -backend-config="region=my_region" \
  -backend-config="key=my_state_key"`

However it doesn't really pull the remote state as it was doing before.

Would anyone be able to guide me into the right direction?


问:
Programmatically mounting a FAT32 filesystem with UTF8
How can I mount a FAT/FAT32 device using "mount()" function (from "mount.h", see "man 2 mount") in a way that it will be mounted UTF8?

This is the relevant code I use to mount it 'til now:

```<code>mount_result = mount(device_node, device_mount_point, fstype, MS_NOATIME, "");
</code>```

Thanks,
Nicola

答:
The last argument to the mount command is a string interpreted by the file system driver in the kernel. It is the same you would pass to the mount shell command. For UTF8 I believe the string should be:</p>

```<code>mount_result = mount(device_node, device_mount_point, fstype, MS_NOATIME, "iocharset=utf8");
</code>```

Body:
How can I mount a FAT/FAT32 device using "mount()" function (from "mount.h", see "man 2 mount") in a way that it will be mounted UTF8?

This is the relevant code I use to mount it 'til now:

mount_result = mount(device_node, device_mount_point, fstype, MS_NOATIME, "");

Thanks,
Nicola

Body:
The last argument to the mount command is a string interpreted by the file system driver in the kernel. It is the same you would pass to the mount shell command. For UTF8 I believe the string should be:

mount_result = mount(device_node, device_mount_point, fstype, MS_NOATIME, "iocharset=utf8");


问:
How can I stop emails being sent automatically to followers when a record is created?
Whenever I create a record like in subscription or change the states in the record, a mail is triggered to the followers present in record with the logs. How to stop sending these mails automatically which picks up the logs created in the form view?</p>

答:
Here is the create() of mail.thread where this comes from:

    @api.model
    def create(self, values):
        """ Chatter override :
            - subscribe uid
            - subscribe followers of parent
            - log a creation message
        """
        if self._context.get('tracking_disable'):
            return super(MailThread, self).create(values)

        # subscribe uid unless asked not to
        if not self._context.get('mail_create_nosubscribe'):
            message_follower_ids = values.get('message_follower_ids') or []  # webclient can send None or False
            message_follower_ids += self.env['mail.followers']._add_follower_command(self._name, [], {self.env.user.partner_id.id: None}, {}, force=True)[0]
            values['message_follower_ids'] = message_follower_ids
        thread = super(MailThread, self).create(values)

        # automatic logging unless asked not to (mainly for various testing purpose)
        if not self._context.get('mail_create_nolog'):
            doc_name = self.env['ir.model'].search([('model', '=', self._name)]).read(['name'])[0]['name']
            thread.message_post(body=_('%s created') % doc_name)

        # auto_subscribe: take values and defaults into account
        create_values = dict(values)
        for key, val in self._context.iteritems():
            if key.startswith('default_') and key[8:] not in create_values:
                create_values[key[8:]] = val
        thread.message_auto_subscribe(create_values.keys(), values=create_values)

        # track values
        if not self._context.get('mail_notrack'):
            if 'lang' not in self._context:
                track_thread = thread.with_context(lang=self.env.user.lang)
            else:
                track_thread = thread
            tracked_fields = track_thread._get_tracked_fields(values.keys())
            if tracked_fields:
                initial_values = {thread.id: dict.fromkeys(tracked_fields, False)}
                track_thread.message_track(tracked_fields, initial_values)

        return thread
```

<p>As you can see there are some context flags to handle such situations. For your requirment <code>mail_create_nolog</code> should be used:</p>

<pre class="lang-py prettyprint-override"><code>@api.model
def create(self, vals):
    return super(MyModel, self.with_context(mail_create_nolog=1)).create(vals)
</code>```

Body:
Here is the create() of mail.thread where this comes from:

    @api.model
    def create(self, values):
        """ Chatter override :
            - subscribe uid
            - subscribe followers of parent
            - log a creation message
        """
        if self._context.get('tracking_disable'):
            return super(MailThread, self).create(values)

        # subscribe uid unless asked not to
        if not self._context.get('mail_create_nosubscribe'):
            message_follower_ids = values.get('message_follower_ids') or []  # webclient can send None or False
            message_follower_ids += self.env['mail.followers']._add_follower_command(self._name, [], {self.env.user.partner_id.id: None}, {}, force=True)[0]
            values['message_follower_ids'] = message_follower_ids
        thread = super(MailThread, self).create(values)

        # automatic logging unless asked not to (mainly for various testing purpose)
        if not self._context.get('mail_create_nolog'):
            doc_name = self.env['ir.model'].search([('model', '=', self._name)]).read(['name'])[0]['name']
            thread.message_post(body=_('%s created') % doc_name)

        # auto_subscribe: take values and defaults into account
        create_values = dict(values)
        for key, val in self._context.iteritems():
            if key.startswith('default_') and key[8:] not in create_values:
                create_values[key[8:]] = val
        thread.message_auto_subscribe(create_values.keys(), values=create_values)

        # track values
        if not self._context.get('mail_notrack'):
            if 'lang' not in self._context:
                track_thread = thread.with_context(lang=self.env.user.lang)
            else:
                track_thread = thread
            tracked_fields = track_thread._get_tracked_fields(values.keys())
            if tracked_fields:
                initial_values = {thread.id: dict.fromkeys(tracked_fields, False)}
                track_thread.message_track(tracked_fields, initial_values)

        return thread

As you can see there are some context flags to handle such situations. For your requirment mail_create_nolog should be used:

@api.model
def create(self, vals):
    return super(MyModel, self.with_context(mail_create_nolog=1)).create(vals)


问:
Unable to hide the column header based on the boolean value in the component
I am trying to show and hide a header and row based on a boolean value in component. I am able to hide the specific td but not able to hide the specific column. In the example below , I am trying to hide Last Edited row which includes th and td element. If I set the boolean variable to false, the td for that column is not shown but how do i hide the header. It doesn't seem to work if I put the following condition

```<code>  <th *ngIf="c == ColumnNames[1] && showCol""
</code>```

Html

```<code> <div *ngIf="LegalFundClasses && LegalFundClasses.LegalFundClassDetailsViewModel && ColumnNames">
     <table class="fundClassesTable table-striped">
      <tr *ngFor="let c of ColumnNames">
        <th [ngClass]="c != ColumnNames[2] ? 'tableItem bold' : 'cellbgcolor'" >{{ c }}</th>
        <ng-container *ngFor="let f of LegalFundClasses.LegalFundClassDetailsViewModel; let i=index">
          <td class="tableItem" *ngIf="c == ColumnNames[0]">{{f.Description}}</td>
          <td class="tableItem" *ngIf="c == ColumnNames[1] && showCol">{{f.AuditSummary}}</td>
          <td class="tableItem" *ngIf="c == ColumnNames[2]">{{f.Id}}</td
        </ng-container>
      </tr>
    </table>
  </div>
</code>```

Component

```<code> public showCol: boolean = false;
 public ColumnNames: string[] = ['Legal Class Name',
                                    'Last Edited',
                                    'Legal Class ID'
                                  ];
</code>```

Here is the fiddle

https://jsfiddle.net/zyk9xhd1/9/

答:
You can put condition in both th and td tag

```<code><table class="fundClassesTable table-striped" border="1">
      <tr *ngFor="let c of ColumnNames" >
        <th *ngIf="c == ColumnNames[1] && showCol" [ngClass]="c != ColumnNames[2] ? 'tableItem bold' : 'cellbgcolor'" >{{ c }}</th>
        <ng-container *ngFor="let f of data">
          <td class="tableItem" *ngIf="c == ColumnNames[0]">{{f.Description}}</td>
          <td class="tableItem" *ngIf="c == ColumnNames[1] && showCol">{{f.AuditSummary}}</td>
          <td class="tableItem" *ngIf="c == ColumnNames[2]">{{f.Id}}</td>
        </ng-container>
      </tr>
      </table>
</code>```

https://jsfiddle.net/viethien/w5rq3ghv/16/

Body:
I am trying to show and hide a header and row based on a boolean value in component. I am able to hide the specific td but not able to hide the specific column. In the example below , I am trying to hide Last Edited row which includes th and td element. If I set the boolean variable to false, the td for that column is not shown but how do i hide the header. It doesn't seem to work if I put the following condition

  <th *ngIf="c == ColumnNames[1] && showCol""

Html

        {{ c }}
        <ng-container *ngFor="let f of LegalFundClasses.LegalFundClassDetailsViewModel; let i=index">
          {{f.Description}}
          {{f.AuditSummary}}
          {{f.Id}}</td
        </ng-container>

Component

 public showCol: boolean = false;
 public ColumnNames: string[] = ['Legal Class Name',
                                    'Last Edited',
                                    'Legal Class ID'
                                  ];

Here is the fiddle

https://jsfiddle.net/zyk9xhd1/9/

Body:
You can put condition in both th and td tag

<table class="fundClassesTable table-striped" border="1">
      <tr *ngFor="let c of ColumnNames" >
        <th *ngIf="c == ColumnNames[1] && showCol" [ngClass]="c != ColumnNames[2] ? 'tableItem bold' : 'cellbgcolor'" >{{ c }}</th>
        <ng-container *ngFor="let f of data">
          <td class="tableItem" *ngIf="c == ColumnNames[0]">{{f.Description}}</td>
          <td class="tableItem" *ngIf="c == ColumnNames[1] && showCol">{{f.AuditSummary}}</td>
          <td class="tableItem" *ngIf="c == ColumnNames[2]">{{f.Id}}</td>
        </ng-container>
      </tr>
      </table>

https://jsfiddle.net/viethien/w5rq3ghv/16/


问:
How to access store values to components in vue js
This is my store.js

```<code>import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        isLoggedIn: !!localStorage.getItem('token'),
        isLog : !!localStorage.getItem('situation')
    },
    mutations: {
        loginUser (state) {
            state.isLoggedIn = true
            state.isLog = true
        },
        logoutUser (state) {
            state.isLoggedIn = false
            state.isLog = false
        },
    }
})
</code>```

but when I call {{state.isLoggedIn}} in the display.vue, I am not getting the values.

In display.vue, I use

```<code><script>
import axios from "axios";
import store from '../store';

export default {
  name: "BookList",
  data() {
    return {
      students: [],
      errors: [],
      state: this.state.isLoggedIn,

    };
  },
})
</script>

<template>
{{this.state}}
</template>
</code>```

But I am getting errors when i done this way. Please can anyone please help what is the problem.

答:
You don't need to import your store into your component. Instead, you should access it using this.$store.

For accessing the store state, the better (and recommended) way is to map the state within your component.

In your example it should be something like:

```<code>import { mapState } from 'vuex'

export default {
    ...
    computed: {
        ...mapState({
            isLoggedIn: 'isLoggedIn'
        })
     }
}
</code>```

In your template, this is not needed. Just call the property by its name:

```<code>{{ isLoggedIn }}
</code>```

Body:
This is my store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        isLoggedIn: !!localStorage.getItem('token'),
        isLog : !!localStorage.getItem('situation')
    },
    mutations: {
        loginUser (state) {
            state.isLoggedIn = true
            state.isLog = true
        },
        logoutUser (state) {
            state.isLoggedIn = false
            state.isLog = false
        },
    }
})

but when I call {{state.isLoggedIn}} in the display.vue, I am not getting the values.

In display.vue, I use

<template>
{{this.state}}
</template>

But I am getting errors when i done this way. Please can anyone please help what is the problem.

Body:
You don't need to import your store into your component. Instead, you should access it using this.$store.

For accessing the store state, the better (and recommended) way is to map the state within your component.

In your example it should be something like:

import { mapState } from 'vuex'

export default {
    ...
    computed: {
        ...mapState({
            isLoggedIn: 'isLoggedIn'
        })
     }
}

In your template, this is not needed. Just call the property by its name:

{{ isLoggedIn }}


问:
Xcode UITest sometimes does not find property of XCUIElement
In my UI tests, the frame property of some XCUIElement are found, but not of others.

The accessibility identifiers used below are set in storyboard, and app is initialised in setUp() as XCUIApplication().

Here is the storyboard layout:

The two UI elements used in the test are Text Field and Add Button.

Here is the relevant code:

```<code>func test() {
    // given
    let mainViewNavigationBar = app.navigationBars[„NavBar“]
    let navBarHeight = mainViewNavigationBar.frame.size.height
    print("navBarHeight: \(navBarHeight)") // is printed out correctly

    let addShoppingItemTextField = app.textFields["TextField"]
    let textFieldHeight = addShoppingItemTextField.frame.size.height // error breakpoint here
    print("textFieldHeight: \(textFieldHeight)")
}
</code>```

The test stops at an error breakpoint at the second last line with the following message:

```<code>No matches found for Find: Descendants matching type TextField from input {(
    Application, 0x60000019f070, pid: 13114, label: ‚xxx‘
)}
</code>```

I do not understand why the frame property, which should be defined for all XCUIElement, is found in the first case, but not in the second.

EDIT

Oletha pointed out below, that my constant addShoppingItemTextField is an XCUIElementQuery that should be resolved when I try to read the frame property of the textField.

Indeed, when the program stops at the test error breakpoint and I print its description, I get

```<code>Printing description of addShoppingItemTextField:
Query chain:
 →Find: Target Application 0x6080000a6ea0
  ↪Find: Descendants matching type TextField
    ↪Find: Elements matching predicate '"TextField" IN identifiers'
</code>```

But the find fails, although Accessibility is enabled, and the Accessibility Identifier is set to TextField:

I also inserted in the app

```<code>print(textField.accessibilityIdentifier!)
</code>```

in viewDidLoad(), and it printed out TextField correctly.

As a workaround, I set the test to recording, and tapped the textField. This created code for the access to the textField. I then replaced let addShoppingItemTextField = app.textFields["TextField"] by (the right side was generated by the recording):

```<code>let addShoppingItemTextField = app.otherElements.containing(.navigationBar, identifier:"WatchNotOK")
.children(matching: .other).element.children(matching: .other).element
.children(matching: .other).element
</code>```

And now the code works without errors.

So it seems to me that the query for the accessibility identifier of a textField does not work correctly.

EDIT 2

I give up: Without changing anything in the storyboard, the test now stops with the same test error (No matches found for Find: Elements matching predicate '"WatchNotOK" IN identifiers‘) at the line let navBarHeight = mainViewNavigationBar.frame.size.height. This did work all the time.

This indicates to me that Xcode UI tests are broken.

答:
In addition with above answers... I would like to add one point
This may happen because the XCUIElement you are accessing is not available on screen.
Suppose you are executing test case for login screen and simulator is launching with dashboard not with login screen. This happen with my case. I tried to logout and then execute test case. Error disappears

Body:
In my UI tests, the frame property of some XCUIElement are found, but not of others.

The accessibility identifiers used below are set in storyboard, and app is initialised in setUp() as XCUIApplication().

Here is the storyboard layout:

The two UI elements used in the test are Text Field and Add Button.

Here is the relevant code:

func test() {
    // given
    let mainViewNavigationBar = app.navigationBars[„NavBar“]
    let navBarHeight = mainViewNavigationBar.frame.size.height
    print("navBarHeight: \(navBarHeight)") // is printed out correctly

    let addShoppingItemTextField = app.textFields["TextField"]
    let textFieldHeight = addShoppingItemTextField.frame.size.height // error breakpoint here
    print("textFieldHeight: \(textFieldHeight)")
}

The test stops at an error breakpoint at the second last line with the following message:

No matches found for Find: Descendants matching type TextField from input {(
    Application, 0x60000019f070, pid: 13114, label: ‚xxx‘
)}

I do not understand why the frame property, which should be defined for all XCUIElement, is found in the first case, but not in the second.

EDIT

Oletha pointed out below, that my constant addShoppingItemTextField is an XCUIElementQuery that should be resolved when I try to read the frame property of the textField.

Indeed, when the program stops at the test error breakpoint and I print its description, I get

Printing description of addShoppingItemTextField:
Query chain:
 →Find: Target Application 0x6080000a6ea0
  ↪Find: Descendants matching type TextField
    ↪Find: Elements matching predicate '"TextField" IN identifiers'

But the find fails, although Accessibility is enabled, and the Accessibility Identifier is set to TextField:

I also inserted in the app

print(textField.accessibilityIdentifier!)

in viewDidLoad(), and it printed out TextField correctly.

As a workaround, I set the test to recording, and tapped the textField. This created code for the access to the textField. I then replaced let addShoppingItemTextField = app.textFields["TextField"] by (the right side was generated by the recording):

let addShoppingItemTextField = app.otherElements.containing(.navigationBar, identifier:"WatchNotOK")
.children(matching: .other).element.children(matching: .other).element
.children(matching: .other).element

And now the code works without errors.

So it seems to me that the query for the accessibility identifier of a textField does not work correctly.

EDIT 2

I give up: Without changing anything in the storyboard, the test now stops with the same test error (No matches found for Find: Elements matching predicate '"WatchNotOK" IN identifiers‘) at the line let navBarHeight = mainViewNavigationBar.frame.size.height. This did work all the time.

This indicates to me that Xcode UI tests are broken.


问:
jQuery solution for dynamically uploading multiple files
I have a form in which I am uploading pictures. I don't know how many pictures I may upload at a specific time. Are there any jQuery/AJAX solutions for dynamically adding a file upload field in a form?</p>

答:
simple code for adding a file field in form using jQuery</p>

```<code><form id="myForm" action="your-action">

    <input type="file" name="files[]" />

    <a href="#" onclick="addMoreFiles()">Add More</a>

</form>

<script>
       function addMoreFiles(){

           $("#myForm").append('<input type="file" name="files[]" />')
       }

 </script>
</code>```

Body:
simple code for adding a file field in form using jQuery

<form id="myForm" action="your-action">

    <input type="file" name="files[]" />

    <a href="#" onclick="addMoreFiles()">Add More</a>

</form>

<script>
       function addMoreFiles(){

           $("#myForm").append('<input type="file" name="files[]" />')
       }

 </script>


问:
How retry works in Azure Service Bus Java
I'm new to service bus, I'm curious about RetryPolicy and how it works, as per the documentation, retry had happened automatically for transient exceptions(MessagingExcepitons, ServerBusy), and the default retry count is 3, but we can set out custom retry policy using RetryExponential class.

I want to see the logs does the RetryPolicy did actually trying  to connect or not when exception occurs.

How can I check this, how to replicate MessagingExcepitons, ServerBusy exceptions, so that I can see the logs. I'm using azure service bus java sdk.

Can any one help me to understand this. Thanks in advance

答:
The Java SDK is open source and looking for retryPolicy in these files shows how the underlying implementation uses it

CoreMessageSender

CoreMessageReceiver

For example, here's the flow for CoreMessageSender when an error is thrown

When an error occurs and if its a ServiceBusException, a retry is scheduled - See line

After waiting, it ensures the link is still open and increments the retry count - See line

This continues and on successful completion it resets the count - See line

As for logging, the Java SDK uses SLF4J and you can see the required logs with a line like this in your code

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

Logger.getLogger("com.microsoft.azure.servicebus").setLevel(Level.WARN);
```


问:
Git. How to roll back changes in certain file in a chain of commits?
I have a repo with three files in it - 1.txt, 2.txt and 3.txt. I created a branch 'new_branch' and made commits (let's call them A, B and C), every of these commits contains changes in several files from my repo. Then I understood, that 1.txt was updated mistakenly. Is it possible to remove changes, made in 1.txt, from commits A, B and C but keep changes in 2.txt and 3.txt?

UPD. I want also to remove changes, made it 1.txt, from commit history. As result 'git log -p' should show, that only 2.txt and 3.txt were modified in commits A, B and C.

Many thanks.

答:
Assuming that your revision tree looks like this:

```<code>-- S <s.sha> -- A -- B -- C (HEAD)
</code>```

You can use git filter-branch to remove the changes from commits A..C made to a single file.

```<code>git filter-branch --tree-filter 'git checkout <s.sha> -- 1.txt' HEAD~3..
</code>```

This will:

check out each of the last three commits,

run the 'git checkout' for the 1.txt file bringing it to the version you want,

put the modified commits back on the tree.

This obviously rewrites history, so the same considerations are in place as for pushing a rebase.

Body:
Assuming that your revision tree looks like this:

-- S <s.sha> -- A -- B -- C (HEAD)

You can use git filter-branch to remove the changes from commits A..C made to a single file.

git filter-branch --tree-filter 'git checkout <s.sha> -- 1.txt' HEAD~3..

This will:

check out each of the last three commits,

run the 'git checkout' for the 1.txt file bringing it to the version you want,

put the modified commits back on the tree.

This obviously rewrites history, so the same considerations are in place as for pushing a rebase.


问:
Google recaptcha error in ie 11
I am getting the following error in IE 11:

SCRIPT5007: unable to get property "toString" of undefined or null
  reference recaptcha__iw.js (451, 41)

Could it be possible that there is an error in the script?

Working on Safari, Chrome and Firefox.

答:
just add this polyfill (taked from cdn.polyfill.io)</p>

```<code>(function(undefined) {

// Symbol
// A modification of https://github.com/WebReflection/get-own-property-symbols
// (C) Andrea Giammarchi - MIT Licensed

(function(Object, GOPS, global) {

  var setDescriptor;
  var id = 0;
  var random = '' + Math.random();
  var prefix = '__\x01symbol:';
  var prefixLength = prefix.length;
  var internalSymbol = '__\x01symbol@@' + random;
  var DP = 'defineProperty';
  var DPies = 'defineProperties';
  var GOPN = 'getOwnPropertyNames';
  var GOPD = 'getOwnPropertyDescriptor';
  var PIE = 'propertyIsEnumerable';
  var ObjectProto = Object.prototype;
  var hOP = ObjectProto.hasOwnProperty;
  var pIE = ObjectProto[PIE];
  var toString = ObjectProto.toString;
  var concat = Array.prototype.concat;
  var cachedWindowNames = typeof window === 'object' ? Object.getOwnPropertyNames(window) : [];
  var nGOPN = Object[GOPN];
  var gOPN = function getOwnPropertyNames(obj) {
    if (toString.call(obj) === '[object Window]') {
      try {
        return nGOPN(obj);
      } catch (e) {
        // IE bug where layout engine calls userland gOPN for cross-domain `window` objects
        return concat.call([], cachedWindowNames);
      }
    }
    return nGOPN(obj);
  };
  var gOPD = Object[GOPD];
  var create = Object.create;
  var keys = Object.keys;
  var freeze = Object.freeze || Object;
  var defineProperty = Object[DP];
  var $defineProperties = Object[DPies];
  var descriptor = gOPD(Object, GOPN);
  var addInternalIfNeeded = function(o, uid, enumerable) {
    if (!hOP.call(o, internalSymbol)) {
      try {
        defineProperty(o, internalSymbol, {
          enumerable: false,
          configurable: false,
          writable: false,
          value: {}
        });
      } catch (e) {
        o[internalSymbol] = {};
      }
    }
    o[internalSymbol]['@@' + uid] = enumerable;
  };
  var createWithSymbols = function(proto, descriptors) {
    var self = create(proto);
    gOPN(descriptors).forEach(function(key) {
      if (propertyIsEnumerable.call(descriptors, key)) {
        $defineProperty(self, key, descriptors[key]);
      }
    });
    return self;
  };
  var copyAsNonEnumerable = function(descriptor) {
    var newDescriptor = create(descriptor);
    newDescriptor.enumerable = false;
    return newDescriptor;
  };
  var get = function get() {};
  var onlyNonSymbols = function(name) {
    return name != internalSymbol &&
      !hOP.call(source, name);
  };
  var onlySymbols = function(name) {
    return name != internalSymbol &&
      hOP.call(source, name);
  };
  var propertyIsEnumerable = function propertyIsEnumerable(key) {
    var uid = '' + key;
    return onlySymbols(uid) ? (
      hOP.call(this, uid) &&
      this[internalSymbol]['@@' + uid]
    ) : pIE.call(this, key);
  };
  var setAndGetSymbol = function(uid) {
    var descriptor = {
      enumerable: false,
      configurable: true,
      get: get,
      set: function(value) {
        setDescriptor(this, uid, {
          enumerable: false,
          configurable: true,
          writable: true,
          value: value
        });
        addInternalIfNeeded(this, uid, true);
      }
    };
    try {
      defineProperty(ObjectProto, uid, descriptor);
    } catch (e) {
      ObjectProto[uid] = descriptor.value;
    }
    return freeze(source[uid] = defineProperty(
      Object(uid),
      'constructor',
      sourceConstructor
    ));
  };
  var Symbol = function Symbol(description) {
    if (this instanceof Symbol) {
      throw new TypeError('Symbol is not a constructor');
    }
    return setAndGetSymbol(
      prefix.concat(description || '', random, ++id)
    );
  };
  var source = create(null);
  var sourceConstructor = {
    value: Symbol
  };
  var sourceMap = function(uid) {
    return source[uid];
  };
  var $defineProperty = function defineProp(o, key, descriptor) {
    var uid = '' + key;
    if (onlySymbols(uid)) {
      setDescriptor(o, uid, descriptor.enumerable ?
        copyAsNonEnumerable(descriptor) : descriptor);
      addInternalIfNeeded(o, uid, !!descriptor.enumerable);
    } else {
      defineProperty(o, key, descriptor);
    }
    return o;
  };

  var onlyInternalSymbols = function(obj) {
    return function(name) {
      return hOP.call(obj, internalSymbol) && hOP.call(obj[internalSymbol], '@@' + name);
    };
  };
  var $getOwnPropertySymbols = function getOwnPropertySymbols(o) {
    return gOPN(o).filter(o === ObjectProto ? onlyInternalSymbols(o) : onlySymbols).map(sourceMap);
  };

  descriptor.value = $defineProperty;
  defineProperty(Object, DP, descriptor);

  descriptor.value = $getOwnPropertySymbols;
  defineProperty(Object, GOPS, descriptor);

  descriptor.value = function getOwnPropertyNames(o) {
    return gOPN(o).filter(onlyNonSymbols);
  };
  defineProperty(Object, GOPN, descriptor);

  descriptor.value = function defineProperties(o, descriptors) {
    var symbols = $getOwnPropertySymbols(descriptors);
    if (symbols.length) {
      keys(descriptors).concat(symbols).forEach(function(uid) {
        if (propertyIsEnumerable.call(descriptors, uid)) {
          $defineProperty(o, uid, descriptors[uid]);
        }
      });
    } else {
      $defineProperties(o, descriptors);
    }
    return o;
  };
  defineProperty(Object, DPies, descriptor);

  descriptor.value = propertyIsEnumerable;
  defineProperty(ObjectProto, PIE, descriptor);

  descriptor.value = Symbol;
  defineProperty(global, 'Symbol', descriptor);

  // defining `Symbol.for(key)`
  descriptor.value = function(key) {
    var uid = prefix.concat(prefix, key, random);
    return uid in ObjectProto ? source[uid] : setAndGetSymbol(uid);
  };
  defineProperty(Symbol, 'for', descriptor);

  // defining `Symbol.keyFor(symbol)`
  descriptor.value = function(symbol) {
    if (onlyNonSymbols(symbol))
      throw new TypeError(symbol + ' is not a symbol');
    return hOP.call(source, symbol) ?
      symbol.slice(prefixLength * 2, -random.length) :
      void 0;
  };
  defineProperty(Symbol, 'keyFor', descriptor);

  descriptor.value = function getOwnPropertyDescriptor(o, key) {
    var descriptor = gOPD(o, key);
    if (descriptor && onlySymbols(key)) {
      descriptor.enumerable = propertyIsEnumerable.call(o, key);
    }
    return descriptor;
  };
  defineProperty(Object, GOPD, descriptor);

  descriptor.value = function(proto, descriptors) {
    return arguments.length === 1 || typeof descriptors === "undefined" ?
      create(proto) :
      createWithSymbols(proto, descriptors);
  };
  defineProperty(Object, 'create', descriptor);

  descriptor.value = function() {
    var str = toString.call(this);
    return (str === '[object String]' && onlySymbols(this)) ? '[object Symbol]' : str;
  };
  defineProperty(ObjectProto, 'toString', descriptor);

  setDescriptor = function(o, key, descriptor) {
    var protoDescriptor = gOPD(ObjectProto, key);
    delete ObjectProto[key];
    defineProperty(o, key, descriptor);
    if (o !== ObjectProto) {
      defineProperty(ObjectProto, key, protoDescriptor);
    }
  };

}(Object, 'getOwnPropertySymbols', this));}).call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
</code>```

Title: Google recaptcha error in ie 11

Body:
just add this polyfill (taked from cdn.polyfill.io)

(function(undefined) {

// Symbol
// A modification of https://github.com/WebReflection/get-own-property-symbols
// (C) Andrea Giammarchi - MIT Licensed

(function(Object, GOPS, global) {

  var setDescriptor;
  var id = 0;
  var random = '' + Math.random();
  var prefix = '__\x01symbol:';
  var prefixLength = prefix.length;
  var internalSymbol = '__\x01symbol@@' + random;
  var DP = 'defineProperty';
  var DPies = 'defineProperties';
  var GOPN = 'getOwnPropertyNames';
  var GOPD = 'getOwnPropertyDescriptor';
  var PIE = 'propertyIsEnumerable';
  var ObjectProto = Object.prototype;
  var hOP = ObjectProto.hasOwnProperty;
  var pIE = ObjectProto[PIE];
  var toString = ObjectProto.toString;
  var concat = Array.prototype.concat;
  var cachedWindowNames = typeof window === 'object' ? Object.getOwnPropertyNames(window) : [];
  var nGOPN = Object[GOPN];
  var gOPN = function getOwnPropertyNames(obj) {
    if (toString.call(obj) === '[object Window]') {
      try {
        return nGOPN(obj);
      } catch (e) {
        // IE bug where layout engine calls userland gOPN for cross-domain `window` objects
        return concat.call([], cachedWindowNames);
      }
    }
    return nGOPN(obj);
  };
  var gOPD = Object[GOPD];
  var create = Object.create;
  var keys = Object.keys;
  var freeze = Object.freeze || Object;
  var defineProperty = Object[DP];
  var $defineProperties = Object[DPies];
  var descriptor = gOPD(Object, GOPN);
  var addInternalIfNeeded = function(o, uid, enumerable) {
    if (!hOP.call(o, internalSymbol)) {
      try {
        defineProperty(o, internalSymbol, {
          enumerable: false,
          configurable: false,
          writable: false,
          value: {}
        });
      } catch (e) {
        o[internalSymbol] = {};
      }
    }
    o[internalSymbol]['@@' + uid] = enumerable;
  };
  var createWithSymbols = function(proto, descriptors) {
    var self = create(proto);
    gOPN(descriptors).forEach(function(key) {
      if (propertyIsEnumerable.call(descriptors, key)) {
        $defineProperty(self, key, descriptors[key]);
      }
    });
    return self;
  };
  var copyAsNonEnumerable = function(descriptor) {
    var newDescriptor = create(descriptor);
    newDescriptor.enumerable = false;
    return newDescriptor;
  };
  var get = function get() {};
  var onlyNonSymbols = function(name) {
    return name != internalSymbol &&
      !hOP.call(source, name);
  };
  var onlySymbols = function(name) {
    return name != internalSymbol &&
      hOP.call(source, name);
  };
  var propertyIsEnumerable = function propertyIsEnumerable(key) {
    var uid = '' + key;
    return onlySymbols(uid) ? (
      hOP.call(this, uid) &&
      this[internalSymbol]['@@' + uid]
    ) : pIE.call(this, key);
  };
  var setAndGetSymbol = function(uid) {
    var descriptor = {
      enumerable: false,
      configurable: true,
      get: get,
      set: function(value) {
        setDescriptor(this, uid, {
          enumerable: false,
          configurable: true,
          writable: true,
          value: value
        });
        addInternalIfNeeded(this, uid, true);
      }
    };
    try {
      defineProperty(ObjectProto, uid, descriptor);
    } catch (e) {
      ObjectProto[uid] = descriptor.value;
    }
    return freeze(source[uid] = defineProperty(
      Object(uid),
      'constructor',
      sourceConstructor
    ));
  };
  var Symbol = function Symbol(description) {
    if (this instanceof Symbol) {
      throw new TypeError('Symbol is not a constructor');
    }
    return setAndGetSymbol(
      prefix.concat(description || '', random, ++id)
    );
  };
  var source = create(null);
  var sourceConstructor = {
    value: Symbol
  };
  var sourceMap = function(uid) {
    return source[uid];
  };
  var $defineProperty = function defineProp(o, key, descriptor) {
    var uid = '' + key;
    if (onlySymbols(uid)) {
      setDescriptor(o, uid, descriptor.enumerable ?
        copyAsNonEnumerable(descriptor) : descriptor);
      addInternalIfNeeded(o, uid, !!descriptor.enumerable);
    } else {
      defineProperty(o, key, descriptor);
    }
    return o;
  };

  var onlyInternalSymbols = function(obj) {
    return function(name) {
      return hOP.call(obj, internalSymbol) && hOP.call(obj[internalSymbol], '@@' + name);
    };
  };
  var $getOwnPropertySymbols = function getOwnPropertySymbols(o) {
    return gOPN(o).filter(o === ObjectProto ? onlyInternalSymbols(o) : onlySymbols).map(sourceMap);
  };

  descriptor.value = $defineProperty;
  defineProperty(Object, DP, descriptor);

  descriptor.value = $getOwnPropertySymbols;
  defineProperty(Object, GOPS, descriptor);

  descriptor.value = function getOwnPropertyNames(o) {
    return gOPN(o).filter(onlyNonSymbols);
  };
  defineProperty(Object, GOPN, descriptor);

  descriptor.value = function defineProperties(o, descriptors) {
    var symbols = $getOwnPropertySymbols(descriptors);
    if (symbols.length) {
      keys(descriptors).concat(symbols).forEach(function(uid) {
        if (propertyIsEnumerable.call(descriptors, uid)) {
          $defineProperty(o, uid, descriptors[uid]);
        }
      });
    } else {
      $defineProperties(o, descriptors);
    }
    return o;
  };
  defineProperty(Object, DPies, descriptor);

  descriptor.value = propertyIsEnumerable;
  defineProperty(ObjectProto, PIE, descriptor);

  descriptor.value = Symbol;
  defineProperty(global, 'Symbol', descriptor);

  // defining `Symbol.for(key)`
  descriptor.value = function(key) {
    var uid = prefix.concat(prefix, key, random);
    return uid in ObjectProto ? source[uid] : setAndGetSymbol(uid);
  };
  defineProperty(Symbol, 'for', descriptor);

  // defining `Symbol.keyFor(symbol)`
  descriptor.value = function(symbol) {
    if (onlyNonSymbols(symbol))
      throw new TypeError(symbol + ' is not a symbol');
    return hOP.call(source, symbol) ?
      symbol.slice(prefixLength * 2, -random.length) :
      void 0;
  };
  defineProperty(Symbol, 'keyFor', descriptor);

  descriptor.value = function getOwnPropertyDescriptor(o, key) {
    var descriptor = gOPD(o, key);
    if (descriptor && onlySymbols(key)) {
      descriptor.enumerable = propertyIsEnumerable.call(o, key);
    }
    return descriptor;
  };
  defineProperty(Object, GOPD, descriptor);

  descriptor.value = function(proto, descriptors) {
    return arguments.length === 1 || typeof descriptors === "undefined" ?
      create(proto) :
      createWithSymbols(proto, descriptors);
  };
  defineProperty(Object, 'create', descriptor);

  descriptor.value = function() {
    var str = toString.call(this);
    return (str === '[object String]' && onlySymbols(this)) ? '[object Symbol]' : str;
  };
  defineProperty(ObjectProto, 'toString', descriptor);

  setDescriptor = function(o, key, descriptor) {
    var protoDescriptor = gOPD(ObjectProto, key);
    delete ObjectProto[key];
    defineProperty(o, key, descriptor);
    if (o !== ObjectProto) {
      defineProperty(ObjectProto, key, protoDescriptor);
    }
  };

}(Object, 'getOwnPropertySymbols', this));}).call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});


问:
How can I find out why my badge is not accepting HTML tags on its tooltip?
I am trying to add a bootstrap badge-alert with an HTML tooltip on it, following the example under: https://getbootstrap.com/docs/4.3/components/tooltips/

However, with the following code, the tooltip is shown, but the HTML tags are not interpreted.

The badge HTML code follows (it is a badge inside a table cell - td):

<span class="badge badge-pill badge-danger" data-toggle="tooltip" data-html="true" title="Tooltip with HTML">1
```

<p>I've tried activating the tooltips on the $(document).ready function, as stated on the page, with</p>

```   // initialize tooltips
   $('[data-toggle="tooltip"]').tooltip()
```

But still couldn't figure why it is happening.

I definitely have no idea on why the HTML is not getting formatted, nor how to debug/understand the source of this issue. How would you even start debugging it?

Thanks.

答:
Your code is working fine use all the links properly like below

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</code>```

$('[data-toggle="tooltip"]').tooltip();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

  <span class="badge badge-pill badge-danger" data-toggle="tooltip" data-html="true" title="<b>Tooltip</b> <u>with</u> <b>HTML</b>">1</span></code>```

Body:
I am trying to add a bootstrap badge-alert with an HTML tooltip on it, following the example under: https://getbootstrap.com/docs/4.3/components/tooltips/

However, with the following code, the tooltip is shown, but the HTML tags are not interpreted.

The badge HTML code follows (it is a badge inside a table cell - td):

<span class="badge badge-pill badge-danger" data-toggle="tooltip" data-html="true" title="Tooltip with HTML">1

I've tried activating the tooltips on the $(document).ready function, as stated on the page, with

   // initialize tooltips
   $('[data-toggle="tooltip"]').tooltip()

But still couldn't figure why it is happening.

I definitely have no idea on why the HTML is not getting formatted, nor how to debug/understand the source of this issue. How would you even start debugging it?

Thanks.

Body:
Your code is working fine use all the links properly like below

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

$('[data-toggle="tooltip"]').tooltip();

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

  <span class="badge badge-pill badge-danger" data-toggle="tooltip" data-html="true" title="<b>Tooltip</b> <u>with</u> <b>HTML</b>">1</span>


问:
how to implement search query for multiple record seperated by comma from single field single column?
```<code>if(count($_POST["search"]) > 0) {

     $arrayString =  implode("','",$_POST["search"]) ;
}
//echo $arrayString;exit;

 $sql="SELECT * FROM domain_inventory_Global_History WHERE company_domain in ('$arrayString') ";
 echo $sql;
</code>```

答:
$searchStrings = ['google.com','yahoo','fa'];

$sql = "SELECT * FROM domain_inventory_Global_History WHERE where company_domain like %".implode("% or company_domain like %",$searchStrings)."%";

echo $sql;


问:
how to create a view like this shape in swift?
how to create this 2D look

How to I create this.

Thanks a lot.

答:
Try this

```<code>class TwoDView : UIView {
    public var xDiff : CGFloat = 5.0
    public var yDiff : CGFloat = 5.0

    override func draw(_ rect: CGRect) {
        let ctx = UIGraphicsGetCurrentContext()

        ctx?.move(to: CGPoint(x: 0, y: rect.height - yDiff))
        ctx?.addLines(between: [
                CGPoint(x: rect.width - xDiff, y: rect.height - yDiff),
                CGPoint(x: rect.width, y: rect.height),
                CGPoint(x: xDiff, y: rect.height),
                CGPoint(x: 0, y: rect.height - yDiff)
            ])
        ctx?.setFillColor(UIColor.black.cgColor)
        ctx?.fillPath()

        ctx?.move(to: CGPoint(x: rect.width - xDiff, y: 0))
        ctx?.addLines(between: [
            CGPoint(x: rect.width, y: yDiff),
            CGPoint(x: rect.width, y: rect.height),
            CGPoint(x: rect.width - xDiff, y: rect.height - yDiff),
            CGPoint(x: rect.width - xDiff, y: 0)
            ])
        ctx?.setFillColor(UIColor.gray.cgColor)
        ctx?.fillPath()

        UIImage(named: "Image")?.draw(in: CGRect(x: 0, y: 0, width: rect.width - xDiff, height: rect.height - yDiff))

    }
}
</code>```

Body:
Try this

class TwoDView : UIView {
    public var xDiff : CGFloat = 5.0
    public var yDiff : CGFloat = 5.0

    override func draw(_ rect: CGRect) {
        let ctx = UIGraphicsGetCurrentContext()

        ctx?.move(to: CGPoint(x: 0, y: rect.height - yDiff))
        ctx?.addLines(between: [
                CGPoint(x: rect.width - xDiff, y: rect.height - yDiff),
                CGPoint(x: rect.width, y: rect.height),
                CGPoint(x: xDiff, y: rect.height),
                CGPoint(x: 0, y: rect.height - yDiff)
            ])
        ctx?.setFillColor(UIColor.black.cgColor)
        ctx?.fillPath()

        ctx?.move(to: CGPoint(x: rect.width - xDiff, y: 0))
        ctx?.addLines(between: [
            CGPoint(x: rect.width, y: yDiff),
            CGPoint(x: rect.width, y: rect.height),
            CGPoint(x: rect.width - xDiff, y: rect.height - yDiff),
            CGPoint(x: rect.width - xDiff, y: 0)
            ])
        ctx?.setFillColor(UIColor.gray.cgColor)
        ctx?.fillPath()

        UIImage(named: "Image")?.draw(in: CGRect(x: 0, y: 0, width: rect.width - xDiff, height: rect.height - yDiff))

    }
}


问:
Oracle : Selecting date by month with where clause
I came across a problem that in selecting the date for current desired month and year. I tried the 2 statements shown below but failed to execute the query

```<code>select to_char(sysdate, 'Month') from income

select * from income where to_char(sysdate,month) = 'feb'
</code>```

Update

But after researching and learning more in depth on oracle docs website. What i came out with is to use  "between" clause. Specifying the first day and last day of the month . Doing so, it will execute the desired month/year

For an example

```<code>SELECT column_name
FROM table_name where column_name = (Your own value) AND
column_date >= to_date('01/02/2012', 'dd/mm/yyyy')
and column_date <  to_date('01/03/2012', 'dd/mm/yyyy')
</code>```

I hope this help :)

答:
I think you can use the following query:</p>

```<code>select *
from   income
where  to_char(<date_column>,'MON-RRRR') = 'MAY-2019';
</code>```

Body:
I came across a problem that in selecting the date for current desired month and year. I tried the 2 statements shown below but failed to execute the query

select to_char(sysdate, 'Month') from income

select * from income where to_char(sysdate,month) = 'feb'

Update

But after researching and learning more in depth on oracle docs website. What i came out with is to use  "between" clause. Specifying the first day and last day of the month . Doing so, it will execute the desired month/year

For an example

SELECT column_name
FROM table_name where column_name = (Your own value) AND
column_date >= to_date('01/02/2012', 'dd/mm/yyyy')
and column_date <  to_date('01/03/2012', 'dd/mm/yyyy')

I hope this help :)

Body:
I think you can use the following query:

select *
from   income
where  to_char(<date_column>,'MON-RRRR') = 'MAY-2019';


问:
Twitter-oAuth-IPhone : Which function on Login Success : twits of followings
I am using Twitter-oAuth-IPhone https://github.com/bengottlieb/Twitter-OAuth-iPhone

Login using this code

```<code>if(![twitterObj isAuthorized]){
    UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine:twitterObj delegate:self];
    if (controller){
        NSLog(@"twitter 2");
        [[self objectForKey:@"self"] presentModalViewController: controller animated: YES];
    }
}
</code>```

I have 2 questions

I want to do some code on login success and login fail.... in which function should I code

Which function return me the my home page updates i.e twits of followings

Amit Battan

答:
I want to do some code on login success and login fail.... in which function should I code

- (void) storeCachedTwitterOAuthData: (NSString *) data forUsername: (NSString *) username

Which function return me the my home page updates i.e twits of followings

getFollowedTimelineSinceID

ContentLicense: CC BY-SA 2.5

Body:
I am using Twitter-oAuth-IPhone https://github.com/bengottlieb/Twitter-OAuth-iPhone

Login using this code

if(![twitterObj isAuthorized]){
    UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine:twitterObj delegate:self];
    if (controller){
        NSLog(@"twitter 2");
        [[self objectForKey:@"self"] presentModalViewController: controller animated: YES];
    }
}

I have 2 questions

I want to do some code on login success and login fail.... in which function should I code

Which function return me the my home page updates i.e twits of followings

Amit Battan


问:
TextField uppercase and lowercase validation
I am working on textfields validations and getting confused how to validate textfield must contain at least 1 character from all of the following categories:
English uppercase characters (A - Z).
English lowercase characters (a - z).</p>

答:
Have a look at CharacterSets (described here)

You can create various Character sets (lowercase letters for instance) and test whether a string has content that matches said character set.

So, you could create a function which returns a boolean. The function checks your string against two CharacterSets and only if both can be found in the string, does the function return true.

Something like this

```<code>func validate(string: String) -> Bool {
    let lowercase = CharacterSet.lowercaseLetters
    let uppercase = CharacterSet.uppercaseLetters

    let lowercaseRange = string.rangeOfCharacter(from: lowercase)
    let uppercaseRange = string.rangeOfCharacter(from: uppercase)

    return lowercaseRange != nil && uppercaseRange != nil
}

validate(string: "Hello") //returns true
validate(string: "hello") //returns false
validate(string: "HELLO") //returns false
</code>```

Have a look at this article from NSHipster to learn more.

Body:
Have a look at CharacterSets (described here)

You can create various Character sets (lowercase letters for instance) and test whether a string has content that matches said character set.

So, you could create a function which returns a boolean. The function checks your string against two CharacterSets and only if both can be found in the string, does the function return true.

Something like this

func validate(string: String) -> Bool {
    let lowercase = CharacterSet.lowercaseLetters
    let uppercase = CharacterSet.uppercaseLetters

    let lowercaseRange = string.rangeOfCharacter(from: lowercase)
    let uppercaseRange = string.rangeOfCharacter(from: uppercase)

    return lowercaseRange != nil && uppercaseRange != nil
}

validate(string: "Hello") //returns true
validate(string: "hello") //returns false
validate(string: "HELLO") //returns false

Have a look at this article from NSHipster to learn more.


问:
Single - row subQuery returns more that one row in Oracle
I am trying to write a Query in Oracle which will return multiple row ,but with this Query i am getting "Single row subquery returns more that one row", I have tried to use IN operations in the place of "=" operator but i can not make it , This is my Query

```<code> Update Quote_line_part_quantity
 SET
 resale_am =(
select target_resale
FROM Quote_line_part_quantity
where quote_id=100218906
)
WHERE
 quote_id=100218906
 AND quote_line_no IN(
 SELECT
 quote_line_no
 FROM
 Quote_Line
 WHERE
quote_id IN 100218906
AND quote_line_no=(1)
AND Quote_line_status_cd IN('R','A')
);
</code>```

I am confused why this is giving this error again and again .Please help

答:
The most likely problem is here:

```<code>set resale_am = (select target_resale
                 from Quote_line_part_quantity
                 where quote_id = 100218906
                )
</code>```

The best way to solve this is unclear, but adding and rownum = 1 will fix your immediate problem.

Body:
I am trying to write a Query in Oracle which will return multiple row ,but with this Query i am getting "Single row subquery returns more that one row", I have tried to use IN operations in the place of "=" operator but i can not make it , This is my Query

 Update Quote_line_part_quantity
 SET
 resale_am =(
select target_resale
FROM Quote_line_part_quantity
where quote_id=100218906
)
WHERE
 quote_id=100218906
 AND quote_line_no IN(
 SELECT
 quote_line_no
 FROM
 Quote_Line
 WHERE
quote_id IN 100218906
AND quote_line_no=(1)
AND Quote_line_status_cd IN('R','A')
);

I am confused why this is giving this error again and again .Please help

Body:
The most likely problem is here:

set resale_am = (select target_resale
                 from Quote_line_part_quantity
                 where quote_id = 100218906
                )

The best way to solve this is unclear, but adding and rownum = 1 will fix your immediate problem.


问:
Javascript (ES6) Date to String format
In Javascript I have Date object which I need to convert to string of format dd.mm.yyyy and dd.mm.yyyy hh24:mi:ss. How do I format the Date in Javascript?

答:
You can use methods of Date object for build your date string:

```<code>const now = new Date();

const formattedDate = now.getDate() + "." + ('0' + (now.getMonth()+1)).slice(-2) + "." + now.getFullYear();

const formattedDateTime = formattedDate + " " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();

console.log(formattedDate); // 28.05.2019

console.log(formattedDateTime); // 28.05.2019 13:19:43
</code>```

Title: Javascript (ES6) Date to String format

Body:
You can use methods of Date object for build your date string:

const now = new Date();

const formattedDate = now.getDate() + "." + ('0' + (now.getMonth()+1)).slice(-2) + "." + now.getFullYear();

const formattedDateTime = formattedDate + " " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();

console.log(formattedDate); // 28.05.2019

console.log(formattedDateTime); // 28.05.2019 13:19:43


问:
Single source pushing: how to send 5kb each 5 minutes to 50000 clients
I need to implement a client server architecture where the server sends
the same message to many clients over the internet.
I need to send a single message every 5 minutes about.
The message won't excede 5KB.
I need the solution to scale to a big number of clients connected (50.000-100.000)

I considered a bunch of solutions:

TCP Sockets

UDP Multicast

WCF http duplex service (comet)

I think I have to discard UDP solution because it is a good solution only for clients on the same network and it won't work over the internet.
I read somewhere that WCF multicast will cause a bottleneck if I have many clients connected but I can't find anywhere documentation showing performance statistics.
Tcp sockets seems to me the solution to chose.
What do you think about? Am I correct?

I'm certainly wrong when I say UDP doesn't work on internet... I thought
this because I read some articles pointing out that you need properly
configured routers in the network to support multicasting... I read of the
udp ports multicast range and thought it was meant to be locally.
Instead, the range 224.0.0.1 - 239.255.255.255 (Class D address group), can be reached over the internet

Considering that in my case reliability is not a crucial point, the udp multicast is a good choice.
The .net framework offers really helpful classes to accomplish this.
I can easily start an UdpClient and begin send data on a multicast address with two lines of code.
At client side it is really easy to.
There is the UdpSingleSourceMulticastClient class that does exactly what I need.
For what concernes reliability and security the .net framework has a smart and simple way of handle DoS attacks, DNS Rebinding attacks and Revers tunnel attacks that is described here: http://msdn.microsoft.com/en-us/library/ee707325(v=vs.95).aspx

答:
The main question is: Do you care if the updates get to the clients?

If you DO then you will need to build something on top of UDP to add reliability. UDP datagrams are NOT reliable and so you should expect that some wont get to the destination. This is more likely if you are pushing UDP datagrams out quickly. Note that your clients might also get multiple copies of the same datagram in some situations with UDP.

50-100k connections with this level of traffic shouldn't be that difficult to achieve with TCP if you have a decent architecture.

See here for some blog posts that I've done on the subject.

http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-concurrent-tcp-connections.html

http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections---part-2---perf-tests-from-day-0.html

http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html

And here's some example code that deals with sending data to many clients.

http://www.serverframework.com/ServerFramework/latest/Docs/examples-datadistributionservers.html


问:
Build pipes with multiple async HTTP requests
I need to make first HTTP request and get from response array of object.
Then I need to make HTTP request for every object in array (probably in loop) to get extra info. All this inside Angular. I try with pipes but have some difficulties.</p>

答:
Basically you would use a mergeMap/flatMap for a nested api call by pulling the value out of the inner Observable and passing it back to the parent stream.

Like in the example in below answer if you had to make a nested call for fetching a User and then his preferences, you would use flatmap like below.

```<code>ngOnInit() {
    this.userService.getUser().pipe(
        tap(u => this.user = u),
        flatMap(u => this.userService.getPreferences(u.username))
      ).subscribe(p => this.preferences = p);
}
</code>```

How to make nested Observable calls in Angular2

Body:
Basically you would use a mergeMap/flatMap for a nested api call by pulling the value out of the inner Observable and passing it back to the parent stream.

Like in the example in below answer if you had to make a nested call for fetching a User and then his preferences, you would use flatmap like below.

ngOnInit() {
    this.userService.getUser().pipe(
        tap(u => this.user = u),
        flatMap(u => this.userService.getPreferences(u.username))
      ).subscribe(p => this.preferences = p);
}

How to make nested Observable calls in Angular2


问:
How to know the size of a widget before painting it?
I’m trying to use an AnimatedContainer for just a simple animation of an expand effect (similar to ExpandableTile) when the user press it.

My issue is that this container, when expanded, can have either 10.0 height, or 1000.0 (it must be dynamic). Ok, to animate it, it needs to know the height before-hand, makes sense. But how would I know the max height of something before rendering it (I’m going to render Text which can have 1 to N lines)).

I’ve think in a lot of possibilities, but none seem to fit. Most of the times we get the size from something that is already rendered, from the RenderBox, not the opposite, so this is kind bugging me.

Thank you in advance!

答:
I end up finding the solution by using the Offstage widget which fits perfectly in this scenario.

Solution

Wrapping the subtree in a Offstage and assigning it a key (can be a GlobalKey), then, before actually rendering it, I can get its height by doing:

```<code>  void _getWidgetHeight() {
    if (subtreeHeight == null) {
      RenderBox renderBox = key.currentContext.findRenderObject();
      subtreeHeight = renderBox.size.height;
    }
    setState(() {
      _isOffstage = false;
    });
  }
</code>```

this way, if you have an AnimatedContainer, for example, and need to animate to its final size, you can have the following:

```<code>AnimatedContainer(
        duration: Duration(milliseconds: 250),
        height: subtreeHeight ?? 100.0 // some default size,
      ...
  )
</code>```

and it will render accordingly.

As a note, make sure the content in your subtree can be inserted inside the Container while it is animating (eg. wrapping the Offstage in a Flexible if you´re using it in a Column or Row).

Body:
I end up finding the solution by using the Offstage widget which fits perfectly in this scenario.

Solution

Wrapping the subtree in a Offstage and assigning it a key (can be a GlobalKey), then, before actually rendering it, I can get its height by doing:

  void _getWidgetHeight() {
    if (subtreeHeight == null) {
      RenderBox renderBox = key.currentContext.findRenderObject();
      subtreeHeight = renderBox.size.height;
    }
    setState(() {
      _isOffstage = false;
    });
  }

this way, if you have an AnimatedContainer, for example, and need to animate to its final size, you can have the following:

AnimatedContainer(
        duration: Duration(milliseconds: 250),
        height: subtreeHeight ?? 100.0 // some default size,
      ...
  )

and it will render accordingly.

As a note, make sure the content in your subtree can be inserted inside the Container while it is animating (eg. wrapping the Offstage in a Flexible if you´re using it in a Column or Row).


问:
How to access outputs from a "each cloud service is a folder" approach in Terraform
So, I have a terraform folder structure as follows:

```<code>environments
  staging
    gke
        main.tf
        terraform.tfvars
        variables.tf
    vpc
        main.tf
        terraform.tfvars
        variables.tf
    secrets.tfvars (non-versioned)
    globals.tfvars
    terraform.tfvars (terragrunt helps require secrets and globals)
modules
    vpc
        main.tf
        outputs.tf
    gke
        main.tf
        outputs.tf
</code>```

The problem I have is that I don't know how to access for example the VPC module self link that I am setting as output, from the GKE module.

Every example I see has like a main.tf on the "staging" level where every module is called in the same file, so that way they can access modules output, but I don't have one (should I with my folder structure approach?)

Would by solution grab the value from remote state? I was trying to access it but it always says it doesn't find the resource:

```<code>  // Define VPC
  network = "${data.terraform_remote_state.vpc.main_vpc_self_link}"
</code>```

I try to access like that this output I have in my VPC module (the module is called vpc)

```<code>// Self link to the VPC
output "main_vpc_self_link" {
  value = "${google_compute_network.main_vpc_network.self_link}"
}
</code>```

答:
You need to pass the output value as a variable inside the module you want to access:

```<code>module "my_vpc":
  ....

module "gke":
    source = "./modules/gke
    vpc_id = module.my_vpc.id
</code>```

On your gke module, you will need to have a vpc_id variable to receive it.

Body:
So, I have a terraform folder structure as follows:

environments
  staging
    gke
        main.tf
        terraform.tfvars
        variables.tf
    vpc
        main.tf
        terraform.tfvars
        variables.tf
    secrets.tfvars (non-versioned)
    globals.tfvars
    terraform.tfvars (terragrunt helps require secrets and globals)
modules
    vpc
        main.tf
        outputs.tf
    gke
        main.tf
        outputs.tf

The problem I have is that I don't know how to access for example the VPC module self link that I am setting as output, from the GKE module.

Every example I see has like a main.tf on the "staging" level where every module is called in the same file, so that way they can access modules output, but I don't have one (should I with my folder structure approach?)

Would by solution grab the value from remote state? I was trying to access it but it always says it doesn't find the resource:

  // Define VPC
  network = "${data.terraform_remote_state.vpc.main_vpc_self_link}"

I try to access like that this output I have in my VPC module (the module is called vpc)

// Self link to the VPC
output "main_vpc_self_link" {
  value = "${google_compute_network.main_vpc_network.self_link}"
}

Body:
You need to pass the output value as a variable inside the module you want to access:

module "my_vpc":
  ....

module "gke":
    source = "./modules/gke
    vpc_id = module.my_vpc.id

On your gke module, you will need to have a vpc_id variable to receive it.


问:
PHPUnit fails with process isolation but passes without that flag
My tests are running properly and all green when I run them without any particular flag:

```<code>phpunit --configuration /home/vagrant/code/phpunit.xml /home/vagrant/code/tests
</code>```

When I enable process isolation, the tests are failing:

```<code>phpunit --configuration /home/vagrant/code/phpunit.xml /home/vagrant/code/tests --process-isolation
</code>```

The error looks like this:

```<code>PHP Fatal error:  Uncaught RuntimeException: A facade root has not been set. in /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:234
Stack trace:
#0 /home/vagrant/code/routes/web.php(6): Illuminate\Support\Facades\Facade::__callStatic('get', Array)
#1 Standard input code(1653): require_once('/home/vagrant/c...')
#2 {main}
  thrown in /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 234
Fatal error: Uncaught RuntimeException: A facade root has not been set. in /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:234
Stack trace:
#0 /home/vagrant/code/routes/web.php(6): Illuminate\Support\Facades\Facade::__callStatic('get', Array)
#1 Standard input code(1653): require_once('/home/vagrant/c...')
#2 {main}
  thrown in /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 234
</code>```

I already tried a few things from the 3 or 4 threads I found on Laracast or StackOverflow regarding that kind of exception but nothing works yet:

Excluding routes from PHPUnit.xml

Running phpunit from vendor/bin or the one included in the system

etc.

Any idea about where to look for or check? I am running out of ideas.

Using latest Laravel 5.8 and PHPUnit 8.0.6

答:
I faced the same error. I fixed it by creating a new app container and then binding it to the Facade.

```<code>use \Illuminate\Container\Container as Container;
use \Illuminate\Support\Facades\Facade as Facade;

/**
* Setup a new app instance container
*
* @var Illuminate\Container\Container
*/
$app = new Container();
$app->singleton('app', 'Illuminate\Container\Container');

/**
* Set $app as FacadeApplication handler
*/
Facade::setFacadeApplication($app);
</code>```

in lumen: bootstrap/app.php

```<code>$app->withFacades();
</code>```

Body:
My tests are running properly and all green when I run them without any particular flag:

phpunit --configuration /home/vagrant/code/phpunit.xml /home/vagrant/code/tests

When I enable process isolation, the tests are failing:

phpunit --configuration /home/vagrant/code/phpunit.xml /home/vagrant/code/tests --process-isolation

The error looks like this:

PHP Fatal error:  Uncaught RuntimeException: A facade root has not been set. in /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:234
Stack trace:
#0 /home/vagrant/code/routes/web.php(6): Illuminate\Support\Facades\Facade::__callStatic('get', Array)
#1 Standard input code(1653): require_once('/home/vagrant/c...')
#2 {main}
  thrown in /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 234
Fatal error: Uncaught RuntimeException: A facade root has not been set. in /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:234
Stack trace:
#0 /home/vagrant/code/routes/web.php(6): Illuminate\Support\Facades\Facade::__callStatic('get', Array)
#1 Standard input code(1653): require_once('/home/vagrant/c...')
#2 {main}
  thrown in /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 234

I already tried a few things from the 3 or 4 threads I found on Laracast or StackOverflow regarding that kind of exception but nothing works yet:

Excluding routes from PHPUnit.xml

Running phpunit from vendor/bin or the one included in the system

etc.

Any idea about where to look for or check? I am running out of ideas.

Using latest Laravel 5.8 and PHPUnit 8.0.6

Body:
I faced the same error. I fixed it by creating a new app container and then binding it to the Facade.

use \Illuminate\Container\Container as Container;
use \Illuminate\Support\Facades\Facade as Facade;

/**
* Setup a new app instance container
*
* @var Illuminate\Container\Container
*/
$app = new Container();
$app->singleton('app', 'Illuminate\Container\Container');

/**
* Set $app as FacadeApplication handler
*/
Facade::setFacadeApplication($app);

in lumen: bootstrap/app.php

$app->withFacades();


问:
FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory
Error:

```<code><--- Last few GCs --->

[873:0x1020aa000]    47109 ms: Scavenge 2107.9 (2131.9) -> 2092.1 (2131.9) MB, 0.3 / 0.0 ms  (average mu = 0.995, current mu = 0.999) allocation failure
[873:0x1020aa000]    47231 ms: Scavenge 2107.9 (2131.9) -> 2092.1 (2131.9) MB, 0.2 / 0.0 ms  (average mu = 0.995, current mu = 0.999) allocation failure
[873:0x1020aa000]    47353 ms: Scavenge 2107.9 (2131.9) -> 2092.1 (2131.9) MB, 0.2 / 0.0 ms  (average mu = 0.995, current mu = 0.999) allocation failure

<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 0x27af028cfc7d]
Security context: 0x00a9d921d971 <JSObject>
    1: push [0xa9d9205831](this=0x00a92dc86431 <JSArray[112813858]>,0x00a9f2d5fdf1 <String[17]\: \n                >)
    2: /* anonymous */ [0xa92dc86471] [0x00a9bba025b1 <undefined>:~1] [pc=0x27af02959ff7](this=0x00a9051847e1 <JSGlobal Object>,0x00a92dc86531 <Object map = 0xa982312831>,0x00a9f2d4f6a9 <JSFunction exports.escapeXML (sfi = 0xa9f2d4edc9)>,0x00...

FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory
 1: 0x100060e87 node::Abort() [/usr/local/Cellar/node/11.10.1/bin/node]
 2: 0x1000614f5 node::OnFatalError(char const*, char const*) [/usr/local/Cellar/node/11.10.1/bin/node]
 3: 0x10017a687 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/usr/local/Cellar/node/11.10.1/bin/node]
 4: 0x10017a628 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/usr/local/Cellar/node/11.10.1/bin/node]
 5: 0x100437638 v8::internal::Heap::UpdateSurvivalStatistics(int) [/usr/local/Cellar/node/11.10.1/bin/node]
 6: 0x10041de6a v8::internal::Factory::AllocateRawFixedArray(int, v8::internal::PretenureFlag) [/usr/local/Cellar/node/11.10.1/bin/node]
 7: 0x10041d781 v8::internal::Factory::NewFixedArrayWithFiller(v8::internal::Heap::RootListIndex, int, v8::internal::Object*, v8::internal::PretenureFlag) [/usr/local/Cellar/node/11.10.1/bin/node]
 8: 0x1003dce56 v8::internal::(anonymous namespace)::ElementsAccessorBase<v8::internal::(anonymous namespace)::FastPackedObjectElementsAccessor, v8::internal::(anonymous namespace)::ElementsKindTraits<(v8::internal::ElementsKind)2> >::ConvertElementsWithCapacity(v8::internal::Handle<v8::internal::JSObject>, v8::internal::Handle<v8::internal::FixedArrayBase>, v8::internal::ElementsKind, unsigned int, unsigned int, unsigned int, int) [/usr/local/Cellar/node/11.10.1/bin/node]
 9: 0x1003dcd0c v8::internal::(anonymous namespace)::ElementsAccessorBase<v8::internal::(anonymous namespace)::FastPackedObjectElementsAccessor, v8::internal::(anonymous namespace)::ElementsKindTraits<(v8::internal::ElementsKind)2> >::GrowCapacityAndConvertImpl(v8::internal::Handle<v8::internal::JSObject>, unsigned int) [/usr/local/Cellar/node/11.10.1/bin/node]
10: 0x1003db82a v8::internal::(anonymous namespace)::ElementsAccessorBase<v8::internal::(anonymous namespace)::FastPackedObjectElementsAccessor, v8::internal::(anonymous namespace)::ElementsKindTraits<(v8::internal::ElementsKind)2> >::Add(v8::internal::Handle<v8::internal::JSObject>, unsigned int, v8::internal::Handle<v8::internal::Object>, v8::internal::PropertyAttributes, unsigned int) [/usr/local/Cellar/node/11.10.1/bin/node]
11: 0x1005068dc v8::internal::JSObject::AddDataElement(v8::internal::Handle<v8::internal::JSObject>, unsigned int, v8::internal::Handle<v8::internal::Object>, v8::internal::PropertyAttributes) [/usr/local/Cellar/node/11.10.1/bin/node]
12: 0x100505a38 v8::internal::Object::AddDataProperty(v8::internal::LookupIterator*, v8::internal::Handle<v8::internal::Object>, v8::internal::PropertyAttributes, v8::internal::ShouldThrow, v8::internal::Object::StoreFromKeyed) [/usr/local/Cellar/node/11.10.1/bin/node]
13: 0x10060fd43 v8::internal::Runtime::SetObjectProperty(v8::internal::Isolate*, v8::internal::Handle<v8::internal::Object>, v8::internal::Handle<v8::internal::Object>, v8::internal::Handle<v8::internal::Object>, v8::internal::LanguageMode) [/usr/local/Cellar/node/11.10.1/bin/node]
14: 0x100612c8c v8::internal::Runtime_SetProperty(int, v8::internal::Object**, v8::internal::Isolate*) [/usr/local/Cellar/node/11.10.1/bin/node]
15: 0x27af028cfc7d
[nodemon] app crashed - waiting for file changes before starting...
</code>```

I am getting this error every time I run my app.js file and click on a page, it tries to load for a minute without success and then crash. I know this question been asked before.

However, I have tried:

```<code>export NODE_OPTIONS=--max_old_space_size=4096
</code>```

I also tried:

```<code>node --max_old_space_size=4096 app.js
</code>```

and then run my app.js and problem still the same. I am not sure where my exported variables go, cannot find the .bashrc file anywhere etc. I am not even sure what's wrong, I am a bit new into coding.

答:
ANSWER:

I managed to solve it, I had an infinite loop working in the background as @alfasin suggested.

Body:
Error:

<--- Last few GCs --->

[873:0x1020aa000]    47109 ms: Scavenge 2107.9 (2131.9) -> 2092.1 (2131.9) MB, 0.3 / 0.0 ms  (average mu = 0.995, current mu = 0.999) allocation failure
[873:0x1020aa000]    47231 ms: Scavenge 2107.9 (2131.9) -> 2092.1 (2131.9) MB, 0.2 / 0.0 ms  (average mu = 0.995, current mu = 0.999) allocation failure
[873:0x1020aa000]    47353 ms: Scavenge 2107.9 (2131.9) -> 2092.1 (2131.9) MB, 0.2 / 0.0 ms  (average mu = 0.995, current mu = 0.999) allocation failure

<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 0x27af028cfc7d]
Security context: 0x00a9d921d971 <JSObject>
    1: push [0xa9d9205831](this=0x00a92dc86431 <JSArray[112813858]>,0x00a9f2d5fdf1 <String[17]\: \n                >)
    2: /* anonymous */ [0xa92dc86471] [0x00a9bba025b1 <undefined>:~1] [pc=0x27af02959ff7](this=0x00a9051847e1 <JSGlobal Object>,0x00a92dc86531 <Object map = 0xa982312831>,0x00a9f2d4f6a9 <JSFunction exports.escapeXML (sfi = 0xa9f2d4edc9)>,0x00...

FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory
 1: 0x100060e87 node::Abort() [/usr/local/Cellar/node/11.10.1/bin/node]
 2: 0x1000614f5 node::OnFatalError(char const*, char const*) [/usr/local/Cellar/node/11.10.1/bin/node]
 3: 0x10017a687 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/usr/local/Cellar/node/11.10.1/bin/node]
 4: 0x10017a628 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/usr/local/Cellar/node/11.10.1/bin/node]
 5: 0x100437638 v8::internal::Heap::UpdateSurvivalStatistics(int) [/usr/local/Cellar/node/11.10.1/bin/node]
 6: 0x10041de6a v8::internal::Factory::AllocateRawFixedArray(int, v8::internal::PretenureFlag) [/usr/local/Cellar/node/11.10.1/bin/node]
 7: 0x10041d781 v8::internal::Factory::NewFixedArrayWithFiller(v8::internal::Heap::RootListIndex, int, v8::internal::Object*, v8::internal::PretenureFlag) [/usr/local/Cellar/node/11.10.1/bin/node]
 8: 0x1003dce56 v8::internal::(anonymous namespace)::ElementsAccessorBase<v8::internal::(anonymous namespace)::FastPackedObjectElementsAccessor, v8::internal::(anonymous namespace)::ElementsKindTraits<(v8::internal::ElementsKind)2> >::ConvertElementsWithCapacity(v8::internal::Handle<v8::internal::JSObject>, v8::internal::Handle<v8::internal::FixedArrayBase>, v8::internal::ElementsKind, unsigned int, unsigned int, unsigned int, int) [/usr/local/Cellar/node/11.10.1/bin/node]
 9: 0x1003dcd0c v8::internal::(anonymous namespace)::ElementsAccessorBase<v8::internal::(anonymous namespace)::FastPackedObjectElementsAccessor, v8::internal::(anonymous namespace)::ElementsKindTraits<(v8::internal::ElementsKind)2> >::GrowCapacityAndConvertImpl(v8::internal::Handle<v8::internal::JSObject>, unsigned int) [/usr/local/Cellar/node/11.10.1/bin/node]
10: 0x1003db82a v8::internal::(anonymous namespace)::ElementsAccessorBase<v8::internal::(anonymous namespace)::FastPackedObjectElementsAccessor, v8::internal::(anonymous namespace)::ElementsKindTraits<(v8::internal::ElementsKind)2> >::Add(v8::internal::Handle<v8::internal::JSObject>, unsigned int, v8::internal::Handle<v8::internal::Object>, v8::internal::PropertyAttributes, unsigned int) [/usr/local/Cellar/node/11.10.1/bin/node]
11: 0x1005068dc v8::internal::JSObject::AddDataElement(v8::internal::Handle<v8::internal::JSObject>, unsigned int, v8::internal::Handle<v8::internal::Object>, v8::internal::PropertyAttributes) [/usr/local/Cellar/node/11.10.1/bin/node]
12: 0x100505a38 v8::internal::Object::AddDataProperty(v8::internal::LookupIterator*, v8::internal::Handle<v8::internal::Object>, v8::internal::PropertyAttributes, v8::internal::ShouldThrow, v8::internal::Object::StoreFromKeyed) [/usr/local/Cellar/node/11.10.1/bin/node]
13: 0x10060fd43 v8::internal::Runtime::SetObjectProperty(v8::internal::Isolate*, v8::internal::Handle<v8::internal::Object>, v8::internal::Handle<v8::internal::Object>, v8::internal::Handle<v8::internal::Object>, v8::internal::LanguageMode) [/usr/local/Cellar/node/11.10.1/bin/node]
14: 0x100612c8c v8::internal::Runtime_SetProperty(int, v8::internal::Object**, v8::internal::Isolate*) [/usr/local/Cellar/node/11.10.1/bin/node]
15: 0x27af028cfc7d
[nodemon] app crashed - waiting for file changes before starting...

I am getting this error every time I run my app.js file and click on a page, it tries to load for a minute without success and then crash. I know this question been asked before.

However, I have tried:

export NODE_OPTIONS=--max_old_space_size=4096

I also tried:

node --max_old_space_size=4096 app.js

and then run my app.js and problem still the same. I am not sure where my exported variables go, cannot find the .bashrc file anywhere etc. I am not even sure what's wrong, I am a bit new into coding.


问:
Is it possible to write a simple custom link that shows or hides all layers on a page?
I have a draw.io diagram page consisting of over 40 layers. But because I don't know which layers the user will have hidden/shown on the published diagram, I want to provide a button with an action set that hides all layers, then shows 3 specific layers.

Is it possible to hide all layers using a wildcard or similar, or do I need to manually create a huge (in manual management terms) layer id JSON array?

From what I can tell it's not possible, which surprises me, hence my asking. For my diagram it means I need to maintain huge JSON arrays in many links.

I've tried various custom links using cell and tag action wildcards, but my tests suggest tags only work for shapes (not layers), and cells includes both shapes AND layers.

```<code>data:action/json,{"actions":[{"hide":{"cells":["*"]}}]}
</code>```

I hoped using the above custom link would cause all layers to be hidden, which it did, but it also caused shapes on the currently selected layer to be hidden. It also caused shapes on the currently selected layer to appear deleted within the editor, so I needed to use the Undo feature to get the shapes back. I guess this is a bug, unless I'm doing something wrong or my drawing has become corrupt.

Something like this would be a really useful feature:

```<code>data:action/json,{"actions":[{"hide":{"layers":["*"]}}]}
</code>```

I would consider writing a plugin, but can't find any help documentation on the subject. Could someone advise on this?

答:
I worked around the problem of not being able to hide all layers on a page via wildcard by using tags.

It's possible to tag individual shapes, or by grouping shapes and adding the tags property at the group level. So long as a shape or group has a "tags" property in the "Edit Data" screen with a value in it, it's possible to hide all by using the following custom link:

```<code>data:action/json,{"actions":[{"hide":{"tags":[""]}}]}
</code>```

The same for showing all tags on a page:

```<code>data:action/json,{"actions":[{"show":{"tags":[""]}}]}
</code>```

To show everything on a page without using tags it's possible to just use:

```<code>data:action/json,{"actions":[{"show":{"cells":["*"]}}]}
</code>```

I also needed to add two buttons to an admin layer:

A "reset" button with "hide"/"show" custom link actions to reset the diagram to an initial state.

A "show all" button with "show" custom link actions to get all the shapes visible again, otherwise it wasn't possible to access them when editing the diagram.

Body:
I have a draw.io diagram page consisting of over 40 layers. But because I don't know which layers the user will have hidden/shown on the published diagram, I want to provide a button with an action set that hides all layers, then shows 3 specific layers.

Is it possible to hide all layers using a wildcard or similar, or do I need to manually create a huge (in manual management terms) layer id JSON array?

From what I can tell it's not possible, which surprises me, hence my asking. For my diagram it means I need to maintain huge JSON arrays in many links.

I've tried various custom links using cell and tag action wildcards, but my tests suggest tags only work for shapes (not layers), and cells includes both shapes AND layers.

data:action/json,{"actions":[{"hide":{"cells":["*"]}}]}

I hoped using the above custom link would cause all layers to be hidden, which it did, but it also caused shapes on the currently selected layer to be hidden. It also caused shapes on the currently selected layer to appear deleted within the editor, so I needed to use the Undo feature to get the shapes back. I guess this is a bug, unless I'm doing something wrong or my drawing has become corrupt.

Something like this would be a really useful feature:

data:action/json,{"actions":[{"hide":{"layers":["*"]}}]}

I would consider writing a plugin, but can't find any help documentation on the subject. Could someone advise on this?

Body:
I worked around the problem of not being able to hide all layers on a page via wildcard by using tags.

It's possible to tag individual shapes, or by grouping shapes and adding the tags property at the group level. So long as a shape or group has a "tags" property in the "Edit Data" screen with a value in it, it's possible to hide all by using the following custom link:

data:action/json,{"actions":[{"hide":{"tags":[""]}}]}

The same for showing all tags on a page:

data:action/json,{"actions":[{"show":{"tags":[""]}}]}

To show everything on a page without using tags it's possible to just use:

data:action/json,{"actions":[{"show":{"cells":["*"]}}]}

I also needed to add two buttons to an admin layer:

A "reset" button with "hide"/"show" custom link actions to reset the diagram to an initial state.

A "show all" button with "show" custom link actions to get all the shapes visible again, otherwise it wasn't possible to access them when editing the diagram.


问:
Preferred library and/or method of converting CMYK to RGB
Each month I get new CMYK and RGB images that shall be used on the web.

I had a script using a patched up ImageMagick doing this, but it got deleted. So I need to do it again, but it was hard last time.

How do you easily and quickly convert CMYK image files to RGB?

答:
convert cmyk_image.jpg -colorspace
  rgb rgb_image.jpg

OwnerDisplayName: Velmont


问:
Finding sum of top two columns and how much points they have?
Trying to find top 2 column with sum function.

Columns can be either 0 or 1 integer value.

Table can be seen as:

```<code>ID  C_ONE C_TWO C_THREE
1     1     1     0
2     0     1     1
3     1     1     0
4     0     0     0
5     1     1     0
</code>```

C_TWO column has 4 points and C_ONE column has 3 points which are the top 2 columns and their values respectively.

I have stucked with this codes.

```<code>SELECT COUNT(ID)
FROM MY_TABLE
ORDER BY SUM(C_ONE), SUM(C_TWO), SUM(C_THREE)
LIMIT 2
</code>```

答:
Well, you can unpivot and aggregate:</p>

```<code>select c.col,
       (case when c.col = 'col1' then t.col1
             when c.col = 'col2' then t.col2
             when c.col = 'col3' then t.col3
        end) as cnt
from (select sum(col1) as col1, sum(col2) as col2, sum(col3) as col3
      from t
     ) t cross join
     (select 'col1' as col union all
      select 'col2' as col union all
      select 'col3' as col
     ) c
order by cnt desc
limit 2;
</code>```

Body:
Trying to find top 2 column with sum function.

Columns can be either 0 or 1 integer value.

Table can be seen as:

ID  C_ONE C_TWO C_THREE
1     1     1     0
2     0     1     1
3     1     1     0
4     0     0     0
5     1     1     0

C_TWO column has 4 points and C_ONE column has 3 points which are the top 2 columns and their values respectively.

I have stucked with this codes.

SELECT COUNT(ID)
FROM MY_TABLE
ORDER BY SUM(C_ONE), SUM(C_TWO), SUM(C_THREE)
LIMIT 2

Body:
Well, you can unpivot and aggregate:

select c.col,
       (case when c.col = 'col1' then t.col1
             when c.col = 'col2' then t.col2
             when c.col = 'col3' then t.col3
        end) as cnt
from (select sum(col1) as col1, sum(col2) as col2, sum(col3) as col3
      from t
     ) t cross join
     (select 'col1' as col union all
      select 'col2' as col union all
      select 'col3' as col
     ) c
order by cnt desc
limit 2;


问:
iloc'ing one level of a multiindex
I have multiindex dataframe, something like:

```<code>df = pd.DataFrame(index = pd.MultiIndex.from_product([['mike', 'matt', 'dave', 'frank', 'larry'], range(10)]))
df['foo']="bar"
df.index.names=['people', 'socket']
</code>```

What I'd like to do is iloc-slice all the rows associated with the first three people in the index.  IE: retrieve all the rows where people is either matt mike or dave.

As far as I can tell, though, this is not at all supported by pandas. Saw some gross levels-related hacks, but they didn't even work.  get_level_values(0) doesn't give distinct level values,  and levels() returns an unsorted frozenset.

edit:  I should have said  that .loc-based solutions won't work for me.

答:
One idea is get first uniqe values of first level, indexing and select by loc:

```<code>df = df.loc[df.index.get_level_values(0).unique()[:3]]
</code>```

Detail:

```<code>print (df.index.get_level_values(0).unique()[:3])
Index(['mike', 'matt', 'dave'], dtype='object', name='people')
</code>```

Title: iloc'ing one level of a multiindex

Body:
I have multiindex dataframe, something like:

df = pd.DataFrame(index = pd.MultiIndex.from_product([['mike', 'matt', 'dave', 'frank', 'larry'], range(10)]))
df['foo']="bar"
df.index.names=['people', 'socket']

What I'd like to do is iloc-slice all the rows associated with the first three people in the index.  IE: retrieve all the rows where people is either matt mike or dave.

As far as I can tell, though, this is not at all supported by pandas. Saw some gross levels-related hacks, but they didn't even work.  get_level_values(0) doesn't give distinct level values,  and levels() returns an unsorted frozenset.

edit:  I should have said  that .loc-based solutions won't work for me.

Body:
One idea is get first uniqe values of first level, indexing and select by loc:

df = df.loc[df.index.get_level_values(0).unique()[:3]]

Detail:

print (df.index.get_level_values(0).unique()[:3])
Index(['mike', 'matt', 'dave'], dtype='object', name='people')


问:
Pure GWT, events converting
So, I have a ‘FlexTable’ in GWT and I need to drop down list of actions on right click on some cell. On left mouse click to retrieve ‘rowIndex’ of my cell I simply use ClickEvent method ‘getCellForEvent(event).getRowIndex()’. But there is no right click handler in pure GWT. So I decided to use ContextMenuHandler which requires ContextMenuEvent. And, of course, I can’t put ContextMenuEvent into ClickEvent method ‘getCellForEvent’. Is there any solution to this case? Or maybe someone knows easier way to drop down list on rightClick on ‘FlexTable’.</p>

答:
Actually you can use click handler to check what button was clicked, left, right or middle what you need to do is something like this :

Button button= new Button();
button.addClickHandler(event -> {
    NativeEvent nativeEvent = event.getNativeEvent();
    if(NativeEvent.BUTTON_RIGHT == nativeEvent.getButton()){
        event.stopPropagation();
        //do something
    }
});
```

Title: Pure GWT, events converting