问:
How do I get content from push notification?
Using Swift3 with xcode8.3

Below is my function code

```<code>func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    print("==== didReceiveRemoteNotification ====")
    print(userInfo)

    let state = UIApplication.shared.applicationState

    if state == .background {
        // background
        if let pushUrl = userInfo[AnyHashable("url")] as? String {
            viewController?.redirectTo(url: pushUrl)
        }
    }
    else if state == .active {
        // foreground
        print("==== foreground Running ====")
        let pushUrl = userInfo[AnyHashable("url")]
        let pushApns = userInfo[AnyHashable("aps")]
        let pushAlert = pushApns["alert"]
        viewController?.showAlertBox(url: pushUrl as! String, msg: pushAlert)
    }
}
</code>```

When I receive a notification on foreground, I need to get the content from it and pass it to viewController.

below is the log from my Xcode

```<code>==== didReceiveRemoteNotification ====
[AnyHashable("aps"): {
    alert = "this is alert";
    badge = 0;
}, AnyHashable("url"): https://www.google.com]
</code>```

But the code above is not working? How can I get "alert" and "url" content from notification?

答:
You're almost there! Try the following:</p>

```<code>let data = userInfo as! [String: AnyObject]

if let url = data["url"] {
    print(url)
}

if let aps = data["aps"] {
    print(aps["alert"])
}
</code>```

Body:
Using Swift3 with xcode8.3

Below is my function code

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    print("==== didReceiveRemoteNotification ====")
    print(userInfo)

    let state = UIApplication.shared.applicationState

    if state == .background {
        // background
        if let pushUrl = userInfo[AnyHashable("url")] as? String {
            viewController?.redirectTo(url: pushUrl)
        }
    }
    else if state == .active {
        // foreground
        print("==== foreground Running ====")
        let pushUrl = userInfo[AnyHashable("url")]
        let pushApns = userInfo[AnyHashable("aps")]
        let pushAlert = pushApns["alert"]
        viewController?.showAlertBox(url: pushUrl as! String, msg: pushAlert)
    }
}

When I receive a notification on foreground, I need to get the content from it and pass it to viewController.

below is the log from my Xcode

==== didReceiveRemoteNotification ====
[AnyHashable("aps"): {
    alert = "this is alert";
    badge = 0;
}, AnyHashable("url"): https://www.google.com]

But the code above is not working? How can I get "alert" and "url" content from notification?

Body:
You're almost there! Try the following:

let data = userInfo as! [String: AnyObject]

if let url = data["url"] {
    print(url)
}

if let aps = data["aps"] {
    print(aps["alert"])
}


来源: stackexchange

问:
if statement inside while that depends on the same variable that while depends on
consider the below programs.
I would like to know why this codes behave in different way.Thankyou in advance.

this doesnot print any

```<code>#include <stdio.h>

int main() {
    int i = 0;

    while(i < 10) {
        if(i < 7)
            printf("value is%d", i++);
    }
}
</code>```

while this does

```<code>#include <stdio.h>
int main() {
    int i = 0;

    while(i < 10) {
        if(i < 7)
            printf("value is%d\n", i++);
    }
}
</code>```

答:
First note both your programs never exit. When i hits 7 it's game over and your stuck forever doing nothing.

Second note the only difference is printing a new line. That should have been your clue. Since the loop is infinite you never print a new line or exit - both things flush STDOUT. Until you flush STDOUT you're just accumulating what you're trying to print in a buffer. Only the flushing will get it on screen, and clean the buffer.

@chux added a good point:

Buffering of STDOUT (or IN or ERR) is implementation defined, meaning different flavors of Linux, Windows, and so forth may display different behavior. Obviously in the OP STDOUT is buffered - as no output appears.

ContentLicense: CC BY-SA 3.0

Body:
consider the below programs.
I would like to know why this codes behave in different way.Thankyou in advance.

this doesnot print any

#include <stdio.h>

int main() {
    int i = 0;

    while(i < 10) {
        if(i < 7)
            printf("value is%d", i++);
    }
}

while this does

#include <stdio.h>
int main() {
    int i = 0;

    while(i < 10) {
        if(i < 7)
            printf("value is%d\n", i++);
    }
}


问:
Concating Values for rows in Oracle
I have a query in Oracle that does a group by on Field1.  This Query returns 2 Rows, however, row1 has a count of 2 on field1.  I'd like to display the both Field1 values in a single cell on row1.  Is this possible?</p>

答: Writing a small stored procedure is sometimes easiest, because you can control the formatting independently of number.  The other answers may be better, but this is quicker if you're familiar with PL/SQL.</p>

ContentLicense: CC BY-SA 2.5

Title: Concating Values for rows in Oracle


问:
Viewing database file of my android application in Redmi phones
My android application is not working in REDMI phones. Infact not sure because sometimes it stores the data and sometimes not. It gives unexpected results, i can able to access my application in other phones correctly.</p>

答:
use facebook stetho which allowed to access app database and fire query on it.
http://facebook.github.io/stetho/#integrations

once integration completed.check in google chrome browser : chrome://inspect/#devices


问:
Elegant way to construct a UIView with params from Xib
I have a UIView subclass that i want to instantiate from my code during runtime which should present a custom picker such that its range (min, max) will be loaded from a server.
I'm looking for a nice way to call a single method that will:

```<code>* get the view from the Xib
* set its min, max properties so its can draw itself
</code>```

I can create init(withMin:Int, max:Int)
But the view won't load from nib so awakeFromNib never gets called (which have some initialize code there)

Thanks for the helpers :)

答:
The easiest way to do this is to just create a static function inside the subclass

```<code>class SomeView: UIView {
    var someInt: Int = 0
    var someString: String = ""

    static func instantiate(owner: AnyObject?, someInt: Int, someString: String) -> SomeView
        // create the View
        let newView = Bundle.main.loadNibNamed("SomeView", owner: self, options: nil)?.first as! SomeView

        // set properties
        newView.someString = someString
        newView.someInt = someInt

        return newView
    }

    ...
    some other codes here
    ...
}
</code>```

The use of this would be like this.

```<code>let someView = SomeView.instantiate(owner: self, someInt: 100, someString: "LOOL")
self.view.addSubView(someView)
</code>```

Body:
I have a UIView subclass that i want to instantiate from my code during runtime which should present a custom picker such that its range (min, max) will be loaded from a server.
I'm looking for a nice way to call a single method that will:

* get the view from the Xib
* set its min, max properties so its can draw itself

I can create init(withMin:Int, max:Int)
But the view won't load from nib so awakeFromNib never gets called (which have some initialize code there)

Thanks for the helpers :)

Body:
The easiest way to do this is to just create a static function inside the subclass

class SomeView: UIView {
    var someInt: Int = 0
    var someString: String = ""

    static func instantiate(owner: AnyObject?, someInt: Int, someString: String) -> SomeView
        // create the View
        let newView = Bundle.main.loadNibNamed("SomeView", owner: self, options: nil)?.first as! SomeView

        // set properties
        newView.someString = someString
        newView.someInt = someInt

        return newView
    }

    ...
    some other codes here
    ...
}

The use of this would be like this.

let someView = SomeView.instantiate(owner: self, someInt: 100, someString: "LOOL")
self.view.addSubView(someView)

ContentLicense: CC BY-SA 4.0


问:
Is it subtable to using spring security to do authorization ( acl ) from cookie only?
I am developing a back-end application, but my application is only part of the whole project, there exists a cookies login application so that the authentication is done and not my control.

In this app, i have to design a file sharing system, some types of clients, file sharing between clients.

I can only get the cookie(custom logic and not standard) which contains all data i need.

My manager advices me to use spring security to do only authorization and then code the acl logic in the authorization. I doubt if it is a good idea.

i have read the spring security doc in brief, cant find any idea about my situation.

Finally sorry for my poor english.

答: Its up to you. But I would suggest Spring Security.It is a flexible and powerful authentication and access control framework to secure Spring-based Java web application.</p>


问:
Drop down options to hide using javascript
I have two drop down menus where I want the options in the second drop down menu to be hidden depending of which option is selected in the first drop down menu. I have found some examples in google for this but the problem is that because I am too deep in my coding, I do not want to risk creating new functions and using jquery and etc from scratch. So what I want to know if someone can implement into my code the way this can be achieved by creating one example of this which is below:

If optionDrop (Drop Down 1) value = "ABC", then numberDrop (Drop Down 2) options will shows "", "1", "2" and "3" but hides "4".

Below is javascript code which is relevant to this question (there is more to this code but don't need to show it for this question):

```<code>   function getDropDown() {
         var optionDrop = document.getElementsByName("optionDrop");
        var numberDrop = document.getElementsByName("numberDrop");

    if (optionDrop[0].value == "abc" || optionDrop[0].value == "abcd" || optionDrop[0].value == "abcde"){
                    numberDrop[0].style.display = "block";
                    na.style.display = "none";

    }else if (optionDrop[0].value == "trueorfalse" || optionDrop[0].value == "yesorno"){
                    numberDrop[0].style.display = "none";
                    na.style.display = "block";
    }
}
</code>```

Html code that shows drop down menus:

```<code><form id="enter" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="return validateForm(this);" >
<table id="middleDetails" border="1">
<tr>
<td>Option Type:</td>
    <td>
        <select name="optionDrop" onClick="getDropDown()">
<option value="">Please Select</option>
<option value="abc">ABC</option>
<option value="abcd">ABCD</option>
<option value="abcde">ABCDE</option>
<option value="trueorfalse">True or False</option>
<option value="yesorno">Yes or No</option>
</select>
    </td>
    </tr>
<tr>
<td>Number of Answers:</td>
<td>
<select name="numberDrop" id="numberDropId" onChange="getButtons()">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
</tr>
</table>
</form>
</code>```

答:
Try to disable that option with hidden attribute.</p>

```<code>if (optionDrop[0].options[optionDrop[0].selectedIndex].text != "Abc") {
    for (var ctr = 0; ctr < optionDrop[0].length; ctr++)
    {
        if (optionDrop[0].options[ctr].text == "Abc")
        {
            optionDrop[0].options[ctr].hidden = "true";
        }
    }
}
else {
    optionDrop[0].options[optionDrop[0].selectedIndex].hidden = "false";
}
</code>```

Body:
I have two drop down menus where I want the options in the second drop down menu to be hidden depending of which option is selected in the first drop down menu. I have found some examples in google for this but the problem is that because I am too deep in my coding, I do not want to risk creating new functions and using jquery and etc from scratch. So what I want to know if someone can implement into my code the way this can be achieved by creating one example of this which is below:

If optionDrop (Drop Down 1) value = "ABC", then numberDrop (Drop Down 2) options will shows "", "1", "2" and "3" but hides "4".

Below is javascript code which is relevant to this question (there is more to this code but don't need to show it for this question):

   function getDropDown() {
         var optionDrop = document.getElementsByName("optionDrop");
        var numberDrop = document.getElementsByName("numberDrop");

    if (optionDrop[0].value == "abc" || optionDrop[0].value == "abcd" || optionDrop[0].value == "abcde"){
                    numberDrop[0].style.display = "block";
                    na.style.display = "none";

    }else if (optionDrop[0].value == "trueorfalse" || optionDrop[0].value == "yesorno"){
                    numberDrop[0].style.display = "none";
                    na.style.display = "block";
    }
}

Html code that shows drop down menus:

<form id="enter" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="return validateForm(this);" >

Option Type:

        <select name="optionDrop" onClick="getDropDown()">
<option value="">Please Select</option>
<option value="abc">ABC</option>
<option value="abcd">ABCD</option>
<option value="abcde">ABCDE</option>
<option value="trueorfalse">True or False</option>
<option value="yesorno">Yes or No</option>
</select>

Number of Answers:

<select name="numberDrop" id="numberDropId" onChange="getButtons()">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>

</form>

Body:
Try to disable that option with hidden attribute.

if (optionDrop[0].options[optionDrop[0].selectedIndex].text != "Abc") {
    for (var ctr = 0; ctr < optionDrop[0].length; ctr++)
    {
        if (optionDrop[0].options[ctr].text == "Abc")
        {
            optionDrop[0].options[ctr].hidden = "true";
        }
    }
}
else {
    optionDrop[0].options[optionDrop[0].selectedIndex].hidden = "false";
}


问:
Auto select value from dropdown from  tag
I have a block of code in a page where a user has to select the package from available packages.

```<code><a href="#block"> VVIP <a>
<a href="#block"> VIP <a>
<a href="#block"> Median <a>
<a href="#block"> General <a>
</code>```

Based on the user selection I want to select a drop-down value in the form. The form is available on the same page.

```<code><select>
    <option selected="" value="Default">Select Package</option>
    <option value="1">Kids Pass</option>
    <option value="2">Single Adult Pass</option>
    <option value="3">Couple Pass</option>
    <option value="4">Single Day Pass</option>
</select>
</code>```

please help me if any HTML or JavaScript solution.

答:
This is what you need,you were looking for events using JS

function selectauto(nameofpackage)
{
    var element = document.getElementById('packages');
    element.value = nameofpackage;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>href="#block" onclick="selectauto(1)"> VVIP <a><br>
href="#block" onclick="selectauto(2)"> VIP <a><br>
href="#block" onclick="selectauto(3)"> Median <a><br>
href="#block" onclick="selectauto(4)"> General <a><br>
<select id="packages">
    <option selected="" value="Default">Select Package</option>
    <option value="1">Kids Pass</option>
    <option value="2">Single Adult Pass</option>
    <option value="3">Couple Pass</option>
    <option value="4">Single Day Pass</option>
</select></code>```

Hope this helps.

Title: Auto select value from dropdown from <a> tag

Body:
I have a block of code in a page where a user has to select the package from available packages.

 VVIP
 VIP
 Median
 General

Based on the user selection I want to select a drop-down value in the form. The form is available on the same page.

<select>
    <option selected="" value="Default">Select Package</option>
    <option value="1">Kids Pass</option>
    <option value="2">Single Adult Pass</option>
    <option value="3">Couple Pass</option>
    <option value="4">Single Day Pass</option>
</select>

please help me if any HTML or JavaScript solution.

Body:
This is what you need,you were looking for events using JS

function selectauto(nameofpackage)
{
    var element = document.getElementById('packages');
    element.value = nameofpackage;
}

<a href="#block" onclick="selectauto(1)"> VVIP <a><br>
<a href="#block" onclick="selectauto(2)"> VIP <a><br>
<a href="#block" onclick="selectauto(3)"> Median <a><br>
<a href="#block" onclick="selectauto(4)"> General <a><br>
<select id="packages">
    <option selected="" value="Default">Select Package</option>
    <option value="1">Kids Pass</option>
    <option value="2">Single Adult Pass</option>
    <option value="3">Couple Pass</option>
    <option value="4">Single Day Pass</option>
</select>

Hope this helps.


问:
How to consume ASP Rest web Api in Xamarin forms?
I have created a REST Api in ASP.Net web form. I can read and write data from MySql database using the API (I tested the Api using chrome's REST Client extension). Now I am trying to consume the Rest Api in my cross platform xamarin forms. I just added a button in my app and see whether it can retrieve data if I click the button. I inserted a breakpoint at the var Json to see whether I'm getting any data. But I am not able to retrieve it. I am running the Web Api in localhost. I run the app in VS Android emulator. Please guide me on how to properly consume the REST web service. Thank you.

Web Api

```<code>namespace WorkAppApi.Controllers
{
public class MachinesController : ApiController
{
    // GET: api/Machines
    public List<machines> Get()
    {
        DBConn db = new DBConn();
        return db.getMachineList();
    }

    // GET: api/Machines/5
    public machines Get(long id)
    {
        DBConn db = new DBConn();
        machines m = db.getMachine(id);
        return m;
    }

    // POST: api/Machines
    public HttpResponseMessage Post([FromBody]machines value)
    {
        DBConn db = new DBConn();
        long id;

        id = db.addMachine(value);
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
        response.Headers.Location = new Uri(Request.RequestUri, String.Format("machines/{0}", id));
        return response;
    }

    // PUT: api/Machines/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE: api/Machines/5
    public void Delete(int id)
    {
    }
}
}
</code>```

Function submit button.

```<code>namespace WorkApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class TestPage : ContentPage
{
    private string Uri = "http://192.168.0.124:59547/api/Machines/";

    public TestPage ()
    {
        InitializeComponent ();
        check();
    }

    private async Task submit(object sender, EventArgs e)
    {

        var httpClient = new HttpClient();
        var json = await httpClient.GetAsync(Uri);

    }

}
}
</code>```

答:
this would be my answer:</p>

```<code>namespace WorkApp
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class TestPage : ContentPage
    {
        private string Uri = "http://192.168.0.124:59547/api/";
        List<Machine> machines;
        public TestPage ()
        {
          InitializeComponent ();
          check();
        }

        private async Task submit(object sender, EventArgs e)
        {
           var httpClient = new HttpClient();
           httpClient.BaseAddress = Uri // I have changed the Uri variabele, you should extend this class and give it the same base address in the constructor.
           var resp= await httpClient.GetAsync("Machines");
            if (resp.Result.IsSuccessStatusCode)
            {
                var repStr = resp.Result.Content.ReadAsStringAsync();
                machines= JsonConvert.DeserializeObject<List<Machine>>(repStr.Result.ToString());
            }
        }
     }
}
</code>```

Body:
I have created a REST Api in ASP.Net web form. I can read and write data from MySql database using the API (I tested the Api using chrome's REST Client extension). Now I am trying to consume the Rest Api in my cross platform xamarin forms. I just added a button in my app and see whether it can retrieve data if I click the button. I inserted a breakpoint at the var Json to see whether I'm getting any data. But I am not able to retrieve it. I am running the Web Api in localhost. I run the app in VS Android emulator. Please guide me on how to properly consume the REST web service. Thank you.

Web Api

namespace WorkAppApi.Controllers
{
public class MachinesController : ApiController
{
    // GET: api/Machines
    public List<machines> Get()
    {
        DBConn db = new DBConn();
        return db.getMachineList();
    }

    // GET: api/Machines/5
    public machines Get(long id)
    {
        DBConn db = new DBConn();
        machines m = db.getMachine(id);
        return m;
    }

    // POST: api/Machines
    public HttpResponseMessage Post([FromBody]machines value)
    {
        DBConn db = new DBConn();
        long id;

        id = db.addMachine(value);
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
        response.Headers.Location = new Uri(Request.RequestUri, String.Format("machines/{0}", id));
        return response;
    }

    // PUT: api/Machines/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE: api/Machines/5
    public void Delete(int id)
    {
    }
}
}

Function submit button.

namespace WorkApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class TestPage : ContentPage
{
    private string Uri = "http://192.168.0.124:59547/api/Machines/";

    public TestPage ()
    {
        InitializeComponent ();
        check();
    }

    private async Task submit(object sender, EventArgs e)
    {

        var httpClient = new HttpClient();
        var json = await httpClient.GetAsync(Uri);

    }

}
}

Body:
this would be my answer:

namespace WorkApp
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class TestPage : ContentPage
    {
        private string Uri = "http://192.168.0.124:59547/api/";
        List<Machine> machines;
        public TestPage ()
        {
          InitializeComponent ();
          check();
        }

        private async Task submit(object sender, EventArgs e)
        {
           var httpClient = new HttpClient();
           httpClient.BaseAddress = Uri // I have changed the Uri variabele, you should extend this class and give it the same base address in the constructor.
           var resp= await httpClient.GetAsync("Machines");
            if (resp.Result.IsSuccessStatusCode)
            {
                var repStr = resp.Result.Content.ReadAsStringAsync();
                machines= JsonConvert.DeserializeObject<List<Machine>>(repStr.Result.ToString());
            }
        }
     }
}


问:
Android Battery Broadcasts
I am trying to make a Battery Alarm Application.  I was reading the Android docs and found out that we don't need to register a BroadcastReceiver. We could do something like this-

```<code>IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
</code>```

MY QUESTIONS ARE-

Does the system broadcast intent(containing battery status) every time the
battery level change?

Do I have to query each time for battery level?

Also, How to play the alarm when the battery level reaches a
particular level(set by the user).

答:
```<code>Q1. Yes, system provide every time .
Example :
      private class BatteryBroadcastReceiver extends BroadcastReceiver {
            private final static String BATTERY_LEVEL = "level";
            @Override
            public void onReceive(Context context, Intent intent) {
                int level = intent.getIntExtra(BATTERY_LEVEL, 0);
                mBatteryLevelText.setText(getString(R.string.battery_level) + " " + level);
                mBatteryLevelProgress.setProgress(level);
            }
        }

//Register our BroadcastReceiver in application

    BatteryBroadcastReceiver mReceiver = new BatteryBroadcastReceiver();
    registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

//Update your progress bar get

    public class MainActivity extends Activity {
        private TextView mBatteryLevelText;
        private ProgressBar mBatteryLevelProgress;
        private BroadcastReceiver mReceiver;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mBatteryLevelText = (TextView) findViewById(R.id.textView);
            mBatteryLevelProgress = (ProgressBar) findViewById(R.id.progressBar);
            mReceiver = new BatteryBroadcastReceiver();
        }
        @Override
        protected void onStart() {
            registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            super.onStart();
        }
        @Override
        protected void onStop() {
            unregisterReceiver(mReceiver);
            super.onStop();
        }
        private class BatteryBroadcastReceiver extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
                mBatteryLevelText.setText(getString(R.string.battery_level) + " " + level);
                mBatteryLevelProgress.setProgress(level);
if(level<10){
// play Battery alarm.

            }
        }
    }
</code>```

Title: Android Battery Broadcasts

Body:
I am trying to make a Battery Alarm Application.  I was reading the Android docs and found out that we don't need to register a BroadcastReceiver. We could do something like this-

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);

MY QUESTIONS ARE-

Does the system broadcast intent(containing battery status) every time the
battery level change?

Do I have to query each time for battery level?

Also, How to play the alarm when the battery level reaches a
particular level(set by the user).


答:
You can do this by changing the options.selectedIndex Dom attribute with javascript

function selectOption(index){
      document.getElementById("select_stuff").options.selectedIndex = index;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!--This will selectKids pass-->
    href="#block" onclick="selectOption(1);"> VVIP <a>
    <!--This will Single Adult pass pass-->
    href="#block" onclick="selectOption(2);"> VIP <a>
    <!-- This will select Default -->
    href="#block" onclick="selectOption(0);"> Median <a>
    <!-- This will select Single Day pass -->
    href="#block" onclick="selectOption(4);"> General <a>

    <select id="select_stuff">
        <option selected="" value="Default">Select Package</option>
        <option value="1">Kids Pass</option>
        <option value="2">Single Adult Pass</option>
        <option value="3">Couple Pass</option>
        <option value="4">Single Day Pass</option>
    </select></code>```

Body:
You can do this by changing the options.selectedIndex Dom attribute with javascript

function selectOption(index){
      document.getElementById("select_stuff").options.selectedIndex = index;
    }

 <!--This will selectKids pass-->
    <a href="#block" onclick="selectOption(1);"> VVIP <a>
    <!--This will Single Adult pass pass-->
    <a href="#block" onclick="selectOption(2);"> VIP <a>
    <!-- This will select Default -->
    <a href="#block" onclick="selectOption(0);"> Median <a>
    <!-- This will select Single Day pass -->
    <a href="#block" onclick="selectOption(4);"> General <a>

    <select id="select_stuff">
        <option selected="" value="Default">Select Package</option>
        <option value="1">Kids Pass</option>
        <option value="2">Single Adult Pass</option>
        <option value="3">Couple Pass</option>
        <option value="4">Single Day Pass</option>
    </select>


问:
Is there a prefered way to specify a text column in SQLite?
Since the SQLite engine will not truncate the data you store in a text column, is there any advantage in being specific with column sizes when you define your schema?
Would anyone prefer this:

```<code>CREATE TABLE contact(
 id    INTEGER PRIMARY KEY,
 name  VARCHAR(45),
 title VARCHAR(10)
);
</code>```

over this:

```<code>CREATE TABLE contact(
 id    INTEGER PRIMARY KEY,
 name  TEXT,
 title TEXT
);
</code>```

Why?

Are there advantages to not being specific?

答:
The advantage of using varchar(x) is that it is compatible with other database systems - if I remember correctly, TEXT isn't a standard SQL datatype.

Other than being more standards-compliant, there is indeed no difference whether you use TEXT or VARCHAR. More info at http://sqlite.org/datatype3.html

Body:
Since the SQLite engine will not truncate the data you store in a text column, is there any advantage in being specific with column sizes when you define your schema?
Would anyone prefer this:

CREATE TABLE contact(
 id    INTEGER PRIMARY KEY,
 name  VARCHAR(45),
 title VARCHAR(10)
);

over this:

CREATE TABLE contact(
 id    INTEGER PRIMARY KEY,
 name  TEXT,
 title TEXT
);

Why?

Are there advantages to not being specific?


问:
How to get today's date as default in kendodatetimepicker in a kendo grid column
I'm working with a kendo grid in which a column consists of kendodatetimepicker.
User will be able to edit date and time for only yesterday and today.

So, when he clicks the edit button on the grid the datetimepicker should first show current date and time as default

My grid looks like this--

columns: [
          { field: "EntryType", title: "Entry Type", width: "50px", editor: $scope.typeDropDownEditor, template: "#=EntryType#" },
          { field: "Chemical", title: "Chemical Name", width: "50px", editor: $scope.chemicalDropDownEditor,template: "#=Chemical.ChemicalName#" },
          { field: "Facility", title: "Facility Name", width: "50px", editor: $scope.facilityDropDownEditor, template: "#=(Facility.FacilityName==null)? '' : Facility.FacilityName #" },
          { field: "RecordedDate", title: "Date - Time", format: 'yyyy-mm-dd HH:mm:ss', editor: dateTimeEditor, width: "50px" },
          { field: "Remarks",title:"Remarks",width:"60px"},
        { field: "Volume", title: "Volume", width: "50px" },
        {
            command: [
               {
                   name: "edit", title: "Edit", "template": ""
               },
            ], field: "Actions",title:"Actions", width: "50px"
        }],
 editable: "inline",```
</div>
</div>
</p>

<p><code>datetimepicker</code> editor--</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> function dateTimeEditor(container, options) {
    $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({
                value: $scope.tdate,
                dateInput: true,
                max: new Date(),
                min: $scope.ydate,
                //template: "#= kendo.toString(kendo.parseDate(value), 'yyyy-mm-dd HH:mm:ss') #"

            });
}</code>```

tdate and ydate are defined as--

var today = new Date();
    var yday = today.getDate() - 1;
    var tday = today.getDate();
    var month = today.getMonth();
    var year = today.getFullYear();
    var hour = today.getHours();
    var minute = today.getMinutes();
    var seconds = today.getSeconds();
    $scope.ydate = (new Date(year, month, yday, hour, minute, seconds));
    $scope.tdate = (new Date(year, month, tday, hour, minute, seconds));```

Putting current date in value field is not giving the required output

答:
You can try for this.:
StartDate is the  id of kendoDatePicker, where you want to show the default date:

Html:

```<code><input id="datepickerjQuery">

<script>
    var todayDate = kendo.toString(kendo.parseDate(new Date()), 'MM/dd/yyyy');
    $("#datepickerjQuery").data("kendoDatePicker").value(todayDate);
</script>
</code>```

Body:
I'm working with a kendo grid in which a column consists of kendodatetimepicker.
User will be able to edit date and time for only yesterday and today.

So, when he clicks the edit button on the grid the datetimepicker should first show current date and time as default

My grid looks like this--

columns: [
          { field: "EntryType", title: "Entry Type", width: "50px", editor: $scope.typeDropDownEditor, template: "#=EntryType#" },
          { field: "Chemical", title: "Chemical Name", width: "50px", editor: $scope.chemicalDropDownEditor,template: "#=Chemical.ChemicalName#" },
          { field: "Facility", title: "Facility Name", width: "50px", editor: $scope.facilityDropDownEditor, template: "#=(Facility.FacilityName==null)? '' : Facility.FacilityName #" },
          { field: "RecordedDate", title: "Date - Time", format: 'yyyy-mm-dd HH:mm:ss', editor: dateTimeEditor, width: "50px" },
          { field: "Remarks",title:"Remarks",width:"60px"},
        { field: "Volume", title: "Volume", width: "50px" },
        {
            command: [
               {
                   name: "edit", title: "Edit", "template": ""
               },
            ], field: "Actions",title:"Actions", width: "50px"
        }],
 editable: "inline",

datetimepicker editor--

 function dateTimeEditor(container, options) {
    $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({
                value: $scope.tdate,
                dateInput: true,
                max: new Date(),
                min: $scope.ydate,
                //template: "#= kendo.toString(kendo.parseDate(value), 'yyyy-mm-dd HH:mm:ss') #"

            });
}

tdate and ydate are defined as--

var today = new Date();
    var yday = today.getDate() - 1;
    var tday = today.getDate();
    var month = today.getMonth();
    var year = today.getFullYear();
    var hour = today.getHours();
    var minute = today.getMinutes();
    var seconds = today.getSeconds();
    $scope.ydate = (new Date(year, month, yday, hour, minute, seconds));
    $scope.tdate = (new Date(year, month, tday, hour, minute, seconds));

Putting current date in value field is not giving the required output

Body:
You can try for this.:
StartDate is the  id of kendoDatePicker, where you want to show the default date:

Html:

<input id="datepickerjQuery">

<script>
    var todayDate = kendo.toString(kendo.parseDate(new Date()), 'MM/dd/yyyy');
    $("#datepickerjQuery").data("kendoDatePicker").value(todayDate);
</script>


问:
How to select the same column from multiple table with almost same name in SQL?
I'd like to select a 2 column from lot of table.

Exemple

```<code>Table_2017-01
id   name   value

Table_2017-02
id   name   value

Table_2017-03
id   name   value
</code>```

etc...

My Query would be

```<code>SELECT name, value
FROM Table_2017-01, Table_2017-02, Table_2017-03
</code>```

But I'd like to know if something it's possible like

```<code>SELECT name, value FROM LIKE Table_%
</code>```

I know this last query is not possible and it could be easier for me if a query exist for this problem as I can have a lot of table with just a part of the name different.

答:
It depends on your database. Oracle f.e. has a data dictionary with all tables.
Because I know oracle better than others I use this for the example:

```<code>SELECT TABLE_NAME FROM ALL_TABLES WHERE TABLE_NAME LIKE 'Table_2017-%';
</code>```

Now there are the following ways I sometimes use:

I build a list of selects and fire them into the database:

via Excel (not explained here)

via SQL

SELECT
  'SELECT '''||TABLE_NAME||''' TABLE_NAME, NAME, VALUE FROM '||
  TABLE_NAME
  ||' UNION '
FROM ALL_TABLES WHERE TABLE_NAME LIKE 'Table_2017-%';

Now you can copy the result to your database (dont forget to delete the last "UNION")

via program (python, Lazarus, c# .. whatever, same view is needed)

But pay attention: It is quick and dirty, the column names and types have to match.

Body:
I'd like to select a 2 column from lot of table.

Exemple

Table_2017-01
id   name   value

Table_2017-02
id   name   value

Table_2017-03
id   name   value

etc...

My Query would be

SELECT name, value
FROM Table_2017-01, Table_2017-02, Table_2017-03

But I'd like to know if something it's possible like

SELECT name, value FROM LIKE Table_%

I know this last query is not possible and it could be easier for me if a query exist for this problem as I can have a lot of table with just a part of the name different.

Body:
It depends on your database. Oracle f.e. has a data dictionary with all tables.
Because I know oracle better than others I use this for the example:

SELECT TABLE_NAME FROM ALL_TABLES WHERE TABLE_NAME LIKE 'Table_2017-%';

Now there are the following ways I sometimes use:

I build a list of selects and fire them into the database:

via Excel (not explained here)

via SQL

SELECT
  'SELECT '''||TABLE_NAME||''' TABLE_NAME, NAME, VALUE FROM '||
  TABLE_NAME
  ||' UNION '
FROM ALL_TABLES WHERE TABLE_NAME LIKE 'Table_2017-%';

Now you can copy the result to your database (dont forget to delete the last "UNION")

via program (python, Lazarus, c# .. whatever, same view is needed)

But pay attention: It is quick and dirty, the column names and types have to match.


问:
how to select dynamic data-attribute element in jquery
I have many elements like

```<code><input  tag="data-initial-222" value="" type="checkbox">

<input   tag="data-initial-111" value="" type="checkbox">
</code>```

How can I select all the elements who have this tag "data-initial-*"

Another Question is :

How to select

```<code> <input data-initial="111" type="checkbox">
</code>```

or

```<code> <input data-initial="222" type="checkbox">
</code>```

using data-initial attribute.

答:
console.log($("input[data-initial]").length)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input  tag="data-initial-222" value="" type="checkbox">

<input   data-initial="111" value="" type="checkbox">

<input  data-initial="222" value="" type="checkbox">

<input   data-initial="333" value="" type="checkbox"></code>```

Use starts with selector

Description: Selects elements that have the specified attribute with a value beginning exactly with a given string.

Attribute selector

Description: Selects elements that have the specified attribute, with any value.

Body:
I have many elements like

<input  tag="data-initial-222" value="" type="checkbox">

<input   tag="data-initial-111" value="" type="checkbox">

How can I select all the elements who have this tag "data-initial-*"

Another Question is :

How to select

 <input data-initial="111" type="checkbox">

or

 <input data-initial="222" type="checkbox">

using data-initial attribute.

Body:
console.log($("input[data-initial]").length)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input  tag="data-initial-222" value="" type="checkbox">

<input   data-initial="111" value="" type="checkbox">

<input  data-initial="222" value="" type="checkbox">

<input   data-initial="333" value="" type="checkbox">

Use starts with selector

Description: Selects elements that have the specified attribute with a value beginning exactly with a given string.

Attribute selector

Description: Selects elements that have the specified attribute, with any value.


答:
```<code>$( "input[tag*='data-initial']" )
</code>```

Title: how to select dynamic data-attribute element in jquery

Body: $( "input[tag*='data-initial']" )


问:
How to make a 'struct' Nullable by definition?
```<code>struct AccountInfo
{
   String Username;
   String Password;
}
</code>```

now if I want to have a Nullable instance I should write:

```<code>Nullable<AccountInfo> myAccount = null;
</code>```

But I want make the struct Nullable by nature and it can be used like this (without use of Nullable<T>):

```<code>AccountInfo myAccount = null;
</code>```

答:
When you declare it, declare it with a "?" if you prefer</p>

```<code>AccountInfo? myAccount = null;
</code>```

Body:
struct AccountInfo
{
   String Username;
   String Password;
}

now if I want to have a Nullable instance I should write:

Nullable<AccountInfo> myAccount = null;

But I want make the struct Nullable by nature and it can be used like this (without use of Nullable<T>):

AccountInfo myAccount = null;

Body:
When you declare it, declare it with a "?" if you prefer

AccountInfo? myAccount = null;


问:
how to stable hover effect even after mouse out
how to set my hover effect stable even after mouse out ???
    code is working fine but after mouse out div element comes to its
    original state ??

html

```<code><div id="sme"></div>
</code>```

css

```<code>#sme{
    width: 400px;
    height: 400px;
    border: 20px solid #06c999;
/* Rotate */
}
#sme:hover{
transition: all 1.9s ease;
 -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    transform: rotate(180deg);

}
</code>```

答:
Something to consider is to use the animation play state. Side effect however is when you remove the mouse while the animation hasn't finished, the animation will pause.

#sme {
  width: 400px;
  height: 400px;
  border: 20px solid #06c999;
  animation: rotatebox 2s ease forwards;
  animation-play-state: paused;
}

#sme:hover {
  animation-play-state: running;
}

@keyframes rotatebox {
  100% {
    transform: rotate(180deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="sme">A</div></code>```

Body:
how to set my hover effect stable even after mouse out ???
    code is working fine but after mouse out div element comes to its
    original state ??

html

css

#sme{
    width: 400px;
    height: 400px;
    border: 20px solid #06c999;
/* Rotate */
}
#sme:hover{
transition: all 1.9s ease;
 -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    transform: rotate(180deg);

}

Body:
Something to consider is to use the animation play state. Side effect however is when you remove the mouse while the animation hasn't finished, the animation will pause.

#sme {
  width: 400px;
  height: 400px;
  border: 20px solid #06c999;
  animation: rotatebox 2s ease forwards;
  animation-play-state: paused;
}

#sme:hover {
  animation-play-state: running;
}

@keyframes rotatebox {
  100% {
    transform: rotate(180deg);
  }
}

<div id="sme">A</div>


问:
Node js creating different session id for each request
Using express-session and storing session in files. However every request it is creating new session id and new file is getting created.

Here is the code which i am using to create the session.

```<code>app.use(session({ secret: 'keyboard cat',
  resave: false,store: new FSStore(options),
  saveUninitialized: false ,
  cookie: { maxAge: 1000,secure: false,httpOnly: true }
}))
</code>```

However i want it should create a single session id for each user or until session expires.

答:
My issue was with MaxAge which I set it 1000 milliseconds i.e 1 sec. Therefore it was creating a new session id everytime. I have set it to 1 hour, it works fine.

Here is the complete code

```<code>var express = require('express');
var app = express();
var session = require('express-session');
var FileStore = require('session-file-store')(session);

app.use(session({ secret: 'keyboard cat',
    resave: false,
    store: new FileStore,
    saveUninitialized: false ,
    cookie: { maxAge: 3600000,secure: false, httpOnly: true }
  })
);

app.get('/', function (req, res) {
  if (req.session.views) {
    req.session.views++;
    res.setHeader('Content-Type', 'text/html');
    res.write('<p>views: ' + req.session.views + '</p>');
    res.end();
  } else {
    req.session.views = 1;
    res.end('Welcome to the file session demo. Refresh page!');
  }
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});
</code>```

Body:
Using express-session and storing session in files. However every request it is creating new session id and new file is getting created.

Here is the code which i am using to create the session.

app.use(session({ secret: 'keyboard cat',
  resave: false,store: new FSStore(options),
  saveUninitialized: false ,
  cookie: { maxAge: 1000,secure: false,httpOnly: true }
}))

However i want it should create a single session id for each user or until session expires.

Body:
My issue was with MaxAge which I set it 1000 milliseconds i.e 1 sec. Therefore it was creating a new session id everytime. I have set it to 1 hour, it works fine.

Here is the complete code

var express = require('express');
var app = express();
var session = require('express-session');
var FileStore = require('session-file-store')(session);

app.use(session({ secret: 'keyboard cat',
    resave: false,
    store: new FileStore,
    saveUninitialized: false ,
    cookie: { maxAge: 3600000,secure: false, httpOnly: true }
  })
);

app.get('/', function (req, res) {
  if (req.session.views) {
    req.session.views++;
    res.setHeader('Content-Type', 'text/html');
    res.write('<p>views: ' + req.session.views + '</p>');
    res.end();
  } else {
    req.session.views = 1;
    res.end('Welcome to the file session demo. Refresh page!');
  }
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});


问:
How to set different background color of every three html table rows in alternate
Suppose I have two HTML tables named table1 and table2. If I want to have different background of every alternative three rows of table2, how can I achieve that using CSS? For example set background of first 3 rows as blue, then another 3 rows as green, again another 3 rows as blue, again another 3 rows as green and so on. Basically I want two different background colors for every three rows in alternate. I found CSS styling for even and odd rows, or every nth rows, but not for this case. I have attached the screenshot of sample table. Rather than hard coding in individual row like in this code, I want to do it in CSS styling.

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 1px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="table2">
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
</table></code>```

Any help is appreciated]1

答:
You can use "nth-child" to achieve this.

```<code>tr:nth-child(6n+1),
tr:nth-child(6n+2),
tr:nth-child(6n+3) {
  background: #dddddd;
}
</code>```

Try with below snippet

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 1px;
}
tr:nth-child(6n+1),
tr:nth-child(6n+2),
tr:nth-child(6n+3) {
  background: #dddddd;
}
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="table2">
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td >Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td >Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td >Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
  <tr>
    <td >Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td >Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td >Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
</table></code>```

Body:
Suppose I have two HTML tables named table1 and table2. If I want to have different background of every alternative three rows of table2, how can I achieve that using CSS? For example set background of first 3 rows as blue, then another 3 rows as green, again another 3 rows as blue, again another 3 rows as green and so on. Basically I want two different background colors for every three rows in alternate. I found CSS styling for even and odd rows, or every nth rows, but not for this case. I have attached the screenshot of sample table. Rather than hard coding in individual row like in this code, I want to do it in CSS styling.

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 1px;
}

    Company
    Contact
    Country

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

    Island Trading
    Helen Bennett
    UK

    Laughing Bacchus Winecellars
    Yoshi Tannamuri
    Canada

    Magazzini Alimentari Riuniti
    Giovanni Rovelli
    Italy

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

    a
    b
    c

    a
    b
    c

    a
    b
    c

Any help is appreciated]1

Body:
You can use "nth-child" to achieve this.

tr:nth-child(6n+1),
tr:nth-child(6n+2),
tr:nth-child(6n+3) {
  background: #dddddd;
}

Try with below snippet

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 1px;
}
tr:nth-child(6n+1),
tr:nth-child(6n+2),
tr:nth-child(6n+3) {
  background: #dddddd;
}

<table id="table2">
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td >Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td >Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td >Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
  <tr>
    <td >Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td >Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td >Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
</table>


问:
How to create empty data table using PrimeNG
I am creating a UI that allows users to input data in batches.

Similar to an Excel spreadsheet but the columns are already fixed.

I'm already using PrimeNG DataTable for other parts of my web app, and I would like to continue using it for the aforementioned feature if possible.

Thanks.

答:
I figured it out.

My initial code was correct but because there was an issue when the backing array of the data table was being updated via push.

I had to create a separate array with the empty objects and assign it to the backing array.


问:
Webpack 2 with historyApiFallback Not Working
I keep getting Cannot GET /task I tried to modify my webpack with solutions I found here but I still get it.

```<code>var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: './src/app.js',
    output: {
        path: __dirname + '/dist',
        filename: 'app.bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.s?css$/,
                use: ['style-loader', 'css-loader', 'sass-loader']
            }, {
                test: /\.js$/,
                exclude: /node_modules/,
                use: 'babel-loader'
            }, {
                test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
                loader: 'file-loader?name=fonts/[name].[ext]'
            }
        ]
    },
    devServer: {
        historyApiFallback: {
            index: '/index.html'
        },
        stats: true,
        inline: true,
        progress: true
    }
    plugins: [new HtmlWebpackPlugin({template: './src/index.html'})]
}
</code>```

答:
I think client gets index.html only when path is /.

Try to use this setting.

```<code>devServer: {
    historyApiFallback: true
}
</code>```

Body:
I keep getting Cannot GET /task I tried to modify my webpack with solutions I found here but I still get it.

var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: './src/app.js',
    output: {
        path: __dirname + '/dist',
        filename: 'app.bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.s?css$/,
                use: ['style-loader', 'css-loader', 'sass-loader']
            }, {
                test: /\.js$/,
                exclude: /node_modules/,
                use: 'babel-loader'
            }, {
                test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
                loader: 'file-loader?name=fonts/[name].[ext]'
            }
        ]
    },
    devServer: {
        historyApiFallback: {
            index: '/index.html'
        },
        stats: true,
        inline: true,
        progress: true
    }
    plugins: [new HtmlWebpackPlugin({template: './src/index.html'})]
}

Body:
I think client gets index.html only when path is /.

Try to use this setting.

devServer: {
    historyApiFallback: true
}


问:
why android is built on a VM (Dalvik)
I am curious to know what made google choose to develop android's framework on java VM.

In the process of writing code for android for nearly 6 months now, I observed that running code on a VM in a resource limited platform is really slow. There is a lot of overhead involved. I know that java is portable etc etc, is it not possible at all to use native languages and get both performance and features offered by a VM ? For performance oriented applications one still ends up writing native code and wrap it with JNI,

So why did google choose this particular stack :

Arm based core (understandable, ARM is the best for mobile devices)

Linux (Open source)

Java VM (My question)

EDIT : I know java - JVM runs on par with C++ applications on my server, but not on android.
With respect to android its not the case - As a matter of my experience, a C++ code wrapped with JNI runs far faster than java code (note I have even checked with exact same code from a static block in java) I will agree with your answer on any other platform.

答: I think the key, is to not think about the Java VM in the same sense that you think of for Destkop or Server virtualization -- they're very different. At the most basic level, the Java VM (in this case Dalvik) is simply a translation layer between the bytecode generated by the "compiler" into native machine code. It is a virtual machine -- but it doesn't have the same overhead as say, running Ubuntu in VirtualBox.

Title: why android is built on a VM (Dalvik)


问:
i want to update state field but drop down (State field) is not updating but other fields are updating. codeigniter
[Here is code of field state that i want to update, i am new and i really appreciate you  ]</p>

```<code><div class="">
                        <label class="control-label" >State</label>
                        <select name="state_id" class="form-control col-sm-5" >
                            <option value="" >Select State...</option>
                            <?php foreach ($all_state as $v_state) : ?>
                                <option value="<?php echo $v_state->state_id ?>" <?php
                                if (!empty($employee_info->state_id)) {
                                    echo $v_state->state_id == $employee_info->state_id ? 'selected' : '';
                                }
                                ?>><?php echo $v_state->name ?></option>
                                    <?php endforeach; ?>
                        </select>
                    </div>
</code>```

答:
Try this my be help you..    </p>

```<code>          <label class="control-label" >State</label>
                    <select name="state_id" class="form-control col-sm-5" >
                     <option value="" >Select State...</option>
                    <?php foreach ($all_state as $v_state) : ?>
                      <option value="<?php echo $v_state->state_id ?>" <?php  if($v_state->state_id == $employee_info->state_id){echo "selected";}?>> <?php echo $v_state->name; ?></option>
                    <?php endforeach; ?>

                    </select>
</code>```

Body:
[Here is code of field state that i want to update, i am new and i really appreciate you  ]

                        State
                        <select name="state_id" class="form-control col-sm-5" >
                            <option value="" >Select State...</option>
                            <?php foreach ($all_state as $v_state) : ?>
                                <option value="<?php echo $v_state->state_id ?>" <?php
                                if (!empty($employee_info->state_id)) {
                                    echo $v_state->state_id == $employee_info->state_id ? 'selected' : '';
                                }
                                ?>><?php echo $v_state->name ?></option>
                                    <?php endforeach; ?>
                        </select>

Body:
Try this my be help you..

          <label class="control-label" >State</label>
                    <select name="state_id" class="form-control col-sm-5" >
                     <option value="" >Select State...</option>
                    <?php foreach ($all_state as $v_state) : ?>
                      <option value="<?php echo $v_state->state_id ?>" <?php  if($v_state->state_id == $employee_info->state_id){echo "selected";}?>> <?php echo $v_state->name; ?></option>
                    <?php endforeach; ?>

                    </select>


问:
Material animation in android
Can any one help me with animations in android I am learning the animation through android developer website but I am also looking for a good tutorial for that, What I am looking for is something similar any help will be appriciated</p>

答:
You  can use following library for  animation

Material-Animations

used for three main things:

Animate activity layout content when transitioning from one activity to another.

Animate shared elements (Hero views) in transitions between activities.

Animate view changes within same activity

EasyAndroidAnimations

Easy Android Animations is an animation library that aims to make android animations easier, with 50+ builtin animations, it allows you to introduce many complex animation effects in your application with one or two lines of code

Facebook pop animation

Pop is an extensible animation engine for iOS, tvOS, and OS X

Material

MaterialLibrary is an Open Source Android library that back-port Material Design components to pre-Lolipop Android.

AndroidViewAnimations

View shake animation.

View animator

A fluent Android animation library,Animate multiple view from one method

AndroidViewAnimation

AndroidViewAnimation, which is an animation collection, to help you make animation easier.

Title: Material animation in android


问:
NO INPUT FILE SPECIFIED - Codeigniter on IIS
I am stuck with Codeigniter v2.2 on IIS. I have PHP installed and configured and when I write plain PHP code, it works including the hyperlinks, but when I try to access any method of the CI controller, I get the error message "No input file specified". Below is my web.config file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="MyRule">
                    <match url="^(.*)$" />
                    <conditions>
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php/{R:1}" appendQueryString="false" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>
</code>```

My config.php settings are as follows:

```<code>$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';
</code>```

I don't understand what I am doing wrong? Please advise.

答:
I have Changed Settings in config.php

```<code>$config['index_page'] = 'index.php?';
$config['uri_protocol'] = 'QUERY_STRING';
</code>```

It worked for me but url is now like http://www.example.com/Admin/index.php?/Login

It is containing index.php? , anyway site is working now. I'll figure out the url problem also.

Body:
I am stuck with Codeigniter v2.2 on IIS. I have PHP installed and configured and when I write plain PHP code, it works including the hyperlinks, but when I try to access any method of the CI controller, I get the error message "No input file specified". Below is my web.config file:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="MyRule">
                    <match url="^(.*)$" />
                    <conditions>
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php/{R:1}" appendQueryString="false" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

My config.php settings are as follows:

$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';

I don't understand what I am doing wrong? Please advise.

Body:
I have Changed Settings in config.php

$config['index_page'] = 'index.php?';
$config['uri_protocol'] = 'QUERY_STRING';

It worked for me but url is now like http://www.example.com/Admin/index.php?/Login

It is containing index.php? , anyway site is working now. I'll figure out the url problem also.


问:
Maven not downloading dependencies in Eclipse
I am setting up a project in eclipse . This projects builds successfully through command line(all mvn commands like mvn package, mvn compile, mvn clean install) work perfectly fine. While setting up this project on STS or Eclipse . I see some of the dependencies are not getting downloaded even though they are present in pom.xml. However, searching them in the maven repository and downloading the jar to my local computer and then adding them to build path makes it work on Eclipse.

Is there anything that we need to do to eclipse to make sure it downloads all the dependencies from the repository.

My POM:

```<code><dependency>
    <groupId>org.apache.bookkeeper</groupId>
    <artifactId>bookkeeper-server-compat410</artifactId>
    <version>4.1.0</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.apache.bookkeeper</groupId>
            <artifactId>bookkeeper-server</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.bookkeeper</groupId>
    <artifactId>bookkeeper-server-compat420</artifactId>
    <version>4.2.0</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.apache.bookkeeper</groupId>
            <artifactId>bookkeeper-server</artifactId>
        </exclusion>
    </exclusions>
</dependency>
</code>```

Both these artifacts were not downloaded for eclipse and there jars found http://mvnrepository.com/artifact/org.apache.bookkeeper/bookkeeper-server-compat410/4.1.0 and http://mvnrepository.com/artifact/org.apache.bookkeeper/bookkeeper-server-compat420/4.2.0 were not present in the folder for MavenDependencies and were subsequently giving errors in Eclipse.

However manually adding them to the build path created a new folder (Reference Library) and resolved the Eclipse Errors . Why did Eclipse not download and import these dependencies by themselves from the maven repository ?? Is it a bug in Eclipse or some problem from my side . Please help.

答: In my case, I had unchecked Build automatically. Checking it again started downloading the jars.

Body:
I am setting up a project in eclipse . This projects builds successfully through command line(all mvn commands like mvn package, mvn compile, mvn clean install) work perfectly fine. While setting up this project on STS or Eclipse . I see some of the dependencies are not getting downloaded even though they are present in pom.xml. However, searching them in the maven repository and downloading the jar to my local computer and then adding them to build path makes it work on Eclipse.

Is there anything that we need to do to eclipse to make sure it downloads all the dependencies from the repository.

My POM:

<dependency>
    <groupId>org.apache.bookkeeper</groupId>
    <artifactId>bookkeeper-server-compat410</artifactId>
    <version>4.1.0</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.apache.bookkeeper</groupId>
            <artifactId>bookkeeper-server</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.bookkeeper</groupId>
    <artifactId>bookkeeper-server-compat420</artifactId>
    <version>4.2.0</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.apache.bookkeeper</groupId>
            <artifactId>bookkeeper-server</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Both these artifacts were not downloaded for eclipse and there jars found http://mvnrepository.com/artifact/org.apache.bookkeeper/bookkeeper-server-compat410/4.1.0 and http://mvnrepository.com/artifact/org.apache.bookkeeper/bookkeeper-server-compat420/4.2.0 were not present in the folder for MavenDependencies and were subsequently giving errors in Eclipse.

However manually adding them to the build path created a new folder (Reference Library) and resolved the Eclipse Errors . Why did Eclipse not download and import these dependencies by themselves from the maven repository ?? Is it a bug in Eclipse or some problem from my side . Please help.


问:
Detecting Chrome browser with AJAX
I use Sys.Browser.name for borwser detection, but Chrome detected as safari.

答:
A quick google search turned up this page: http://davidwalsh.name/detecting-google-chrome-javascript

Basically, read the full user-agent and find the string 'chrome':

```<code>var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
</code>```

Title: Detecting Chrome browser with AJAX

Body:
A quick google search turned up this page: http://davidwalsh.name/detecting-google-chrome-javascript

Basically, read the full user-agent and find the string 'chrome':

var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;


问:
Pandas Assign Lambda Function
I have a DataFrame which has an open time and a close time and I am trying to calculate the difference in milliseconds.

My code is currently like this

```<code>df = df.assign(Latency=lambda d: d.CloseTimeStamp - d.CreationTimeStamp)
df.Latency = df.apply(lambda d: d.Latency.total_seconds() * 1000., axis=1)
</code>```

However, I'd like to know why I can't do as a one-liner like so

```<code>df = df.assign(Latency=lambda d: (d.CloseTimeStamp - d.CreationTimeStamp).total_seconds() * 1000.)
</code>```

When I try the latter I get AttributeError: 'Series' object has no attribute 'total_seconds'

答:
Total seconds is inside the .dt attribute, so this should work:

```<code>df = df.assign(Latency=lambda d: (d.CloseTimeStamp - d.CreationTimeStamp).dt.total_seconds() * 1000.)
</code>```

Having said so, there's no need for a lambda function:

```<code>df = df.assign(Latency=(df.CloseTimeStamp - df.CreationTimeStamp).dt.total_seconds() * 1000.)
</code>```

is much faster.

A further remark on efficiency: df.assign() builds a completely new dataframe object; if you're intending to assign this object back onto df, you're better off modifying df in-place:

```<code>df['Latency'] = (df.CloseTimeStamp - df.CreationTimeStamp).dt.total_seconds() * 1000.
</code>```

Title: Pandas Assign Lambda Function

Body:
I have a DataFrame which has an open time and a close time and I am trying to calculate the difference in milliseconds.

My code is currently like this

df = df.assign(Latency=lambda d: d.CloseTimeStamp - d.CreationTimeStamp)
df.Latency = df.apply(lambda d: d.Latency.total_seconds() * 1000., axis=1)

However, I'd like to know why I can't do as a one-liner like so

df = df.assign(Latency=lambda d: (d.CloseTimeStamp - d.CreationTimeStamp).total_seconds() * 1000.)

When I try the latter I get AttributeError: 'Series' object has no attribute 'total_seconds'

Body:
Total seconds is inside the .dt attribute, so this should work:

df = df.assign(Latency=lambda d: (d.CloseTimeStamp - d.CreationTimeStamp).dt.total_seconds() * 1000.)

Having said so, there's no need for a lambda function:

df = df.assign(Latency=(df.CloseTimeStamp - df.CreationTimeStamp).dt.total_seconds() * 1000.)

is much faster.

A further remark on efficiency: df.assign() builds a completely new dataframe object; if you're intending to assign this object back onto df, you're better off modifying df in-place:

df['Latency'] = (df.CloseTimeStamp - df.CreationTimeStamp).dt.total_seconds() * 1000.


问:
How to get next param in linux shell command params?
I'm writing a shell script of this command:

```<code>ovs-dump -i dpdkb2 [-d in] [-p tcp] [host 192.168.102.2][port 80] [-w /test.pcap]
</code>```

For '-w' options, I want to process '/test.pcap' into '$PWD/test.pcap', so I write script like this:

```<code>for arg
do
    case $arg in
        -h | --help)
            ...
            ;;
        -w )
            echo "OPTARG=$OPTARG"
            ;;
        ?)
            ;;
    esac
done
</code>```

As we see, I want to get '/test.pcap' by '$OPTARG', but is none. So my question is how to get 'test.pcap' in my script?

When I use 'getopts' like this:

```<code>while getopts "w:h:" arg
    do
        case $arg in
            -h | --help)
                ...
                ;;
            -w )
                echo "OPTARG=$OPTARG"
                ;;
            ?)
                ;;
        esac
    done
</code>```

When I run sh ovs-dump -w a.pcap, I got error: '/usr/local/share/openvswitch/scripts/gangyewei-ovs-dump: line 68: -w: command not found'.

And the output of 'echo "OPTARG=$OPTARG"' is 'OPTARG='.

It's also not work, what should I do? Thank you~

答:
You can have your script as this:

```<code>OPTIND=-1   # rest OPTIND if it has been set earlier

# start getopts loop
while getopts "w:h:" arg; do
    case $arg in
        h | --help)
            ...
        ;;
        w)
            echo "OPTARG=$OPTARG"
        ;;
        ?)

        ;;
    esac;
done
</code>```

Then run it as:

```<code>bash ./ovs-dump -w a.pcap
</code>```

Body:
I'm writing a shell script of this command:

ovs-dump -i dpdkb2 [-d in] [-p tcp] [host 192.168.102.2][port 80] [-w /test.pcap]

For '-w' options, I want to process '/test.pcap' into '$PWD/test.pcap', so I write script like this:

for arg
do
    case $arg in
        -h | --help)
            ...
            ;;
        -w )
            echo "OPTARG=$OPTARG"
            ;;
        ?)
            ;;
    esac
done

As we see, I want to get '/test.pcap' by '$OPTARG', but is none. So my question is how to get 'test.pcap' in my script?

When I use 'getopts' like this:

while getopts "w:h:" arg
    do
        case $arg in
            -h | --help)
                ...
                ;;
            -w )
                echo "OPTARG=$OPTARG"
                ;;
            ?)
                ;;
        esac
    done

When I run sh ovs-dump -w a.pcap, I got error: '/usr/local/share/openvswitch/scripts/gangyewei-ovs-dump: line 68: -w: command not found'.

And the output of 'echo "OPTARG=$OPTARG"' is 'OPTARG='.

It's also not work, what should I do? Thank you~

Body:
You can have your script as this:

OPTIND=-1   # rest OPTIND if it has been set earlier

# start getopts loop
while getopts "w:h:" arg; do
    case $arg in
        h | --help)
            ...
        ;;
        w)
            echo "OPTARG=$OPTARG"
        ;;
        ?)

        ;;
    esac;
done

Then run it as:

bash ./ovs-dump -w a.pcap


问:
Viewing database file of my android application in Redmi phones
My android application is not working in REDMI phones. Infact not sure because sometimes it stores the data and sometimes not. It gives unexpected results, i can able to access my application in other phones correctly.</p>

答:
First of all, see you logcat if nothing suspicious found then For debugging your database query take a look at this awesome open source library called Android Debug database
https://github.com/amitshekhariitbhu/Android-Debug-Database

This library operate through your browser and also give access to your app's shared preferences


问:
Undefined is not an object in React Native project
I'm trying to open existing React Native project in the emulator on Windows 10, but it throws this error:

```<code>undefined is not an object (evaluating '_reactNativeParse2.default.Object.extend')
</code>```

I'm using 0.45.1 version of React Native. Backend is Parse Server. Why is this happening?

答:
Found this on Github issues. Try this for now:</p>

```<code>edit package.json -> Replace 0.45.1 with 0.43.4 for react-native

'rm -rf node_modules' //get rid of previous module installations based on 0.45.1
npm install
react-native link
react-native run-android // but in separate window be running 'npm start' first.
</code>```

Body:
I'm trying to open existing React Native project in the emulator on Windows 10, but it throws this error:

undefined is not an object (evaluating '_reactNativeParse2.default.Object.extend')

I'm using 0.45.1 version of React Native. Backend is Parse Server. Why is this happening?

Body:
Found this on Github issues. Try this for now:

edit package.json -> Replace 0.45.1 with 0.43.4 for react-native

'rm -rf node_modules' //get rid of previous module installations based on 0.45.1
npm install
react-native link
react-native run-android // but in separate window be running 'npm start' first.


问:
Make a whole div clickable in order to launch a _blank document
How can I write the _blank statement in this location.href call?

```<code>  <div onclick="location.href='http://www.test.com';" style="display:block; height:40px; width:100px; cursor:pointer;"></div>
</code>```

Please note: I need to keep the div and treat it as a href container.

When someone clicks it should open a new browser window, not a popup box.

答: Use window.open.</p>

Body:
How can I write the _blank statement in this location.href call?

Please note: I need to keep the div and treat it as a href container.

When someone clicks it should open a new browser window, not a popup box.

Body: Use window.open.


问:
Detect change in each object of an array. Typescript/Angular 2
I have a person array which I displayed in a primeng datatable. Each object has these fields (firstName, lastName and age). Each field corresponds to a column in a table with an additional column that displays the status of each object. The status indicates if the object/row in the table has change. There are two status "Object Change/Not Change"

```<code><p-dataTable [value]="persons" [editable]="true"  resizableColumns="true" reorderableColumns="true">
    <p-column header="Status">
      <ng-template pTemplate="body">
         <span [hidden]=true>Object Change</span>
       <span >Not Change</span>
      </ng-template>
    </p-column>
    <p-column field="firstName" header="First Name" [editable]="true"></p-column>
    <p-column field="lastName" header="Last Name" [editable]="true"></p-column>
    <p-column field="age" header="Age" [editable]="true">
      <ng-template let-col let-car="rowData" pTemplate="editor">
        <select class="form-control" [(ngModel)]="car[col.field]">
          <option [value]=12>12</option>
          <option [value]=14>14</option>
          <option [value]=23>23</option>
        </select>
      </ng-template>
    </p-column>
</p-dataTable>

<p>{{persons | json}}</p>
</code>```

I set the primeng datatable column editable to true so that the user can edit the data inside the table. Now, I want to detect if each object has changed. If the object has changed I want the "status" column be set to "Object change". I want to apply this condition in each object in the array. Is there a way to detect the change for each row/object in the array.I createda plunkr for this. http://plnkr.co/edit/x8Sdgz?p=preview

答:
a possible solution is to replace

```<code>[(ngModel)]="car[col.field]"
</code>```

by

```<code>[ngModel]="car[col.field]" (ngModelChange)="onCarChange($event)"
</code>```

this way you can attach any logic you want

Body:
I have a person array which I displayed in a primeng datatable. Each object has these fields (firstName, lastName and age). Each field corresponds to a column in a table with an additional column that displays the status of each object. The status indicates if the object/row in the table has change. There are two status "Object Change/Not Change"

      <ng-template pTemplate="body">
         Object Change
       Not Change
      </ng-template>

      <ng-template let-col let-car="rowData" pTemplate="editor">
        <select class="form-control" [(ngModel)]="car[col.field]">
          <option [value]=12>12</option>
          <option [value]=14>14</option>
          <option [value]=23>23</option>
        </select>
      </ng-template>

{{persons | json}}

I set the primeng datatable column editable to true so that the user can edit the data inside the table. Now, I want to detect if each object has changed. If the object has changed I want the "status" column be set to "Object change". I want to apply this condition in each object in the array. Is there a way to detect the change for each row/object in the array.I createda plunkr for this. http://plnkr.co/edit/x8Sdgz?p=preview

Body:
a possible solution is to replace

[(ngModel)]="car[col.field]"

by

[ngModel]="car[col.field]" (ngModelChange)="onCarChange($event)"

this way you can attach any logic you want


问:
Generate a list of existing functions across multiple files in C
Due to paperwork that has to be filled out, I need to know how many functions exist in an entire C project.

The project is split across multiple folders, so ideally what I am looking for is something where you can type in:

```<code>FindAllTheFunctions --recursive /path/to/folder
</code>```

And the result is written something like:

```<code>/path.../filename: int foo(float bar)
.
.
.
/path.../final/filename: double foo2(int bar2)
</code>```

How could I get results of this nature?

Many thanks!

答:
Moving/expanding from the comments, a slightly more general one-liner:

```<code>ctags -f - -R | cut -s -f 4- | grep -P '(^|\t)f($|\t)' | wc -l
</code>```

ctags -R parses (... mostly...) recursively the supported files in the current directory; -f - redirects its output to stdout instead of writing a tags file;

we use cut to only extract the fields we are interested in;

The tags file format is made of fields separated by tabs (so the default delimiters for cut are already ok); the first three fields have a fixed meaning and are not of our interest, while the ones that follow are "extended fields", where we are looking for a single f that indicates that the row refers to a function.

-s matches only lines with delimiters (= skip garbage); -f 4- outputs only from the fourth field to the last.

we use grep to look for our lonely f; the order of "extended fields" is not guaranteed - and in facts, when calling ctags over a C++ project I saw that extra fields besides f are added (class: fields in particular).

-P uses PCRE regexes (just because it's easier to look for a tab character, egrep would suffice otherwise); (^|\t)f($|\t) looks for an f either surrounded by our separators (tabs) or by the start/end of line;

wc -l counts the resulting lines; the result should be the number of function definitions.

Body:
Due to paperwork that has to be filled out, I need to know how many functions exist in an entire C project.

The project is split across multiple folders, so ideally what I am looking for is something where you can type in:

FindAllTheFunctions --recursive /path/to/folder

And the result is written something like:

/path.../filename: int foo(float bar)
.
.
.
/path.../final/filename: double foo2(int bar2)

How could I get results of this nature?

Many thanks!

Body:
Moving/expanding from the comments, a slightly more general one-liner:

ctags -f - -R | cut -s -f 4- | grep -P '(^|\t)f($|\t)' | wc -l

ctags -R parses (... mostly...) recursively the supported files in the current directory; -f - redirects its output to stdout instead of writing a tags file;

we use cut to only extract the fields we are interested in;

The tags file format is made of fields separated by tabs (so the default delimiters for cut are already ok); the first three fields have a fixed meaning and are not of our interest, while the ones that follow are "extended fields", where we are looking for a single f that indicates that the row refers to a function.

-s matches only lines with delimiters (= skip garbage); -f 4- outputs only from the fourth field to the last.

we use grep to look for our lonely f; the order of "extended fields" is not guaranteed - and in facts, when calling ctags over a C++ project I saw that extra fields besides f are added (class: fields in particular).

-P uses PCRE regexes (just because it's easier to look for a tab character, egrep would suffice otherwise); (^|\t)f($|\t) looks for an f either surrounded by our separators (tabs) or by the start/end of line;

wc -l counts the resulting lines; the result should be the number of function definitions.


问:
export data from a xml file on sharepoint to sql server using ssis
I have a xml file sitting in a folder which is in a document library on a page on sharepoint. I am trying to extract data from the xml file to a table using SSIS packages.

I have tried using Listadapters for sharepoint and I don't think that works to export data from a file on sharepoint library (maybe only for lists).

I have also tried using HTTP connection manager to connect to the sharepoint online. But it keeps giving me an error saying "connection is forbidden (403). I have provided the appropriate credentials.

This is my first time and any kind of direction would be appreciated.

答:
Use the 'copy link' feature in sharepoint to generate a URL with authentication.

Use the 'execute process task' to download the file using powershell

Import the file to SQL server using an 'xml source' connection found inside the data flow under 'other sources'.


问:
Not showing the Modal
I want to show a notification modal when i submit a form.but unfortunately the modal is not popping up here is the code

$("#submitmodalRetailer").submit(function() {
  var FirstName = $('#FirstNameRetailer').val();
  var LastName = $('#LastNameRetailer').val();
  var QRCodeRetailer = $('#QRCodeRetailer').val();
  var prefixNumberRetailers = $('#prefixNumberRetailer').val();
  var Retailer7Digits = $('#Retailer7Digit').val();
  $.ajax({
    type: "POST",
    url: "addRetailer.php",
    data: $('form.form-modal-retailer').serialize(),
    success: function(msg) {
      $("#RetailerAdd").modal('hide');
      location.reload();
      if (msg == 'Valid') {
        $("#RetailerAddshow").modal('show');
      } else if (msg == 'AlreadyExists') {
        $("#BarcodeExists").modal();
      } else if (msg == 'Invalid') {
        alert('Your Barcode number is invalid. \n User only 100001 to 199999')
      }
    },
    error: function() {
      alert("failure");
    }
  });
  return false;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

答:
You may remove

```<code>location.reload();
</code>```

in Ajax success method to avoid page reload that hinder popup from showing up.

and also you can add

```<code>e.preventDefault();
</code>```

in the button click event to prevent the form submit to cause reloading that may also hinder popup from showing.
and you need to add e as a parameter to event.

$("#submitmodalRetailer").submit(function(e) {.
  e.preventDefault();
  var FirstName = $('#FirstNameRetailer').val();
  var LastName = $('#LastNameRetailer').val();
  var QRCodeRetailer = $('#QRCodeRetailer').val();
  var prefixNumberRetailers = $('#prefixNumberRetailer').val();
  var Retailer7Digits = $('#Retailer7Digit').val();
  $.ajax({
    type: "POST",
    url: "addRetailer.php",
    data: $('form.form-modal-retailer').serialize(),
    success: function(msg) {
      $("#RetailerAdd").modal('hide');
      // location.reload();
      if (msg == 'Valid') {
        $("#RetailerAddshow").modal('show');
      } else if (msg == 'AlreadyExists') {
        $("#BarcodeExists").modal();
      } else if (msg == 'Invalid') {
        alert('Your Barcode number is invalid. \n User only 100001 to 199999')
      }
    },
    error: function() {
      alert("failure");
    }
  });
  return false;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Title: Not showing the Modal

Body:
You may remove

location.reload();

in Ajax success method to avoid page reload that hinder popup from showing up.

and also you can add

e.preventDefault();

in the button click event to prevent the form submit to cause reloading that may also hinder popup from showing.
and you need to add e as a parameter to event.

$("#submitmodalRetailer").submit(function(e) {.
  e.preventDefault();
  var FirstName = $('#FirstNameRetailer').val();
  var LastName = $('#LastNameRetailer').val();
  var QRCodeRetailer = $('#QRCodeRetailer').val();
  var prefixNumberRetailers = $('#prefixNumberRetailer').val();
  var Retailer7Digits = $('#Retailer7Digit').val();
  $.ajax({
    type: "POST",
    url: "addRetailer.php",
    data: $('form.form-modal-retailer').serialize(),
    success: function(msg) {
      $("#RetailerAdd").modal('hide');
      // location.reload();
      if (msg == 'Valid') {
        $("#RetailerAddshow").modal('show');
      } else if (msg == 'AlreadyExists') {
        $("#BarcodeExists").modal();
      } else if (msg == 'Invalid') {
        alert('Your Barcode number is invalid. \n User only 100001 to 199999')
      }
    },
    error: function() {
      alert("failure");
    }
  });
  return false;
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
ASP.NET: How to get FormsAuthenticationTicket object when authentication expired
I'm trying to check the Expired property of the user's current FormsAuthenticationTicket to see if the authentication period has expired. But when the period has expired, I'm never able to get enough information to even create the ticket to check. I've tried this:

```<code>FormsIdentity id = (FormsIdentity)User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
</code>```

But User is null when the authentication period has expired. So that won't work. I've tried this:

```<code>HttpCookie authCookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
</code>```

But the Forms Cookie is gone when the authentication period has expired, meaning authCookie will be null. So that doesn't work.

Is there any way to actually get the FormsAuthenticationTicket object when the authentication period has expired? There must be, because there's an "Expired" property in the object. What am I missing?

Thanks.

答: An expired cookie is left out of the headers by the client browser. So there is no code-behind method of retrieving it since the client will never give it to you. It might be possible to use javascript cookies to retrieve the raw cookie data and put it into a post header or AJAX call for some purpose, but I believe the javascript cookie mechanism has the same expiration restrictions as the browser. Expired cookies are no longer valid, and thus not accessible.</p>

Body:
I'm trying to check the Expired property of the user's current FormsAuthenticationTicket to see if the authentication period has expired. But when the period has expired, I'm never able to get enough information to even create the ticket to check. I've tried this:

FormsIdentity id = (FormsIdentity)User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;

But User is null when the authentication period has expired. So that won't work. I've tried this:

HttpCookie authCookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

But the Forms Cookie is gone when the authentication period has expired, meaning authCookie will be null. So that doesn't work.

Is there any way to actually get the FormsAuthenticationTicket object when the authentication period has expired? There must be, because there's an "Expired" property in the object. What am I missing?

Thanks.


问:
Merging data out multiple workbooks in Excel PowerQuery
I want to create a PowerQuery in Excel. I have 10 workbooks with same format to each table in first sheet. I want to merge them all into a one main workbook with the data out of this tables. All workbooks is in the same folder.It is the format i built on:</p>

答:
Start with a query from file > from folder.  Then use the Combine Binaries, which will prompt you to define which element from each file you want to combine.

https://support.office.com/en-us/article/Combine-files-in-a-folder-with-Combine-Binaries-Power-Query-94b8023c-2e66-4f6b-8c78-6a00041c90e4


问:
Simple “Hello World” in ReactJS not working
I am not getting hello world as an output. Can anyone tell me what i am missing  , its a basic code , got an output in a different way using createElement function. I am new to react.

Code:

```<code><!DOCTYPE html>
<html>
    <head>
        <title>My First App</title>
    </head>
    <body>
        <div id="react-app"></div>
        <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react.js"></script>
        <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react-dom.js"></script>

        <script type="text/jsx">

            class StoryBox extends React.Component{
                render(){
                    return(<div> Hello World </div> );
                }
            }

            var target= document.getElementById('react-app')
            ReactDOM.render(<StoryBox>,target);
        </script>
    </body>
</html>
</code>```

答:
You need to add JSX self-closing tag /> - when there is no children.

replace this line:

```<code>ReactDOM.render(<StoryBox>,target)
</code>```

to

```<code>ReactDOM.render(<StoryBox />,target)
</code>```

See working code:

class StoryBox extends React.Component{
        render(){
            return(
 Hello World
);
        }
    }
var target= document.getElementById('react-app')
ReactDOM.render(<StoryBox />,target)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="react-app"></div></code>```

Body:
I am not getting hello world as an output. Can anyone tell me what i am missing  , its a basic code , got an output in a different way using createElement function. I am new to react.

Code:

<!DOCTYPE html>

        <title>My First App</title>

Body:
You need to add JSX self-closing tag /> - when there is no children.

replace this line:

ReactDOM.render(<StoryBox>,target)

to

ReactDOM.render(<StoryBox />,target)

See working code:

class StoryBox extends React.Component{
        render(){
            return(<div> Hello World </div>);
        }
    }
var target= document.getElementById('react-app')
ReactDOM.render(<StoryBox />,target)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="react-app"></div>