问:
ReactJS Redux Api Fetch
I just need a little help with regards to fetching of data through an api

currently I have this code in my container

```<code>    fetchAll: () => {
        Promise.resolve(token.getToken()).then( (response) => {
            let obj = {
             token_type: response.data.token_type,
             access_token: response.data.access_token
            }

            apiFetch("http://dev.apiserver.com/api/all",{
              "method": "GET",
              "headers": {
                "Authorization": `${obj.token_type} ${obj.access_token}`,
                "userId": 1
              }
            })
            .then( (res) => {
                return res.json();
            }).then( (json) => {
                dispatch({
                    type: 'FETCH_ALL',
                    payload: json
                })
            }).catch(function(err) {
                console.log(err)
            })
        })
    }
</code>```

I'm calling the above function from componentWillMount(), I can successfully log the result in my console

here is my reducer code

```<code>    const allReducer = (state: Immut = initialState, action: { type: string, payload: any }) => {
        switch (action.type) {
          case FETCH_ALL:
            let newState = state
            let payload = action.payload

            newState = Immutable.fromJS(payload)
            console.log(newState)

            return newState
        }
    }
</code>```

the problem is that it doesn't update the state or re-render the components

答: You're dispatching type 'FETCH_ALL' and catching case FETCH_ALL. One is a variable and one is a string.

Title: ReactJS Redux Api Fetch

Body:
I just need a little help with regards to fetching of data through an api

currently I have this code in my container

    fetchAll: () => {
        Promise.resolve(token.getToken()).then( (response) => {
            let obj = {
             token_type: response.data.token_type,
             access_token: response.data.access_token
            }

            apiFetch("http://dev.apiserver.com/api/all",{
              "method": "GET",
              "headers": {
                "Authorization": `${obj.token_type} ${obj.access_token}`,
                "userId": 1
              }
            })
            .then( (res) => {
                return res.json();
            }).then( (json) => {
                dispatch({
                    type: 'FETCH_ALL',
                    payload: json
                })
            }).catch(function(err) {
                console.log(err)
            })
        })
    }

I'm calling the above function from componentWillMount(), I can successfully log the result in my console

here is my reducer code

    const allReducer = (state: Immut = initialState, action: { type: string, payload: any }) => {
        switch (action.type) {
          case FETCH_ALL:
            let newState = state
            let payload = action.payload

            newState = Immutable.fromJS(payload)
            console.log(newState)

            return newState
        }
    }

the problem is that it doesn't update the state or re-render the components


来源: stackexchange

问:
Generics in Swift
I am learning about Generics in Swift. For me, this topic is quite hard to understand. In the book I am reading, there is 2 challenges on Generics:

1st challenge: it asks to write a function findAll(_:_:) that takes and array of any type T that conforms to the Equatable protocol and a single element (also of type T). findAll(_:_:) should return an array of integers corresponding to every location where the element was found in the array. For example, findAll([5,3,7,3,9], 3] should return [1,3].

2nd challenge: to modify findAll(_:_:) to accept a Collection instead of an array and it gives a hint "You will need to change the return type from [Int] to an array of an associated type of the Collection protocol"

This is what i have done for first challenge

```<code>func findAll<T:Equatable> (_ first: [T], _ second: T) -> [Int] {
var array = [Int]()

for i in 0..<first.count {
    if first[i] == second {
        array.append(i)
        }
    }
return array
}
</code>```

For the second challenge, what i am thinking about is a generic function that I can pass a Collection (can be an Array, a Dictionary or a Set). But for Set type, as it does not have a defined ordering, how do you find location of an item in a Set?

Thank you.

答:
In order to create a custom definition of a function, you should create an extension on the type which the function belongs to. From there, the override tag must be used so that you can create a custom implementation for the function. More specifically, to create a function that accepts a collection instead of an array, create an overridden version of the function that accepts a collection instead.

Also please show us what you've tried so far, instead of just saying I've tried several things.

Here are some links that may be useful:

Swift Documentation

Override function

Another simple example of an override is whenever a ViewContoller class is made, the viewDidLoad() method where view setup happens in is often overridden.

ContentLicense: CC BY-SA 3.0

Title: Generics in Swift

Body:
I am learning about Generics in Swift. For me, this topic is quite hard to understand. In the book I am reading, there is 2 challenges on Generics:

1st challenge: it asks to write a function findAll(_:_:) that takes and array of any type T that conforms to the Equatable protocol and a single element (also of type T). findAll(_:_:) should return an array of integers corresponding to every location where the element was found in the array. For example, findAll([5,3,7,3,9], 3] should return [1,3].

2nd challenge: to modify findAll(_:_:) to accept a Collection instead of an array and it gives a hint "You will need to change the return type from [Int] to an array of an associated type of the Collection protocol"

This is what i have done for first challenge

func findAll<T:Equatable> (_ first: [T], _ second: T) -> [Int] {
var array = [Int]()

for i in 0..<first.count {
    if first[i] == second {
        array.append(i)
        }
    }
return array
}

For the second challenge, what i am thinking about is a generic function that I can pass a Collection (can be an Array, a Dictionary or a Set). But for Set type, as it does not have a defined ordering, how do you find location of an item in a Set?

Thank you.


问:
How can I use GCrypt within an Objective-C (Cocoa) app for Mac?
Hey,
I need to use the GCrypt library from within an XCode Objective-C project. I'm totally new to programming with such so apologies if this is a somewhat silly question.
Is this possible and, if so, how may I go about it?

Thanks,
Tim

答:
You can use C in Objective C directly, so you would access GCrypt as you would in regular C.

At the most basic level, include the libcrypt source in your project and then use

```<code>#include <gcrypt.h>
</code>```

In source files that you need to access the gcrypt api.

For some general info on using libraries in Xcode see this (Also includes a script called FrameworkMaker which can turn a generic library into a .framework file.)

ContentLicense: CC BY-SA 2.5

Body:
You can use C in Objective C directly, so you would access GCrypt as you would in regular C.

At the most basic level, include the libcrypt source in your project and then use

#include <gcrypt.h>

In source files that you need to access the gcrypt api.

For some general info on using libraries in Xcode see this (Also includes a script called FrameworkMaker which can turn a generic library into a .framework file.)


问:
WSO2 DAS. Vizualization event points on the map
I would like to test GEO map gadget using WSO2 DAS.
I have a stream with geo coordinates (e.g.: latitude=51.509865, longitude=-0.118092). My goal is to show points on the map in real time (real time datasource) using Geo Map chart type. I set only Id, latitude and longitude properties (default for others). In the result I see the map without points any points.
I cannot find detailed information and examples in documentation.
Is it possible or I have to use GPL - Siddhi Geo Extension?</p>

答:
As per the documentation

Download GPL feature as mentioned in the Prerequisites section.

As per the steps in the GPL feature installing documentation,

Start WSO2 DAS

Log into the DAS Management Console.

Click Configure in the side toolbar, and then click Features.

Click Repository Management, and then click Add Repository.

Enter the details as shown below to add the created P2 repository.

Click the Available Features tab.

In the Repository  parameter, select the  WSO2 GPL Feature Repository repository you previously added.

Remove the tick for "Group features by category" Click Find Features. Once all the features are listed, select the "GPL - Siddhi Geo Extension" feature and install.

Copy the two extension JAR files in the / samples/cep/utils/geo-dashboard-extensions/ directory to the  /repository/components/lib/ directory.

Navigate to the /repository/resources/geo-dashboard  directory and copy all the folders into the /repository/deployment/server directory.

Download GeoTools GIS toolkit

Copy the following client JAR files from downloaded  directory to /repository/components/lib/

gt-geojson-13.1.jar

gt-main-13.1.jar

gt-metadata-13.1.jar

jai_core-1.1.3.jar

jai_imageio-1.1.jar

Download JTS Topology Suite.

Copy jts-1.8.jar from /lib directory to both /repository/components/lib directory

Copy /samples/capp/org_wso2_carbon_geo_dashboard-1.0.0.car to /repository/deployment/server/carbonapps

Add <\Role>GeoDashboard</Role> to /repository/conf/carbon.xml under <\ServerRoles> parent tag

Add the Geo_DB datasource as mentioned in the 3rd step of prerequisites.

Restart the DAS server and you can access the dashboard via this url

You can then simulate some events through the simulator and see.

Click Tools in the side toolbar, and then click Simulator.

Add the following and send the event.

You will be able to see the sent information (Zoom out the map)

Best Regards,
Ramindu.


问:
VBA how to open a excel file and tell its creation date
I am trying to open a file from somewhere and also get the date when the opened file was created. However the line below gives me an error "Run Time Error, Automation error and Unspecified error". How can I fix this? Thanks.

MsgBox wb2.BuiltinDocumentProperties("Creation Date")

```<code>Private Sub CommandButton1_Click()

    Dim wb1 As Workbook, wb2 As Workbook
    Dim Ret1, Ret2
    Dim WS As Worksheet

    Set wb1 = ActiveWorkbook

    'Clear Summary tab
    wb1.Worksheets("Summary").Cells.Clear

    'Delete existing worksheet with name "Task List Data Export"
    For Each WS In Worksheets
    If WS.Name = "Task List Data Export" Then
        Application.DisplayAlerts = False
        Sheets("Task List Data Export").Delete
        Application.DisplayAlerts = True
        End
        End If
    Next

    'Get the File
    Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
    , "Please select file")
    If Ret1 = False Then Exit Sub

    'Copy file
    Set wb2 = Workbooks.Open(Ret1)

    MsgBox wb2.BuiltinDocumentProperties("Creation Date")

    wb2.Sheets(1).Select
    wb2.Sheets(1).Copy After:=wb1.Sheets(2)

    'Close opened file
    wb2.Close savechanges:=False
    Set wb2 = Nothing

    Worksheets("Cover").Activate

End Sub
</code>```

答:
If Microsoft Excel doesn’t define a value for one of the built-in document properties, reading the Value property for that document property causes an error.

From Workbook.BuiltinDocumentProperties Property

There is always a file created date and hence it is quite surprising that you are getting that error. I have never got this error. Even a newly created file which has not been saved gives you a "File Created Date and Time".

Here is an alternative.

```<code>Dim CtdDate As String
Dim fs As Object, f As Object

Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
                                   , "Please select file")

If Ret1 = False Then Exit Sub

Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(Ret1)

CtdDate = f.DateCreated

Set wb2 = Workbooks.Open(Ret1)

MsgBox CtdDate
</code>```

Body:
I am trying to open a file from somewhere and also get the date when the opened file was created. However the line below gives me an error "Run Time Error, Automation error and Unspecified error". How can I fix this? Thanks.

MsgBox wb2.BuiltinDocumentProperties("Creation Date")

Private Sub CommandButton1_Click()

    Dim wb1 As Workbook, wb2 As Workbook
    Dim Ret1, Ret2
    Dim WS As Worksheet

    Set wb1 = ActiveWorkbook

    'Clear Summary tab
    wb1.Worksheets("Summary").Cells.Clear

    'Delete existing worksheet with name "Task List Data Export"
    For Each WS In Worksheets
    If WS.Name = "Task List Data Export" Then
        Application.DisplayAlerts = False
        Sheets("Task List Data Export").Delete
        Application.DisplayAlerts = True
        End
        End If
    Next

    'Get the File
    Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
    , "Please select file")
    If Ret1 = False Then Exit Sub

    'Copy file
    Set wb2 = Workbooks.Open(Ret1)

    MsgBox wb2.BuiltinDocumentProperties("Creation Date")

    wb2.Sheets(1).Select
    wb2.Sheets(1).Copy After:=wb1.Sheets(2)

    'Close opened file
    wb2.Close savechanges:=False
    Set wb2 = Nothing

    Worksheets("Cover").Activate

End Sub

Body:
If Microsoft Excel doesn’t define a value for one of the built-in document properties, reading the Value property for that document property causes an error.

From Workbook.BuiltinDocumentProperties Property

There is always a file created date and hence it is quite surprising that you are getting that error. I have never got this error. Even a newly created file which has not been saved gives you a "File Created Date and Time".

Here is an alternative.

Dim CtdDate As String
Dim fs As Object, f As Object

Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
                                   , "Please select file")

If Ret1 = False Then Exit Sub

Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(Ret1)

CtdDate = f.DateCreated

Set wb2 = Workbooks.Open(Ret1)

MsgBox CtdDate


问:
Check if DataGridView Contains specific word
I'm currently doing a school project and I need to know how to check if in any row of the datagridview contains a specific word in any column, and hide the rows that don't contain that word, in any column.
I have no code yet, just the datagridview and the textbox on the form.</p>

答:
You need to iterate all the rows and cells,
and hide the row if your keyword found in a cell,

```<code>private void HideRow(string word)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
            var value = Convert.ToString(cell.Value);
            if (word != value)
            {
                row.Visible = false;
                break;
            }
        }
    }
}
</code>```

call this method wherever you want, on TextChanged Event or ButtonClick

Body:
You need to iterate all the rows and cells,
and hide the row if your keyword found in a cell,

private void HideRow(string word)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
            var value = Convert.ToString(cell.Value);
            if (word != value)
            {
                row.Visible = false;
                break;
            }
        }
    }
}

call this method wherever you want, on TextChanged Event or ButtonClick


问:
Sending an email by adding cc and to fields in codeigniter php
Hi in contact us i am sending mails to different ids by adding them in CC but while sending an email all the emails are displaying in "TO" option the mail ids which i have mentioned in CC it should display in CC only but it is combing with To email id.How to differentiate TO and CC emails.

```<code>function send_mails($email)
{
     $name = $this->input->post('fullname');
        $from_email = $this->input->post('email');
        $phone = $this->input->post('phone');
        $description = $this->input->post('text');
        $subject=$this->input->post('subject');

        //set to_email id to which you want to receive mails
        $to_email = 'example@gmail.com';

        $config=Array(
    'protocol'=> 'smtp',
    'smtp_host' => 'ssl://smtp.gmail.com', //smtp host name
    'smtp_port' => '465', //smtp port number
    'smtp_user' => 'XXX@gmail.com',
    'smtp_pass' => 'YYYY', //$from_email password
    'mailtype' =>'html',
    'newline'  =>"\r\n",
    'crlf' =>"\r\n",
    'charset' => 'iso-8859-1',
    'wordwrap' => TRUE
    );

    $message            = array();

$message[] = 'Username  :  '.trim($name).' ';
$message[] = 'Phone Number :  '.trim($phone).' ';
$message[] = 'Description :  '.trim($description).' ';
$message = implode(PHP_EOL, $message);
    //send mail
    $this->load->library('email',$config);
    $this->email->from($from_email);
    $this->email->to($to_email);
    $this->email->cc('info@gmail.com,xyz@gmail.com');
    $this->email->subject($subject);
    $this->email->message($message);
    $this->email->set_newline("\r\n");
            if ($this->email->send())
        {
           $this->flash->success('Thank you for contacting us we will get back to you soon!</div>');
            redirect('contact');
        }
        else
        {
            $this->flash->success('There is error in sending mail! Please try again later');
            redirect('contact');
        }
}
</code>```

Here in TO address there is only one Email id that should display in TO Field only.
And in CC there are two Email ids they both should display in cc.

答:
Try to use array while doing cc.

```<code>$this->load->library('email',$config);
$this->email->from($from_email);
$this->email->to($to_email);
$list = array('one@example.com', 'two@example.com', 'three@example.com');
$this->email->cc($list);
$this->email->subject($subject);
$this->email->message($message);
$this->email->set_newline("\r\n");
</code>```

Please try this and let me know if you have still the same error.

Body:
Hi in contact us i am sending mails to different ids by adding them in CC but while sending an email all the emails are displaying in "TO" option the mail ids which i have mentioned in CC it should display in CC only but it is combing with To email id.How to differentiate TO and CC emails.

function send_mails($email)
{
     $name = $this->input->post('fullname');
        $from_email = $this->input->post('email');
        $phone = $this->input->post('phone');
        $description = $this->input->post('text');
        $subject=$this->input->post('subject');

        //set to_email id to which you want to receive mails
        $to_email = 'example@gmail.com';

        $config=Array(
    'protocol'=> 'smtp',
    'smtp_host' => 'ssl://smtp.gmail.com', //smtp host name
    'smtp_port' => '465', //smtp port number
    'smtp_user' => 'XXX@gmail.com',
    'smtp_pass' => 'YYYY', //$from_email password
    'mailtype' =>'html',
    'newline'  =>"\r\n",
    'crlf' =>"\r\n",
    'charset' => 'iso-8859-1',
    'wordwrap' => TRUE
    );

    $message            = array();

$message[] = 'Username  :  '.trim($name).' ';
$message[] = 'Phone Number :  '.trim($phone).' ';
$message[] = 'Description :  '.trim($description).' ';
$message = implode(PHP_EOL, $message);
    //send mail
    $this->load->library('email',$config);
    $this->email->from($from_email);
    $this->email->to($to_email);
    $this->email->cc('info@gmail.com,xyz@gmail.com');
    $this->email->subject($subject);
    $this->email->message($message);
    $this->email->set_newline("\r\n");
            if ($this->email->send())
        {
           $this->flash->success('Thank you for contacting us we will get back to you soon!
');
            redirect('contact');
        }
        else
        {
            $this->flash->success('There is error in sending mail! Please try again later');
            redirect('contact');
        }
}

Here in TO address there is only one Email id that should display in TO Field only.
And in CC there are two Email ids they both should display in cc.

Body:
Try to use array while doing cc.

$this->load->library('email',$config);
$this->email->from($from_email);
$this->email->to($to_email);
$list = array('one@example.com', 'two@example.com', 'three@example.com');
$this->email->cc($list);
$this->email->subject($subject);
$this->email->message($message);
$this->email->set_newline("\r\n");

Please try this and let me know if you have still the same error.


问:
TortoiseSVN : Error running context: The server unexpectedly closed the connection when trying to create a branch/tag
I am trying to create a branch/tag from TortoiseSVN. After I click on OK, it transfers 0 Bytes/second and it takes around 15 mins and then comes back with an error

```<code>"Copy C:\MyRepository to https://example.com/svn/svn_repository/tags/release_1.0, Revision HEAD"
"Error running context: The server unexpectedly closed the connection"
"Completed"
</code>```

SVN version : 1.8.8, TortoiseSVN version : 1.9.4, SVN is setup with apache

I am able to SVN commit and update and do everything else in the repository except creating a release using branch/tag option.

apache error log :

```<code>[Fri Jun 09 06:58:37.301131 2017] [access_compat:error] [pid 29848] [client my_ip:61199] AH01797: client denied by server configuration: svn:path_to_my_repository_in_server

[Fri Jun 09 06:59:08.220708 2017] [access_compat:error] [pid 3480] [client my_ip:61375] AH01797: client denied by server configuration: svn:path_to_my_repository_in_server/tags/release_1.0
</code>```

Can anyone please help.

答: @Supersonic it looks like you don't have permission to create branch/tag on SVN, you just have read/write access on that branch/trunk.talk to your SVN administrator, ask to check SVN apache configuration.</p>

Body:
I am trying to create a branch/tag from TortoiseSVN. After I click on OK, it transfers 0 Bytes/second and it takes around 15 mins and then comes back with an error

"Copy C:\MyRepository to https://example.com/svn/svn_repository/tags/release_1.0, Revision HEAD"
"Error running context: The server unexpectedly closed the connection"
"Completed"

SVN version : 1.8.8, TortoiseSVN version : 1.9.4, SVN is setup with apache

I am able to SVN commit and update and do everything else in the repository except creating a release using branch/tag option.

apache error log :

[Fri Jun 09 06:58:37.301131 2017] [access_compat:error] [pid 29848] [client my_ip:61199] AH01797: client denied by server configuration: svn:path_to_my_repository_in_server

[Fri Jun 09 06:59:08.220708 2017] [access_compat:error] [pid 3480] [client my_ip:61375] AH01797: client denied by server configuration: svn:path_to_my_repository_in_server/tags/release_1.0

Can anyone please help.


问:
Best way to implement Video Chat with Django Backend?
So i'm trying to build a React Native with basic video chat functionality.

So far I have a Django backend and users can signin/signup/signout. Other than that, what's the best way to tackle this video chat? Thanks!

答:
You can use WebRTC for building video chat in React Native.

Find more details here
https://webrtchacks.com/reacting-to-react-native-for-native-webrtc-apps-alexey-aylarov/

https://github.com/oney/react-native-webrtc


问:
getting xml child in javascript
I'm trying to get to to the items child in XML using javascript.

The rss file is: Can i use dot syntax? item.title? I'mg etting undefined in the code below

<item>
<title><link>

$(document).ready(function(){     alert =
  console.log;

```<code>  var ns = {
</code>```

```<code>    init : function(){
        $.ajax({
            url: '/calendar/RSSSyndicator.aspx?type=N&number=15&category=8-0%2c4-0%2c6-0%2c10-0%2c7-0%2c17-0%2c16-0%2c9-0%2c5-0%2c3-0%2c2-0&department=3&numdays=31&ics=Y&rsstitle=Annandale+-+Event+Listing&rssid=11',
            success: this.loaded
        });
    },

    loaded: function(data){
        // Get access to the events id in the DOM
        var events = document.getElementById('events');

        // Get item from the RSS document
        var items = data.getElementsByTagName('item');
    alert('test');

    }

}

ns.init();
</code>```

});

答:
No, unless you're using E4X you can't use dot notation to navigate an XML DOM in JavaScript. You'll have to use standard DOM: getElementsByTagName("title"), childNodes etc.

E4X does let you navigate XML as though it were a JavaScript object tree, but of the main browsers it is only supported in Firefox.

Title: getting xml child in javascript

Body:
I'm trying to get to to the items child in XML using javascript.

The rss file is: Can i use dot syntax? item.title? I'mg etting undefined in the code below

<item>
<title><link>

$(document).ready(function(){     alert =
  console.log;

  var ns = {

    init : function(){
        $.ajax({
            url: '/calendar/RSSSyndicator.aspx?type=N&number=15&category=8-0%2c4-0%2c6-0%2c10-0%2c7-0%2c17-0%2c16-0%2c9-0%2c5-0%2c3-0%2c2-0&department=3&numdays=31&ics=Y&rsstitle=Annandale+-+Event+Listing&rssid=11',
            success: this.loaded
        });
    },

    loaded: function(data){
        // Get access to the events id in the DOM
        var events = document.getElementById('events');

        // Get item from the RSS document
        var items = data.getElementsByTagName('item');
    alert('test');

    }

}

ns.init();

});


问:
Unable to change the font family in GXT text Area
I am not able to change the default font family of GXT Text Area. I have tried using StyleInjector and CSS. But it is not getting updated. Can you please help me?

```<code>TextArea textArea = new TextArea();
textArea.setStyleName("gxtTextArea");
</code>```

And in the CSS file, I have given as,

```<code>.gxtTextArea {
    font-family: Arial !important;
    /* color: red !important;
    font-size: 24px !important;
    font-style: bold !important;
    font-weight: bold !important; */
}
</code>```

答:
You can also use addStyleName instead of setStyleName.

```<code>TextArea textArea = new TextArea();
textArea.addStyleName("gxtTextArea");
</code>```

And in the CSS side, change it as below.

```<code>.gxtTextArea * {
    font-family: Arial !important;
    /* color: red !important;
    font-size: 24px !important;
    font-style: bold !important;
    font-weight: bold !important; */
 }
</code>```

Body:
I am not able to change the default font family of GXT Text Area. I have tried using StyleInjector and CSS. But it is not getting updated. Can you please help me?

TextArea textArea = new TextArea();
textArea.setStyleName("gxtTextArea");

And in the CSS file, I have given as,

.gxtTextArea {
    font-family: Arial !important;
    /* color: red !important;
    font-size: 24px !important;
    font-style: bold !important;
    font-weight: bold !important; */
}

Body:
You can also use addStyleName instead of setStyleName.

TextArea textArea = new TextArea();
textArea.addStyleName("gxtTextArea");

And in the CSS side, change it as below.

.gxtTextArea * {
    font-family: Arial !important;
    /* color: red !important;
    font-size: 24px !important;
    font-style: bold !important;
    font-weight: bold !important; */
 }


问:
Is it possible to change BackgroundColor of snackbar for ios?
My app uses a snackbar of material-components-ios. I want to change BackgroundColor to blue, but I can't.

So is it possible to change the background color of snackbar?

答:
You have to hack it. :)

In your pods there is a file called.

MDCSnackbarMessageView.m

there is  function like this. I changed the value already to blue. And it will take hex value color code.

```<code>- (UIColor *)snackbarBackgroundColor {
   // return MDCRGBAColor(0x32, 0x32, 0x32, 1.0f); //previous grey color
    return MDCRGBAColor(0x10, 0x3F, 0xFF, 1.0f);// blue color
}
</code>```

Now do, clean and build again. Here is the output.

Body:
You have to hack it. :)

In your pods there is a file called.

MDCSnackbarMessageView.m

there is  function like this. I changed the value already to blue. And it will take hex value color code.

- (UIColor *)snackbarBackgroundColor {
   // return MDCRGBAColor(0x32, 0x32, 0x32, 1.0f); //previous grey color
    return MDCRGBAColor(0x10, 0x3F, 0xFF, 1.0f);// blue color
}

Now do, clean and build again. Here is the output.


问:
MySQL 5.6 not starting in Ubuntu 16.04
I am unable to start the MySQL server. In the "StartUp/Stutdown" page of MySQL Workbench, initially Start Server button is enabled. When i click on it, a pop up with the following error is seen, "Unhandled exception: TextBox_append_text_with_encoding() takes exactly 3 arguments (4 given)".</p>

答:
It is a post installation/upgrade issue.

Its a known bug reported at https://bugs.mysql.com/bug.php?id=85807

You can temporarily use solution provided at https://askubuntu.com/a/762775/458468

Title: MySQL 5.6 not starting in Ubuntu 16.04


问:
scala how to reduce while n > 0
I am wondering if there's a way to deal with a while (n > 0) loop in a more functional way, I have a small Scala app that counts the number of digits equal to K from a range from 1 to N:
for example 30 and 3 would return 4 [3, 13, 23, 30]

```<code>object NumKCount {

  def main(args: Array[String]): Unit = {
    println(countK(30,3))
  }

  def countKDigit(n:Int, k:Int):Int = {
      var num = n
      var count = 0
      while (num > 10) {
        val digit = num % 10
        if (digit == k) {count += 1}
        num = num / 10
      }
      if (num == k) {count += 1}
      count
  }

  def countK(n:Int, k:Int):Int = {
    1.to(n).foldLeft(0)((acc, x) => acc + countKDigit(x, k))
  }
}
</code>```

I'm looking for a way to define the function countKDigit using a purely functional approach

答:
Assuming that K is always 1 digit, you can convert n to String and use collect or filter, like below (there's not much functional stuff you can do with Integer):

```<code>def countKDigit(n: Int, k: Int): Int = {
  n.toString.collect({ case c if c.asDigit == k => true }).size
}
</code>```

or

```<code>def countKDigit(n: Int, k: Int): Int = {
  n.toString.filter(c => c.asDigit == 3).length
}
</code>```

E.g.

```<code>scala> 343.toString.collect({ case c if c.asDigit == 3 => true }).size
res18: Int = 2

scala> 343.toString.filter(c => c.asDigit == 3).length
res22: Int = 2
</code>```

Title: scala how to reduce while n > 0

Body:
I am wondering if there's a way to deal with a while (n > 0) loop in a more functional way, I have a small Scala app that counts the number of digits equal to K from a range from 1 to N:
for example 30 and 3 would return 4 [3, 13, 23, 30]

object NumKCount {

  def main(args: Array[String]): Unit = {
    println(countK(30,3))
  }

  def countKDigit(n:Int, k:Int):Int = {
      var num = n
      var count = 0
      while (num > 10) {
        val digit = num % 10
        if (digit == k) {count += 1}
        num = num / 10
      }
      if (num == k) {count += 1}
      count
  }

  def countK(n:Int, k:Int):Int = {
    1.to(n).foldLeft(0)((acc, x) => acc + countKDigit(x, k))
  }
}

I'm looking for a way to define the function countKDigit using a purely functional approach

Body:
Assuming that K is always 1 digit, you can convert n to String and use collect or filter, like below (there's not much functional stuff you can do with Integer):

def countKDigit(n: Int, k: Int): Int = {
  n.toString.collect({ case c if c.asDigit == k => true }).size
}

or

def countKDigit(n: Int, k: Int): Int = {
  n.toString.filter(c => c.asDigit == 3).length
}

E.g.

scala> 343.toString.collect({ case c if c.asDigit == 3 => true }).size
res18: Int = 2

scala> 343.toString.filter(c => c.asDigit == 3).length
res22: Int = 2


问:
PHP date range problems
Today I am having a rather strange problem with my date range.

```<code>$oBeginDate = newDateTime('last wednesday');
$oEndDate = newDateTime('next tuesday');
echo $oBeginDate->format('d/m/Y') . ' to ' . $oEndDate->format('d/m/Y');
</code>```

This should usually display 14/12/2010 to 21/12/2010, but today, 14/12/2010, it is displaying 08/12/2010 to 21/12/2010.

Any suggestions as to how I can fix this problem?

I would like the date to update from 08/12/2010 to 14/12/2010 automatically to keep the one week range.

答: Today, December 14th, is a Tuesday. So last Wednesday is indeed December 8th.</p>

Title: PHP date range problems

Body:
Today I am having a rather strange problem with my date range.

$oBeginDate = newDateTime('last wednesday');
$oEndDate = newDateTime('next tuesday');
echo $oBeginDate->format('d/m/Y') . ' to ' . $oEndDate->format('d/m/Y');

This should usually display 14/12/2010 to 21/12/2010, but today, 14/12/2010, it is displaying 08/12/2010 to 21/12/2010.

Any suggestions as to how I can fix this problem?

I would like the date to update from 08/12/2010 to 14/12/2010 automatically to keep the one week range.


问:
Not sure why I am getting this error, I have an idea but am not sure how to fix it
This is for a project that I am working on. I am trying to model an intrusive dike of magma cooling in some host or country rock within the earths crust. I am fairly new to coding. I did my best to convert this code form another coding language to python. I have a basic idea of what is going on. I know that I am trying to index something out of range, but am not sure where and or how to fix it. Any help I could get would be greatly appreciated! Thanks in advance.

```<code>import numpy as np
import matplotlib.pyplot as plt

#Physical parameters
L = 100 #Length of modeled domain [m]
Tmagma = 1200 #Temp. magma [°C]
Trock = 300 #Temp. of country rock [°C]
kappa = 1e-6 #Thermal diffusivity of rock [m^2/s]
W = 5 #Width of dike [m]
day = 3600*24 #seconds per day
dt = 1*day #Timestep
print(kappa)
print(day)
print(dt)

#Numerical parameters
nx = 201 #Number of gridpoints in x-direction
nt = 500 #Number of timesteps to compute
dx = L/(nx-1) #Spacing of grid
x = np.linspace(-50,50,100) #Grid
print(dx)
print(x)

#Setup initial temp. profile
T = np.ones(np.shape(x))*Trock
T[x>=-W/2] = 1200
T[x>=W/2] = 300
print(T)

time = 0
for n in range(0,nt): #Timestep loop
    #compute new temp.
    Tnew = np.zeros((1,nx))
    print(Tnew)
    for i in range(2,nx-1):
        Tnew[i] = T[i]+kappa*dt*((T[i+1]-2*T[i]+T[i-1])/(dt**2))             # Set BC's
    Tnew[1] = T[1]
    Tnew[nx] = T[nx]

    #update temp. and time
    T = Tnew
    time = time+dt

    #Plot solution
    plt.figure()
    plt.plot(x,Tnew)
    plt.xlabel('x [m]')
    plt.ylabel('Temerpature [°C]')
    plt.legend()
    surf = ax.plot_surface(X, Y, cmap=cm.coolwarm, linewidth=0, antialiased=False)
    fig.colorbar(surf, shrink=0.5, aspect=5)
    plt.show()
</code>```

```<code>IndexError                                Traceback (most recent call last)
<ipython-input-51-e80d6234a5b4> in <module>()
     37     print(Tnew)
     38     for i in range(2,nx-1):
---> 39         Tnew[i] = T[i]+kappa*dt*((T[i+1]-2*T[i]+T[i-1])/(dt**2))
     40
     41     # Set BC's

IndexError: index 2 is out of bounds for axis 0 with size
</code>```

答:
The shape you gave Tnew is (1,nx), i.e. it's a 1-by-nx 2D array.

If you only want a 1D array, set Tnew = np.zeros(nx) instead. Or if you want to keep it 2D, access it at Tnew[0,i].

Body:
This is for a project that I am working on. I am trying to model an intrusive dike of magma cooling in some host or country rock within the earths crust. I am fairly new to coding. I did my best to convert this code form another coding language to python. I have a basic idea of what is going on. I know that I am trying to index something out of range, but am not sure where and or how to fix it. Any help I could get would be greatly appreciated! Thanks in advance.

import numpy as np
import matplotlib.pyplot as plt

#Physical parameters
L = 100 #Length of modeled domain [m]
Tmagma = 1200 #Temp. magma [°C]
Trock = 300 #Temp. of country rock [°C]
kappa = 1e-6 #Thermal diffusivity of rock [m^2/s]
W = 5 #Width of dike [m]
day = 3600*24 #seconds per day
dt = 1*day #Timestep
print(kappa)
print(day)
print(dt)

#Numerical parameters
nx = 201 #Number of gridpoints in x-direction
nt = 500 #Number of timesteps to compute
dx = L/(nx-1) #Spacing of grid
x = np.linspace(-50,50,100) #Grid
print(dx)
print(x)

#Setup initial temp. profile
T = np.ones(np.shape(x))*Trock
T[x>=-W/2] = 1200
T[x>=W/2] = 300
print(T)

time = 0
for n in range(0,nt): #Timestep loop
    #compute new temp.
    Tnew = np.zeros((1,nx))
    print(Tnew)
    for i in range(2,nx-1):
        Tnew[i] = T[i]+kappa*dt*((T[i+1]-2*T[i]+T[i-1])/(dt**2))             # Set BC's
    Tnew[1] = T[1]
    Tnew[nx] = T[nx]

    #update temp. and time
    T = Tnew
    time = time+dt

    #Plot solution
    plt.figure()
    plt.plot(x,Tnew)
    plt.xlabel('x [m]')
    plt.ylabel('Temerpature [°C]')
    plt.legend()
    surf = ax.plot_surface(X, Y, cmap=cm.coolwarm, linewidth=0, antialiased=False)
    fig.colorbar(surf, shrink=0.5, aspect=5)
    plt.show()

IndexError                                Traceback (most recent call last)
<ipython-input-51-e80d6234a5b4> in <module>()
     37     print(Tnew)
     38     for i in range(2,nx-1):
---> 39         Tnew[i] = T[i]+kappa*dt*((T[i+1]-2*T[i]+T[i-1])/(dt**2))
     40
     41     # Set BC's

IndexError: index 2 is out of bounds for axis 0 with size


问:
viewWillAppear equivalent for earlier version of OSX 10.10
life cycle methods (viewDidLoad, viewWillAppear, viewDidAppear etc) are available since OSX 10.10 Yosemite. Then how to used viewWillAppear in OSX 10.8,10.9 is there any other options for Lower version OS.</p>

答:
These lifecycle methods are used in NSViewController class. In order to achieve similar functionality you could use NSWindowController's windowDidLoad and windowWillLoad methods.

Keep in mind that you (if you use Apple's MVC) will also have to move all your view logic from NSViewControllers to NSWindowControllers since ViewControllers do not participate in the responder chain on APIs earlier than 10.10.


问:
I am creating a sample website. How do I check how it looks on mobile devices?
I have not launched the website yet. All the mobile testing websites I have found on the internet are asking for my URL. Is there any way to test a website that has not been launched yet?</p>

答:
My suggestion is to use Google Chrome and then inspect by right clicking on your webpage. Click on Responsive icon in the menu bar (shown in  attached image) and adjust screen size.

You need to write MEDIA QUERIES for making your page responsive for different screen sizes.


答:
Using the literals 'last wednesday' or 'next tuesday' returns a date relative to the current date time.

If you are attempting to get the range from today, the default parameter to the DateTime constructor is 'now' and will return the current date time.

Additionally a 'fixed' date in the future or the past would have to be declared explicitly.

If you are trying to get this week's date for that day, just pass the name explicitly.

```<code>    $startd = new DateTime('wednesday');

   $end_date = date_add($startd,date_interval_create_from_date_string('1 week'));
   echo $startd->format('d/m/Y').' to '.$endd->format('d/m/Y');
</code>```

To have the range update day to day without reference to day of week, use 'now' instead of 'wednesday'.

Title: PHP date range problems

Body:
Using the literals 'last wednesday' or 'next tuesday' returns a date relative to the current date time.

If you are attempting to get the range from today, the default parameter to the DateTime constructor is 'now' and will return the current date time.

Additionally a 'fixed' date in the future or the past would have to be declared explicitly.

If you are trying to get this week's date for that day, just pass the name explicitly.

    $startd = new DateTime('wednesday');

   $end_date = date_add($startd,date_interval_create_from_date_string('1 week'));
   echo $startd->format('d/m/Y').' to '.$endd->format('d/m/Y');

To have the range update day to day without reference to day of week, use 'now' instead of 'wednesday'.


问:
r shiny - upload all files from shinyDirChoose folder to server
I saved the path of a user-defined folder with shinyDirChoose. Now I want to upload files from that user's folder, but I cannot figure out how to do it.
1) All on the server end?
2) Feeding the file paths to fileInput somehow?

This is how I construct the file paths for the three files that should be uploaded.

```<code>### ui end, to browse to desired folder
ui = fluidPage(shinyDirButton('directory', 'Folder select', 'Please select a folder'))

### extracting the folder path
server = function(input, output, session) {
    volumes <- getVolumes()
    shinyDirChoose(input, 'directory', roots=volumes, session=session)
    path1 <- reactive({
       return(print(parseDirPath(volumes, input$directory)))
    })

### constructing the 3 file paths
datpat <- renderText({
    req(nchar(path1())>0)
    datpat <- paste0(path1(),"/data.csv")
  })
vispat <- renderText({
    req(nchar(path1())>0)
    vispat <- paste0(path1(),"/visit.csv")
  })
statpat <- renderText({
   req(nchar(path1())>0)
   statpat <- paste0(path1(),"/statvisit.csv")
})
</code>```

So now I have these paths, but how can I use them to upload the related content to the server? A simple read.csv unfortunately does not do the trick.

EDIT - but not there yet...

Working further with the great help @SBista provided, I think I'm approaching my goal, but see below code...

```<code>volumes <- getVolumes()
shinyDirChoose(input, 'directory', roots=volumes, session=session)
path1 <- reactive({
  return(print(parseDirPath(volumes, input$directory)))
})

observe({
  if(!is.null(path1)){
    ### vis1
    vis1 <- reactive({
      datpat <- paste0(path1(),"/visit.csv")
      vis <- read.csv(datpat, header = input$header, sep = input$sep, quote = input$quote,
                      stringsAsFactors = FALSE)
      vis
    })
    ### dataruw1
    dataruw1 <- reactive({
      datpat <- paste0(path1(),"/data.csv")
      dataruw <- read.csv(datpat, header = input$header, sep = input$sep, quote = input$quote,
                          stringsAsFactors = FALSE)
      dataruw
    })
  }
})
</code>```

Unfortunately, dataruw1 and vis1 do not seem to be generated, as I get a 'could not find function' error when trying to use the actual data with dataruw1() and vis1(). What am I missing? Any idea? Thanks a lot in advance!

答:
I have modified your app to demonstrate that you can use read.csv to upload the file. For demonstration I am reading only one file from the folder and displaying the read data frame in a datatable.

```<code>  library(shiny)
  library(shinyFiles)

  ### ui end, to browse to desired folder
  ui = fluidPage(shinyDirButton('directory', 'Folder select', 'Please select a folder'),
                 tableOutput(outputId = "datpat")
                 )

  ### extracting the folder path
  server = function(input, output, session) {
    volumes <- getVolumes()
    shinyDirChoose(input, 'directory', roots=volumes, session=session)
    path1 <- reactive({
      return(print(parseDirPath(volumes, input$directory)))
    })

    ### constructing the 3 file paths
    observe({
      if(!is.null(path1)){
        output$datpat <- renderTable({
          req(nchar(path1())>0)
          datpat <- paste0(path1(),"/data.csv")
          dat <- read.csv(datpat)
          dat
        })

      }
    })

  }

  shinyApp(ui = ui, server = server)
</code>```

Hope it helps!

Body:
I saved the path of a user-defined folder with shinyDirChoose. Now I want to upload files from that user's folder, but I cannot figure out how to do it.
1) All on the server end?
2) Feeding the file paths to fileInput somehow?

This is how I construct the file paths for the three files that should be uploaded.

### ui end, to browse to desired folder
ui = fluidPage(shinyDirButton('directory', 'Folder select', 'Please select a folder'))

### extracting the folder path
server = function(input, output, session) {
    volumes <- getVolumes()
    shinyDirChoose(input, 'directory', roots=volumes, session=session)
    path1 <- reactive({
       return(print(parseDirPath(volumes, input$directory)))
    })

### constructing the 3 file paths
datpat <- renderText({
    req(nchar(path1())>0)
    datpat <- paste0(path1(),"/data.csv")
  })
vispat <- renderText({
    req(nchar(path1())>0)
    vispat <- paste0(path1(),"/visit.csv")
  })
statpat <- renderText({
   req(nchar(path1())>0)
   statpat <- paste0(path1(),"/statvisit.csv")
})

So now I have these paths, but how can I use them to upload the related content to the server? A simple read.csv unfortunately does not do the trick.

EDIT - but not there yet...

Working further with the great help @SBista provided, I think I'm approaching my goal, but see below code...

volumes <- getVolumes()
shinyDirChoose(input, 'directory', roots=volumes, session=session)
path1 <- reactive({
  return(print(parseDirPath(volumes, input$directory)))
})

observe({
  if(!is.null(path1)){
    ### vis1
    vis1 <- reactive({
      datpat <- paste0(path1(),"/visit.csv")
      vis <- read.csv(datpat, header = input$header, sep = input$sep, quote = input$quote,
                      stringsAsFactors = FALSE)
      vis
    })
    ### dataruw1
    dataruw1 <- reactive({
      datpat <- paste0(path1(),"/data.csv")
      dataruw <- read.csv(datpat, header = input$header, sep = input$sep, quote = input$quote,
                          stringsAsFactors = FALSE)
      dataruw
    })
  }
})

Unfortunately, dataruw1 and vis1 do not seem to be generated, as I get a 'could not find function' error when trying to use the actual data with dataruw1() and vis1(). What am I missing? Any idea? Thanks a lot in advance!

Body:
I have modified your app to demonstrate that you can use read.csv to upload the file. For demonstration I am reading only one file from the folder and displaying the read data frame in a datatable.

  library(shiny)
  library(shinyFiles)

  ### ui end, to browse to desired folder
  ui = fluidPage(shinyDirButton('directory', 'Folder select', 'Please select a folder'),
                 tableOutput(outputId = "datpat")
                 )

  ### extracting the folder path
  server = function(input, output, session) {
    volumes <- getVolumes()
    shinyDirChoose(input, 'directory', roots=volumes, session=session)
    path1 <- reactive({
      return(print(parseDirPath(volumes, input$directory)))
    })

    ### constructing the 3 file paths
    observe({
      if(!is.null(path1)){
        output$datpat <- renderTable({
          req(nchar(path1())>0)
          datpat <- paste0(path1(),"/data.csv")
          dat <- read.csv(datpat)
          dat
        })

      }
    })

  }

  shinyApp(ui = ui, server = server)

Hope it helps!

ContentLicense: CC BY-SA 4.0


问:
Android stop specified IntentService
I've have develop an android application with an IntentService.

This IntentService does nothing more like a fileupload.

I just want to implement the functionality to upload multiple "file-upload-threads".

The problem is to stop one specified "file-upload-thread".

For example:

User choose ten files from the device and upload these.

A notification is created to gives the user "transfer-feedback".

While the thread is working the user can choose other files to upload.

Another notification is created but does not start until the first thread is done.

Is it possible to implement a "cancel-functionality" for the user to cancel the first thread and the second thread start automatically?!

Maybe is it better to user an Service instead of an IntentService?

答:
An IntentService is designed to stop itself only when all the requests present in the work queue have been handled.As per docs,IntentService class "Stops the service after all of the start requests are handled, so you never have to call stopSelf()

In case you want to cancel requests,you can probably use volley and cancel previous requests
https://developer.android.com/training/volley/simple.html#cancel

Title: Android stop specified IntentService


问:
Wordpress receiving a payload via a response url from third party API
I am sending & receiving JSON responses from a third party API, in one instance though they need to send a response to a url on my site ie: https://my-wordpress-site/api/confirm?transaction=T0efewgfweg78105 Can someone point me in the right direction on how to receive the payload from this response? The payload will be a JSON response like: “Status”: "Success" What script will I run on https://my-wordpress-site/api/confirm.php</p>

答:
If I understand the situation correctly
You can fetch this data with this snippet:

```<code>if(isset($_REQUEST['transaction']) && !empty($_REQUEST['transaction']))
{

$response_body = file_get_contents('php://input');
$data = json_decode($response_body);

}
</code>```

php://input is a read-only stream that allows you to read raw data from the request body

Body:
If I understand the situation correctly
You can fetch this data with this snippet:

if(isset($_REQUEST['transaction']) && !empty($_REQUEST['transaction']))
{

$response_body = file_get_contents('php://input');
$data = json_decode($response_body);

}

php://input is a read-only stream that allows you to read raw data from the request body


问:
How can I forward calls from a Twilio or Nexmo number I bought to my Android phone over data / VOIP?
I don't want to forward to my mobile number, I want to install some kind of "softphone" and have Twilio / Nexmo forward the call to that softphone. Can my Android phone receive VOIP calls directly somehow?

This seems like such a simple thing to do, but I can't figure out how to do it. Do I need my own "SIP trunk"? Surely not, for such a simple use-case.

答: If you don't want to forward to your personal number, you can buy some Virtual number from Application like Vyke, RWG. and give that number it will reach your app in your mobile.</p>


问:
How to add two numbers of any length in java?
How to add two numbers of any length in java?

Say for example, in java long size is 64 bit. So the maximum range is -9223372036854775808 to 9223372036854775807. Am i right?

So if we want to add a number which is greater than this like below, i got a error

" Integer Number too large"

long a = 9223372036854775807L;

  long b
  = 9223372036854775808L;

In C, we can take those numbers as char array, by traversing through the address of each char and use some data structure, we can add two numbers of any size.

How to do it java. Can we traverse through the address of each character in String.

Thanks for your responses.

I have tried to code by passing the numbers as string and add each character from the end. It works fine for me.

Is there any big difference between the addition of two very large numbers using BigInteger and the method, i specified above (add each character from end and store remainder in temporary variable and goes on).
Is the underlying mechanism of BigInteger is same as my code(add each character from end)?

Thanks.

答:
```<code>    import java.math.BigInteger;
    import java.util.Scanner;

    public class BigIntergerSumExample {

        public static void main(String args[]) {

            BigInteger number1;
            BigInteger number2;
            BigInteger sum;
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter the value of number 1");
            number1 = sc.nextBigInteger();
            System.out.println("Enter the value of number 2");
            number2 = sc.nextBigInteger();

            BigInteger a = new BigInteger(""+number1);
            BigInteger b = new BigInteger(""+number2);
            BigInteger result = a.add(b);

            System.out.println("Sum is Two numbers : -> " + result);
        }

    }

**OUTPUT IS**

Enter the value of number 1
1111111111111111111111111111111111111111111111111
Enter the value of number 2
2222222222222222222222222222222222222222222222222
Sum is Two numbers : ->
3333333333333333333333333333333333333333333333333
</code>```

import java.math.BigInteger will let you work with numbers of any size,

Body:
    import java.math.BigInteger;
    import java.util.Scanner;

    public class BigIntergerSumExample {

        public static void main(String args[]) {

            BigInteger number1;
            BigInteger number2;
            BigInteger sum;
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter the value of number 1");
            number1 = sc.nextBigInteger();
            System.out.println("Enter the value of number 2");
            number2 = sc.nextBigInteger();

            BigInteger a = new BigInteger(""+number1);
            BigInteger b = new BigInteger(""+number2);
            BigInteger result = a.add(b);

            System.out.println("Sum is Two numbers : -> " + result);
        }

    }

**OUTPUT IS**

Enter the value of number 1
1111111111111111111111111111111111111111111111111
Enter the value of number 2
2222222222222222222222222222222222222222222222222
Sum is Two numbers : ->
3333333333333333333333333333333333333333333333333

import java.math.BigInteger will let you work with numbers of any size,


问:
Why can I not create a ParentNode with multiple children?
I have the following html structure with A-Frame. Basically, I am constructing a 3D representation of an atom with the following basic html:\

```<code>  <a-scene>
    <a-entity id=#AtomComponent>

      <a-sphere id=#nucleus></a-sphere>

      <a-entity id=#electronShell>
        <a-sphere id=#electron></a-sphere>
      </a-entity>
    </a-entity>
  </a-scene>
</code>```

To dynamically create this I am using the following javascript:

```<code>let sceneEl = document.querySelector('a-scene'); #grab the main html component

# Create the individual components
let atomComponent = document.createElement('a-entity');

let nucleus = document.createElement('a-sphere');

let electronShell = document.createElement('a-entity');

let electron = document.createElement('a-sphere');

#Append them

sceneEl.appendChild(atomComponent);

atomComponent.appendChild(nucleus);

electronShell.appendChild(atomComponent);

electron.appendChild(electronShell);
</code>```

Maybe I'm tired but I believe that I am creating the html elements in the correct order. However when I try to execute this code I receive the following two errors:

```<code>material.js:170 Uncaught TypeError: Cannot read property 'dispose' of undefined

`Uncaught (in promise) TypeError: Cannot read property 'isPlaying' of null`
</code>```

Could someone double check that my html looks legitimate? AtomComponent should have two children (nucleus and electronShell) with electronShell having only one child. Since I'm new to A-Frame and rusty on javascript I can't decide if this is an AFrame level error or a JS selector error. Help would be appreciated.

答:
Use atomComponent.appendChild to append both nucleus and electronShell to have multiple childs

let sceneEl = document.querySelector('a-scene');

let atomComponent = document.createElement('a-entity');

let nucleus = document.createElement('a-sphere');

let electronShell = document.createElement('a-entity');

let electron = document.createElement('a-sphere');

sceneEl.appendChild(atomComponent);

atomComponent.appendChild(nucleus);

atomComponent.appendChild(electronShell);

electronShell.appendChild(electron);
console.log(document.querySelector('a-scene').outerHTML);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><a-scene>
</a-scene></code>```

Body:
I have the following html structure with A-Frame. Basically, I am constructing a 3D representation of an atom with the following basic html:\

To dynamically create this I am using the following javascript:

let sceneEl = document.querySelector('a-scene'); #grab the main html component

# Create the individual components
let atomComponent = document.createElement('a-entity');

let nucleus = document.createElement('a-sphere');

let electronShell = document.createElement('a-entity');

let electron = document.createElement('a-sphere');

#Append them

sceneEl.appendChild(atomComponent);

atomComponent.appendChild(nucleus);

electronShell.appendChild(atomComponent);

electron.appendChild(electronShell);

Maybe I'm tired but I believe that I am creating the html elements in the correct order. However when I try to execute this code I receive the following two errors:

material.js:170 Uncaught TypeError: Cannot read property 'dispose' of undefined

`Uncaught (in promise) TypeError: Cannot read property 'isPlaying' of null`

Could someone double check that my html looks legitimate? AtomComponent should have two children (nucleus and electronShell) with electronShell having only one child. Since I'm new to A-Frame and rusty on javascript I can't decide if this is an AFrame level error or a JS selector error. Help would be appreciated.

Body:
Use atomComponent.appendChild to append both nucleus and electronShell to have multiple childs

let sceneEl = document.querySelector('a-scene');

let atomComponent = document.createElement('a-entity');

let nucleus = document.createElement('a-sphere');

let electronShell = document.createElement('a-entity');

let electron = document.createElement('a-sphere');

sceneEl.appendChild(atomComponent);

atomComponent.appendChild(nucleus);

atomComponent.appendChild(electronShell);

electronShell.appendChild(electron);
console.log(document.querySelector('a-scene').outerHTML);

<a-scene>
</a-scene>


问:
displaying array items in tableview with swift
I cannot display elements of an array in a tableview by using swift programming language. I did some research but could not solve the problem. Below, you can see my code and download project as a .zip file from here: http://1drv.ms/1Ca2hyp

I can also give some videos. They're 11 min and 10 sec. long in total

```<code>import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var myTableView: UITableView!
    var cars = [String]()
    var newCar: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        cars = ["BMW","Audi", "Volkswagen"]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cars.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell

        cell.textLabel?.text = cars[indexPath.row]

        return cell
    }

}
</code>```

答:
```<code>    class SelectCategoryViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
        var CategeryArray = ["Food","Travel","Lifestyle","Card","MyReserve","Game","Songs","Movies","Entertainment","Business","Education","Finance","Drink","Sports","Social","Shopping"]

    override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
            self.tableView.dataSource = self
            self.tableView.delegate = self
        }
}
    extension SelectCategoryViewController: UITableViewDelegate,UITableViewDataSource {

        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return CategeryArray.count
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell")!
            cell.textLabel?.text = self.CategeryArray[indexPath.row]
            return cell
        }
    }
</code>```

set the identifier =TableViewCell in Main.storyboard

        And also set the class name for TableViewCell

Body:
I cannot display elements of an array in a tableview by using swift programming language. I did some research but could not solve the problem. Below, you can see my code and download project as a .zip file from here: http://1drv.ms/1Ca2hyp

I can also give some videos. They're 11 min and 10 sec. long in total

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var myTableView: UITableView!
    var cars = [String]()
    var newCar: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        cars = ["BMW","Audi", "Volkswagen"]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cars.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell

        cell.textLabel?.text = cars[indexPath.row]

        return cell
    }

}

Body:
    class SelectCategoryViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
        var CategeryArray = ["Food","Travel","Lifestyle","Card","MyReserve","Game","Songs","Movies","Entertainment","Business","Education","Finance","Drink","Sports","Social","Shopping"]

    override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
            self.tableView.dataSource = self
            self.tableView.delegate = self
        }
}
    extension SelectCategoryViewController: UITableViewDelegate,UITableViewDataSource {

        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return CategeryArray.count
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell")!
            cell.textLabel?.text = self.CategeryArray[indexPath.row]
            return cell
        }
    }

set the identifier =TableViewCell in Main.storyboard

        And also set the class name for TableViewCell


问:
Node - Converting file data to a Stream
I have a Node.js app. In that app, a user can upload a file.

```<code>const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

app.put('/files/upload', upload.single('myFile'), function(req, res) {
  let fileData = req.body['myFile'];
  if (fileData ) {
    let commaIndex = fileData.indexOf(',');
    if (commaIndex !== -1) {
      fileData = fileData.substr(commaIndex+1);

       // Convert file data to stream here...
    }
  }
});
</code>```

I'm trying to figure out how to convert the fileData to a stream. The reason I want a stream is because I'm trying to upload the file to Azure Storage. The API I'm trying to use ([createFileFromStream][1]) requires a stream.

Thank you!

答:
The function you would want to use is fs.createReadStream() which allows you to read a file to stream from the file path. And then you can use createWriteStreamToBlockBlob function to upload a stream to Azure Storage.

Example:

```<code>const express = require('express')
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })
const fs = require('fs')
const azure = require('azure-storage')

const app = express()

const accountName = "yourAccountName"
const accessKey = "yourAccessKey"
const blobSvc = azure.createBlobService(accountName, accessKey)

app.post('/files/upload', upload.single('myFile'), function(req, res) {
  fs.createReadStream(req.file.path).pipe(blobSvc.createWriteStreamToBlockBlob('mycontainer', req.file.originalname, function() {
    res.send('Upload completed!')
  }))

})
</code>```

Title: Node - Converting file data to a Stream

Body:
I have a Node.js app. In that app, a user can upload a file.

const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

app.put('/files/upload', upload.single('myFile'), function(req, res) {
  let fileData = req.body['myFile'];
  if (fileData ) {
    let commaIndex = fileData.indexOf(',');
    if (commaIndex !== -1) {
      fileData = fileData.substr(commaIndex+1);

       // Convert file data to stream here...
    }
  }
});

I'm trying to figure out how to convert the fileData to a stream. The reason I want a stream is because I'm trying to upload the file to Azure Storage. The API I'm trying to use ([createFileFromStream][1]) requires a stream.

Thank you!

Body:
The function you would want to use is fs.createReadStream() which allows you to read a file to stream from the file path. And then you can use createWriteStreamToBlockBlob function to upload a stream to Azure Storage.

Example:

const express = require('express')
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })
const fs = require('fs')
const azure = require('azure-storage')

const app = express()

const accountName = "yourAccountName"
const accessKey = "yourAccessKey"
const blobSvc = azure.createBlobService(accountName, accessKey)

app.post('/files/upload', upload.single('myFile'), function(req, res) {
  fs.createReadStream(req.file.path).pipe(blobSvc.createWriteStreamToBlockBlob('mycontainer', req.file.originalname, function() {
    res.send('Upload completed!')
  }))

})


问:
How can I compress images,so that google pagespeed test won't recommend to compress that image again?
Whenever I run pagespeed test , it gives possible optimization of images in bytes & percentage like,

  Compressing and resizing https://example.com/…ts/AMP.jpg?6750368613317441460 could save 530KiB (91% reduction).

Compressing https://example.com/…AMP.png?12287830358450898504 could save 4.4KiB (31% reduction).

I am using ImageMagick to compress the images.

I have tried  convert AMP.gif_or_png -strip  [-alpha Remove] OUTPUT.png  for png images  and

```<code> convert INPUT.jpg -sampling-factor 4:2:0 -strip [-quality 85] [-interlace JPEG] [-colorspace RGB] OUTPUT.jpg
</code>```

for jpg images, but none of the above commands gives me the same reduction as suggested by google pagespeed.
 So, let me know if i am missing any parameters or I have passed wrong values of parameters.

The pack of compressed contents are available on google pagespeed page but,I want to compress images using ImageMagick
 or any other sources .

答:
Compressing and resizing https://example.com/…ts/AMP.jpg?6750368613317441460 could save 530KiB (91% reduction).

530 KiB reduction is quite a lot. Verify that the image size is congruous. I mean, if you have a 400x200 image and you show it at 200x100, then serving it at the correct resolution (or resolutions) could be what PageSpeed is after.

For PNG images, often color reduction is possible: if you have a 12 colors image (e.g. a schematic), having it in 24-bit, 8-bit or 4-bit format makes a significant difference, while changing nothing in what people see once it's displayed. Good call removing unneeded alpha channel, though.

The rest you can do with tools like pngopt, pngcrush or advpng. JPEG quality parameter or suitable tools (tinyjpg, or google 'JPEG compression optimizer') can be used to improve JPEG size. There are some tools that are capable of selectively encoding different areas of the image, or rewrite a PNG palette to leverage zLib compression features.

Another possibility with JPEG is using the progressive format, that allows quickly displaying a raw image, and refine it iteratively. More overall bandwidth but also more apparent speed (less browser support also; check it out).

It is not automatic that any of this can be done with ImageMagick - after all, ImageMagick is not directly tasked with file manipulation but with image manipulation. It may well be that its file-compression functions are not as complete or as advanced as other tools'.

Body:
Whenever I run pagespeed test , it gives possible optimization of images in bytes & percentage like,

  Compressing and resizing https://example.com/…ts/AMP.jpg?6750368613317441460 could save 530KiB (91% reduction).

Compressing https://example.com/…AMP.png?12287830358450898504 could save 4.4KiB (31% reduction).

I am using ImageMagick to compress the images.

I have tried  convert AMP.gif_or_png -strip  [-alpha Remove] OUTPUT.png  for png images  and

 convert INPUT.jpg -sampling-factor 4:2:0 -strip [-quality 85] [-interlace JPEG] [-colorspace RGB] OUTPUT.jpg

for jpg images, but none of the above commands gives me the same reduction as suggested by google pagespeed.
 So, let me know if i am missing any parameters or I have passed wrong values of parameters.

The pack of compressed contents are available on google pagespeed page but,I want to compress images using ImageMagick
 or any other sources .


问:
Why the property SetVertexCount is not exist in LineRenderer?
```<code>using UnityEngine;
using UnityEditor;

public class DrawRectangle : MonoBehaviour
{
    LineRenderer line;
    void Start()
    {
        line = transform.GetComponent<LineRenderer>();
        line.SetVertexCount(5);
        line.SetPosition(0, new Vector3(-1, 1, 0));
        line.SetPosition(1, new Vector3(1, 1, 0));
        line.SetPosition(2, new Vector3(1, -1, 0));
        line.SetPosition(3, new Vector3(-1, -1, 0));
        line.SetPosition(4, new Vector3(-1, 1, 0));
    }
}
</code>```

The script is attached to a GameObject with LineRenderer component.
But I'm getting errors on all the line properties.
The SetVertexCount and all the SetPosition do not exist.

I'm using unity ver 5.5.1f1 Personal

答:
This was just answered some hours before you posted this question.

https://stackoverflow.com/a/44442707/1895303

Use lineRenderer.positionCount.

```<code>lineRenderer.positionCount = 5;
</code>```

Body:
using UnityEngine;
using UnityEditor;

public class DrawRectangle : MonoBehaviour
{
    LineRenderer line;
    void Start()
    {
        line = transform.GetComponent<LineRenderer>();
        line.SetVertexCount(5);
        line.SetPosition(0, new Vector3(-1, 1, 0));
        line.SetPosition(1, new Vector3(1, 1, 0));
        line.SetPosition(2, new Vector3(1, -1, 0));
        line.SetPosition(3, new Vector3(-1, -1, 0));
        line.SetPosition(4, new Vector3(-1, 1, 0));
    }
}

The script is attached to a GameObject with LineRenderer component.
But I'm getting errors on all the line properties.
The SetVertexCount and all the SetPosition do not exist.

I'm using unity ver 5.5.1f1 Personal

Body:
This was just answered some hours before you posted this question.

https://stackoverflow.com/a/44442707/1895303

Use lineRenderer.positionCount.

lineRenderer.positionCount = 5;


问:
Recommended structure for multi Products and Customers
Let's say our company have 3 customers.

And we are developing 3 different products.

Products are built to allow customization for each customers.
Our repositories structure is thus as follow: For each products, we have a single Product-Core repository, and one Product-Customer repository for each customers.

Let's say these customers have bought these products:

-Cust1:

Product1

Product2

Product3

-Cust2:

Product1

Product2

-Cust3:

Product1

Product3

We would like each customer's stakeholder to log into VSTS and see his backlog items for the products he bought.
It is extremely important that each customers don't see other customers items.
Developers must be able to see all workitems for all Products and all Customers.

Also, as stated before, each product has a Core repository and a Customer specific repository.
So we may have to commit in both repositories when developing for a customer workitem.

What is the recommended structure to use in VSTS for this scenario, regarding Project / Teams / Security / etc ?

答:
You can put the three products into three VSTS projects, and add customers as teams for different products/projects.

```<code>Projects        teams
---------------------------------
Product1    cust1, cust2, cust3
Product2    cust1, cust2
Product3    cust1, cust3
</code>```

For different teams, you add different members and set certain permissions.

And set areas permissions so that teams only view theirs own work items. Such as in the work of product2 https://account.visualstudio.com/Product2/_admin/_work -> click Areas Tab -> set security for cust1 -> add users of cust2 -> set View permissions for this node and View work items in this node to Deny -> set users of cust1 to deny View permissions for this node and View work items in this node for cust2 Area too.

Body:
You can put the three products into three VSTS projects, and add customers as teams for different products/projects.

Projects        teams
---------------------------------
Product1    cust1, cust2, cust3
Product2    cust1, cust2
Product3    cust1, cust3

For different teams, you add different members and set certain permissions.

And set areas permissions so that teams only view theirs own work items. Such as in the work of product2 https://account.visualstudio.com/Product2/_admin/_work -> click Areas Tab -> set security for cust1 -> add users of cust2 -> set View permissions for this node and View work items in this node to Deny -> set users of cust1 to deny View permissions for this node and View work items in this node for cust2 Area too.


问:
Are lots of inheritied single-plugin profiles in Maven a good idea?
In our infrastructure, we have lots of little Java projects built by Maven2. Each project has its own pom.xml that ultimately inherits from our one company "master" parent pom.

We've recently started adding small profiles to our parent pom, disabled by default, that, when enabled, execute a single plugin in a conventional manner.

Examples:

The 'sources' profile executes the maven-source-plugin to create the jar of project sources.

The 'clover' profile executes the maven-clover2-plugin to generate the Clover report. It also embeds our Clover license file so it need not be re-specified in child projects.

The 'fitnesse' profile executes the fitnesse-maven-plugin to run the fitnesse tests associated with the project. It contains the fitnesse server host and port and other information that need not be repeated.

This is being used to specify builds in our CI server like:

```<code>mvn test -P clover
mvn deploy site-deploy -P fitnesse,sources
</code>```

and so on.

So far, this seems to provide a convenient composition of optional features.

However, are there any dangers or pitfalls in continuing on with this approach (obvious or otherwise)? Could this type of functionality be better implemented or expressed in another way?

答:
The problem with this solution is that you may be creating a "pick and choose" model which is a bit un-mavenesque. In the case of the profiles you're describing you're sort of in-between; if each profile produces a decent result by itself you may be ok. The moment you start requiring specific combinations of profiles I think you're heading for troubles.

Individual developers will typically run into consistency issues because they forget which set of profiles should be used for a given scenario. Your mileage may vary, but we had real problems with this. Half your developers will forget the "correct" combinations after only a short time and end up wasting hours on a regular basis because they run the wrong combinations at the wrong time.

The practical problem you'll have with this is that AFAIK there's no way to have a set of "meta" profiles that activate a set of sub-profiles. If there had been a nice way to create an umbrella profile this'd be a really neat feature. Your "fitnesse" and "sources" profiles should really be private, activated by one or more meta-profiles. (You can activate a default set in settings.xml for each developer)

OwnerDisplayName: Brian Laframboise

Body:
In our infrastructure, we have lots of little Java projects built by Maven2. Each project has its own pom.xml that ultimately inherits from our one company "master" parent pom.

We've recently started adding small profiles to our parent pom, disabled by default, that, when enabled, execute a single plugin in a conventional manner.

Examples:

The 'sources' profile executes the maven-source-plugin to create the jar of project sources.

The 'clover' profile executes the maven-clover2-plugin to generate the Clover report. It also embeds our Clover license file so it need not be re-specified in child projects.

The 'fitnesse' profile executes the fitnesse-maven-plugin to run the fitnesse tests associated with the project. It contains the fitnesse server host and port and other information that need not be repeated.

This is being used to specify builds in our CI server like:

mvn test -P clover
mvn deploy site-deploy -P fitnesse,sources

and so on.

So far, this seems to provide a convenient composition of optional features.

However, are there any dangers or pitfalls in continuing on with this approach (obvious or otherwise)? Could this type of functionality be better implemented or expressed in another way?

OwnerDisplayName: krosenvold

LastEditorDisplayName: krosenvold


问:
Why does Xcode show errors in the source code, but does my app compile and run properly?
It shows the error, but when I build or compile the app. It works perfectly. There is no error in runtime. How can I solve this?

答: These kinds of errors often occur if you have multiple targets (e.g. a "Test" target and an "App" target) and some files are linked with both targets and other files are linked with just the "App" target. So in order to fix this, browse through your files and make sure they are linked to the proper targets. Use the "target membership" pane to easily compare files in your project.


问:
Toggle() function is not working in accordion
Onclick of (.cancel-name) cancel button which is inside of panel-body, panel-body has to get hide and I have used toggle function for that and it is working fine. But, after that edit is not working once if the page is refreshed edit will work can anyone help me out from this?

view page

```<code><div class="panel-group" id="accordion">
    <div class="panel panel-default">
        <div class="panel-heading row">
            <div class="col-md-4">First Name</div>
            <div class="col-md-4"><?php echo $row->first_name; ?></div>
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
                <div class="col-md-4 profile-edit"> <i class="fa fa-pencil"></i> Edit</div>
            </a>
        </div>
        <div id="collapseOne" class="panel-collapse collapse">
            <div class="panel-body">
                <div class="row">
                    <div class="col-md-7 col-md-offset-2 text-center">
                        <label class="col-md-4">First Name</label>
                        <div class="col-md-8">
                            <input type="hidden" name="id" value="<?php echo $row->id; ?>" />
                            <input type ="text" name="first_name" id="first_name" class="form-control" value="<?php echo $row->first_name; ?>"/></br>
                            <input type="submit" value="Save" class="btn btn-success" style="width:70px;">
                            <!--                                            <button type="submit" class="btn btn-success" name="" id="">Save</button>-->
                            <button  type="button" class="btn btn-warning cancel-name">Cancel</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

Script

```<code><script>
    var event = 'click';
    var speed = "500";
    $(document).ready(function () {
        $('.cancel-name').on(event, function () {
            $("div.panel-body").toggle();

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

答:
You don't need to have click event to toggle collapsing panel on cancel. Just add data-target and data-toggle attributes to cancel button as you have it for Edit button:

Example:

```<code><button type="button" data-target="#collapseOne" data-toggle="collapse" class="btn btn-warning cancel-name">Cancel</button>
</code>```

Working Snippet

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" />

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />

First Name

        John Doe

  Edit

            First Name

              <input type="hidden" name="id" value="<?php echo $row->id; ?>" />
              <input type="text" name="first_name" id="first_name" class="form-control" value="<?php echo $row->first_name; ?>" />

              <input type="submit" value="Save" class="btn btn-success" style="width:70px;" />

              <button type="button" data-target="#collapseOne" data-toggle="collapse" class="btn btn-warning cancel-name">Cancel</button>

```

Body:
Onclick of (.cancel-name) cancel button which is inside of panel-body, panel-body has to get hide and I have used toggle function for that and it is working fine. But, after that edit is not working once if the page is refreshed edit will work can anyone help me out from this?

view page

First Name

<?php echo $row->first_name; ?>

  Edit

                        First Name

                            <input type="hidden" name="id" value="<?php echo $row->id; ?>" />
                            <input type ="text" name="first_name" id="first_name" class="form-control" value="<?php echo $row->first_name; ?>"/>

                            <input type="submit" value="Save" class="btn btn-success" style="width:70px;">

                            <button  type="button" class="btn btn-warning cancel-name">Cancel</button>

Script

Body:
You don't need to have click event to toggle collapsing panel on cancel. Just add data-target and data-toggle attributes to cancel button as you have it for Edit button:

Example:

<button type="button" data-target="#collapseOne" data-toggle="collapse" class="btn btn-warning cancel-name">Cancel</button>

Working Snippet

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>

<div class="panel-group" id="accordion">
  <div class="panel panel-default">
    <div class="panel-heading row">
      <div class="col-md-4">First Name</div>
      <div class="col-md-4">
        John Doe
      </div>
      <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
        <div class="col-md-4 profile-edit"> <i class="fa fa-pencil"></i> Edit</div>
      </a>
    </div>
    <div id="collapseOne" class="panel-collapse collapse">
      <div class="panel-body">
        <div class="row">
          <div class="col-md-7 col-md-offset-2 text-center">
            <label class="col-md-4">First Name</label>
            <div class="col-md-8">
              <input type="hidden" name="id" value="<?php echo $row->id; ?>" />
              <input type="text" name="first_name" id="first_name" class="form-control" value="<?php echo $row->first_name; ?>" /><br/>
              <input type="submit" value="Save" class="btn btn-success" style="width:70px;" />
              <!--                                            <button type="submit" class="btn btn-success" name="" id="">Save</button>-->
              <button type="button" data-target="#collapseOne" data-toggle="collapse" class="btn btn-warning cancel-name">Cancel</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>


问:
how to dynamicly calculate angular class var
```<code>export class example {
  @Input() a;
  @Input() b;
  c；
  constructor() {
  }
}
</code>```

a and b will change dynamiclly.I want c be like this:c=a+b;how can i do that like react's state.

答:
You can use a getter

```<code>@Component({ /* ...  */})
export class SomeComponent {
   @Input() numberA: number;
   @Input() numberB: number;

   constructor() { }

   get numberC() {
       return this.numberA + this.numberB;
   }
}
</code>```

Then you can bind to it using {{ numberC }}. Everytime numberC is accessed it will compute the value from the current state of numberA and numberB

I changed the names of the properties for more clarity, you can read more on `Typescript getters and setters here

Body:
export class example {
  @Input() a;
  @Input() b;
  c；
  constructor() {
  }
}

a and b will change dynamiclly.I want c be like this:c=a+b;how can i do that like react's state.

Body:
You can use a getter

@Component({ /* ...  */})
export class SomeComponent {
   @Input() numberA: number;
   @Input() numberB: number;

   constructor() { }

   get numberC() {
       return this.numberA + this.numberB;
   }
}

Then you can bind to it using {{ numberC }}. Everytime numberC is accessed it will compute the value from the current state of numberA and numberB

I changed the names of the properties for more clarity, you can read more on `Typescript getters and setters here


问:
how to start a next activity after clicking on viewpager?
my HomeActivity.java :

```<code>    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    FragmentManager fm = getSupportFragmentManager();
    SlidingImage_Adapter pagerAdapter = new SlidingImage_Adapter(fm);
    pager.setAdapter(pagerAdapter);
}

private Boolean exit=false;
@Override
public void onBackPressed() {
    if (exit) {
        finish();
    } else {
        Toast.makeText(this, "Tekan lagi untuk keluar.",
                Toast.LENGTH_SHORT).show();
        exit = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                exit = false;
            }
        }, 3 * 1000);
    }
    ;
}
</code>```

this is for connecting between Homeact and image_model

my SlidingImage_adapter.java :

```<code>@Override
public Fragment getItem(int arg0) {
    ImageModel myFragment = new ImageModel();
    Bundle data = new Bundle();
    data.putInt("current_page", arg0+1);
    myFragment.setArguments(data);
    return myFragment;
}
@Override
public int getCount() {
    return Page_Count;
}
</code>```

this is to take the pict from .xml that i make (layout1.xml, layout2.xml, etc)

my Image_Model.java

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle data = getArguments();
    mCurrentPage = data.getInt("current_page", 0);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = null;
    if (mCurrentPage == 1) {
        v = inflater.inflate(R.layout.layout1, container, false);
    } else if (mCurrentPage == 2) {
        v = inflater.inflate(R.layout.layout2, container, false);
    } else if (mCurrentPage == 3) {
        v = inflater.inflate(R.layout.layout3, container, false);
    }
    return v;
}
</code>```

答: Set viewPager.clicable = true; on xml file or dynamically if you want and use onClickListener method on viewpager.</p>

Body:
my HomeActivity.java :

    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    FragmentManager fm = getSupportFragmentManager();
    SlidingImage_Adapter pagerAdapter = new SlidingImage_Adapter(fm);
    pager.setAdapter(pagerAdapter);
}

private Boolean exit=false;
@Override
public void onBackPressed() {
    if (exit) {
        finish();
    } else {
        Toast.makeText(this, "Tekan lagi untuk keluar.",
                Toast.LENGTH_SHORT).show();
        exit = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                exit = false;
            }
        }, 3 * 1000);
    }
    ;
}

this is for connecting between Homeact and image_model

my SlidingImage_adapter.java :

@Override
public Fragment getItem(int arg0) {
    ImageModel myFragment = new ImageModel();
    Bundle data = new Bundle();
    data.putInt("current_page", arg0+1);
    myFragment.setArguments(data);
    return myFragment;
}
@Override
public int getCount() {
    return Page_Count;
}

this is to take the pict from .xml that i make (layout1.xml, layout2.xml, etc)

my Image_Model.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle data = getArguments();
    mCurrentPage = data.getInt("current_page", 0);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = null;
    if (mCurrentPage == 1) {
        v = inflater.inflate(R.layout.layout1, container, false);
    } else if (mCurrentPage == 2) {
        v = inflater.inflate(R.layout.layout2, container, false);
    } else if (mCurrentPage == 3) {
        v = inflater.inflate(R.layout.layout3, container, false);
    }
    return v;
}


问:
Silverlight: Determine which control initiated drag'n'drop
Using the drag'n'drop features of the Silverlight 4 Toolkit, I have a drag'n'drop enabled Listbox where each ListboxItem can be dragged/reordered up and down.

Each ListboxItem contains several controls (TextBlocks, TextBoxes and Buttons) and my problem is that when I click the buttons within a ListboxItem, I will occasionally initiate a drag event instead of just a click event on that control.

One solution would be to handle the ItemDragStarting event and determine what was clicked on to start the event - and cancel the event if called by a Button.

I can however not figure out how to determine what I've clicked on. Sender of the event and e.DragSource is of type ListBoxDragDropTarget, whether I initiate the drag from a button or the ListboxItem itself.

Any help would be appreciated - solutions to my problem or alternative methods of doing what I need!

答:
You can drill down to the object type by using the following method:</p>

```<code>private void OldFaithful_ItemDragStarting(object sender, ItemDragEventArgs e)
        {
            SelectionCollection selections = e.Data as SelectionCollection;

            if (selections != null)
            {
                IEnumerable<CXSectionControl> draggedItems = selections.Select(s => s.Item as YOUREXCPECTEDOBJECTTYPE);
                foreach (YOUREXCPECTEDOBJECTTYPE x in draggedItems)
                {
                    MessageBox.Show(x.GetType().ToString());
                }

            }
        }
</code>```

Body:
You can drill down to the object type by using the following method:

private void OldFaithful_ItemDragStarting(object sender, ItemDragEventArgs e)
        {
            SelectionCollection selections = e.Data as SelectionCollection;

            if (selections != null)
            {
                IEnumerable<CXSectionControl> draggedItems = selections.Select(s => s.Item as YOUREXCPECTEDOBJECTTYPE);
                foreach (YOUREXCPECTEDOBJECTTYPE x in draggedItems)
                {
                    MessageBox.Show(x.GetType().ToString());
                }

            }
        }


问:
Access-Control-Allow-Credentials header not added
I want to add Access-Control-Allow-Credentials: true to a response on an Apache 2.2 server. My .htaccess file looks like this.

```<code>SetEnvIfNoCase ORIGIN (.*) ORIGIN=$1
Header always add Access-Control-Allow-Origin "%{ORIGIN}e" env=ORIGIN
Header always add Access-Control-Allow-Methods "GET,POST,OPTIONS,DELETE,PUT"
Header always add Access-Control-Allow-Headers "Link, Location, Accept-Post, Content-Type, Slug, Origin"
Header always set Access-Control-Allow-Credentials "true"

RewriteCond %{HTTP_ACCEPT} text/turtle
RewriteRule ^/?$ https://example/me.ttl [R=303]
</code>```

On line 5 I set the header Access-Control-Allow-Credentials to true. But the resulting response has '' for this header. When I add line 5 also at the end of the file, resulting in the following

```<code>SetEnvIfNoCase ORIGIN (.*) ORIGIN=$1
Header always add Access-Control-Allow-Origin "%{ORIGIN}e" env=ORIGIN
Header always add Access-Control-Allow-Methods "GET,POST,OPTIONS,DELETE,PUT"
Header always add Access-Control-Allow-Headers "Link, Location, Accept-Post, Content-Type, Slug, Origin"
Header always set Access-Control-Allow-Credentials "true"

RewriteCond %{HTTP_ACCEPT} text/turtle
RewriteRule ^/?$ https://example/me.ttl [R=303]
Header always set Access-Control-Allow-Credentials "true"
</code>```

the value of Access-Control-Allow-Credentials is 'true, true'. While I want it to be only 'true'.
Does anybody know what the reason is for this behaviour?

EDIT: I've tried to put '' in line 5 in order to get 'true' at the end, but then I get just ''.

答: I contacted my hosting and although they said that nothing is wrong on their side, suddenly it works...</p>

Body:
I want to add Access-Control-Allow-Credentials: true to a response on an Apache 2.2 server. My .htaccess file looks like this.

SetEnvIfNoCase ORIGIN (.*) ORIGIN=$1
Header always add Access-Control-Allow-Origin "%{ORIGIN}e" env=ORIGIN
Header always add Access-Control-Allow-Methods "GET,POST,OPTIONS,DELETE,PUT"
Header always add Access-Control-Allow-Headers "Link, Location, Accept-Post, Content-Type, Slug, Origin"
Header always set Access-Control-Allow-Credentials "true"

RewriteCond %{HTTP_ACCEPT} text/turtle
RewriteRule ^/?$ https://example/me.ttl [R=303]

On line 5 I set the header Access-Control-Allow-Credentials to true. But the resulting response has '' for this header. When I add line 5 also at the end of the file, resulting in the following

SetEnvIfNoCase ORIGIN (.*) ORIGIN=$1
Header always add Access-Control-Allow-Origin "%{ORIGIN}e" env=ORIGIN
Header always add Access-Control-Allow-Methods "GET,POST,OPTIONS,DELETE,PUT"
Header always add Access-Control-Allow-Headers "Link, Location, Accept-Post, Content-Type, Slug, Origin"
Header always set Access-Control-Allow-Credentials "true"

RewriteCond %{HTTP_ACCEPT} text/turtle
RewriteRule ^/?$ https://example/me.ttl [R=303]
Header always set Access-Control-Allow-Credentials "true"

the value of Access-Control-Allow-Credentials is 'true, true'. While I want it to be only 'true'.
Does anybody know what the reason is for this behaviour?

EDIT: I've tried to put '' in line 5 in order to get 'true' at the end, but then I get just ''.


问:
Getting an issue while integrating google-cloud with webpack
I am integrating the google-cloud npm package with my react application and i am using firebase.

Errors i am encountering -

WARNING in ./~/google-cloud/~/hash-stream-validation/index.js Module
  not found: Error: Can't resolve 'fast-crc32c' in
  '/home/linuxbox/React-Workspace/Kaptify/node_modules/google-cloud/node_modules/hash-stream-validation'
  @ ./~/google-cloud/~/hash-stream-validation/index.js 5:8-30  @
  ./~/google-cloud/~/@google-cloud/storage/src/file.js  @
  ./~/google-cloud/~/@google-cloud/storage/src/index.js  @
  ./~/google-cloud/src/index.js  @ ./src/actions/UserStateStore.js  @
  ./app.js  @ multi (webpack)-dev-server/client?http://127.0.0.1:3000
  webpack/hot/dev-server ./app.js

WARNING in ./~/google-cloud/~/google-auto-auth/index.js 53:13-58
  Critical dependency: the request of a dependency is an expression

WARNING in ./~/google-cloud/~/grpc/src/node/src/grpc_extension.js
  38:14-35 Critical dependency: the request of a dependency is an
  expression

WARNING in ./~/google-cloud/~/node-pre-gyp/lib/pre-binding.js 19:22-48
  Critical dependency: the request of a dependency is an expression

WARNING in ./~/google-cloud/~/node-pre-gyp/lib/util/versioning.js
  15:20-67 Critical dependency: the request of a dependency is an
  expression

Can anybody help me to resolve this?

答:
I see you're using webpack, and I'm assuming you're using the google-cloud library in the backend.

Try putting this in your webpack config:

```<code>config = {
    // ...
    externals: {
        '@google-cloud/storage': 'commonjs @google-cloud/storage'
    },
    // ...
}
</code>```

Explanation

Modules meant for the backend aren't really made with the intention of them being bundled (see: Backend Apps with Webpack). So we use webpack's externals config to exclude libraries that don't handle that bundling well. When the app is run, they are just require()'ed from the node_modules directory as normal.

If you don't want to specify your offending modules one-by-one, try out webpack-node-externals to automatically exclude all modules.

Body:
I see you're using webpack, and I'm assuming you're using the google-cloud library in the backend.

Try putting this in your webpack config:

config = {
    // ...
    externals: {
        '@google-cloud/storage': 'commonjs @google-cloud/storage'
    },
    // ...
}

Explanation

Modules meant for the backend aren't really made with the intention of them being bundled (see: Backend Apps with Webpack). So we use webpack's externals config to exclude libraries that don't handle that bundling well. When the app is run, they are just require()'ed from the node_modules directory as normal.

If you don't want to specify your offending modules one-by-one, try out webpack-node-externals to automatically exclude all modules.


问:
How to coorect a corrupted excel file
how to correct a excel file which is on opening giving message as 'Excel cannot open the file because the file format or file extension is not valid,verify that the file has not been corrupted and the file extension matches the format of the file.</p>

答:
Try to open the MS Excel file in safe mode. If it's opening in safe mode then delete the COM Add-ins.

If above option won't work the repair MS Office.

Good Luck!

Title: How to coorect a corrupted excel file


问:
ImageMagick: convert image to B&W, high contrast!
I'm trying to OCR certain images, but am having problems with the accuracy. I would like to see if I can improve accuracy by converting images to B&W, high contrast. Any ideas how I can do that with ImageMagick?</p>

答: Fred's two colour threshold ImageMagick script might help.</p>