问:
Best framework for developing real-time website?
The title may be misleading many, so let me rephrase. What is the best framework or language that is used for displaying real-time data, that requires a lot of UI/backend rendering?

Recently I was using mean stack with angular2 for a project and it was very cumbersome for always using two-way data-binding or using event emitters to watch any change.

Is there any language/framework that just renders UI based on what has been changed in backend or frontend?

Would reactjs or metoeorjs do the job?

Please enlighten me.

Thanks

答:
A lot of people are straying away from Angular due to the huge changes in 2 in my experience.

Personally, I use react to do this. If you set up web sockets, or use Firebase all you do is handle the event triggers. When they do, react uses immutability to see what part of objects have changed and renders/updates elements accordingly.


来源: stackexchange

问:
My IndexedDB add() in my service worker succeed but I cannot see the data it in the Chrome dev tools Application/Storage
I am on Chrome Version 57.0.2987.110 (64-bit) on MacOS/OSX 12.3 Sierra,

I managed to get a service worker working, but I must say I am new at this.

I now try to get it to use an IndexedDB and store data in it.

It fetches data from a local web server in http and retrieve it without problem in json format.

The data format is :

```<code>[{"id":"1", "...":"...", ...},
 {"id":"2", "...":"...", ...},
 {"id":"3", "...":"...", ...},
 ...
 {"id":"n", "...":"...", ...}]
</code>```

it then adds the data to an IndexedDB without problem apparently because the onsuccess callback is triggered ...

```<code>entityObjectStore.add success : Event {isTrusted: true, type: "success", target: IDBRequest, currentTarget: IDBRequest, eventPhase: 2…}
</code>```

But it does not appear in the Chrome dev tools!

Here is my service worker:

```<code>self.addEventListener('install',function(event)
    {
    event.waitUntil(
        (new Promise(function(resolve,reject)resolve()}))
        .then(function()
            {return self.skipWaiting();}));
    });

self.addEventListener('activate', function(event)
    {
    event.waitUntil(
        (new Promise(function(resolve,reject){resolve()}))
        .then(function() {return self.clients.claim();}));
    });

self.addEventListener('message', function(event)
    {
    if(event.data.command=="data.load")
        {
        var options = event.data.options
        var url = new URL(event.data.host+options.source);
        var parameters = {entity:options.name,
                          options:encodeURIComponent(options.options)};
        Object.keys(parameters)
            .forEach(key => url.searchParams.append(key,
                                                    parameters[key]))
        fetch(url).then(function(response)
            {
            if(response.ok)
                {
                response.json().then(function(data_json)
                    {
                    var entityData = data_json;
                    var request = indexedDB.open(options.name);
                    request.onerror = function(event)
                        {
                        console.log("indexedDB.open error :",event);
                        };
                    request.onsuccess = function(event)
                        {
                        console.log("indexedDB.open success :",event)
                        var db = event.target.result;
                        }
                    request.onupgradeneeded = function(event)
                        {
                        console.log("indexedDB.open upgrade :",event)
                        var db = event.target.result;
                        db.createObjectStore(options.options.id, { keyPath: "id" });
                        objectStore.transaction.oncomplete = function(event)
                            {
                            var entityObjectStore = db.transaction(options.options.id, "readwrite").objectStore(options.options.id);
                            for (var i in entityData)
                                {
                                var addRequest = entityObjectStore.add(entityData[i]);
                                addRequest.onerror = function(event)
                                    {
                                    console.log("entityObjectStore.add error :",event);
                                    };
                                addRequest.onsuccess = function(event)
                                    {
                                    console.log("entityObjectStore.add success :",event);
                                    };
                                }
                            }
                        };

                    });
                }
            });
        }
    else if(event.data.command=="data.get")
        {
        var command = event.data;
        var request = indexedDB.open(command.domain);
        request.onerror = function(event)
            {
            console.log("indexedDB.open error :",event);
            };
        request.onsuccess = function(event)
            {
            console.log("indexedDB.open success :", event)
            var db = event.target.result;
            var transaction = db.transaction([command.domain]);
            var objectStore = transaction.objectStore(command.entity);
            var request = objectStore.get(command.id);
            request.onerror = function(event)
                {
                console.log("objectStore.get error :",event);
                };
            request.onsuccess = function(event)
                {
                console.log("objectStore.get success :",event);
                console.log("request.result=" + request.result);
                };
            }
        }
    });
</code>```

Here is the HTML file I use with it :

```<code><!DOCTYPE html>
<html>
    <head>
        <title>My service worker app</title>
    </head>
    <body>
        <button id="update">Update</button>
        <div id="log"></div>
        <script type="text/javascript">
        function sendMessage(message)
            {
            return new Promise(function(resolve, reject)
                {
                var messageChannel = new MessageChannel();
                messageChannel.port1.onmessage = function(event)
                    {
                    if (event.data.error)
                        {
                        reject(event.data.error);
                        }
                    else
                        {
                        resolve(event.data);
                        }
                    };

                });
            }
            if (navigator.serviceWorker.controller)
                {
                var url = navigator.serviceWorker.controller.scriptURL;
                var initData =  [
                                {
                                name:"my_entity_type",
                                source:"/webapp/data",
                                options:{id:"my_entity_type_id"}
                                }
                                ]
                for(var dataIndex in initData)
                    {
                    var data = initData[dataIndex]
                    sendMessage({
                                 command:"data.load",
                                 host: document.location.origin,
                                 options: data
                                 });
                    }
                }
            else
                {
                navigator.serviceWorker.register('/webapp/lt_sw.js')
                    .then(function(registration)
                        {
                        debug('Refresh to allow ServiceWorker to control this client', 'onload');
                        debug(registration.scope, 'register');
                        });
                }

    navigator.serviceWorker.addEventListener('controllerchange',
    function()
        {
        var scriptURL = navigator.serviceWorker.controller.scriptURL;
        debug(scriptURL, 'oncontrollerchange');
        });

    document.querySelector('#update').addEventListener('click',
    function()
        {
        navigator.serviceWorker.ready.then(function(registration)
            {
            registration.update()
                .then(function()
                    {
                    console.log('Checked for update');
                    })
                .catch(function(error)
                    {
                    console.error('Update failed', error);
                    });
                });
            });

        function debug(message, element)
            {
            var target = document.querySelector('#log');
            console.log(element,":",message)
            target.textContent = message;
            }
        </script>
    </body>
</html>
</code>```

Any idea about what I am, doing wrong?

Edit 1:

I modified the script in the html file so that update mechanism sends another message to the service worker asking for data :

```<code>    document.querySelector('#update').addEventListener('click',
    function()
        {
        navigator.serviceWorker.ready.then(function(registration)
            {
            registration.update()
                .then(function()
                    {
                    console.log('Checked for update');
                    sendMessage({
                        command:"data.get",
                        domain:"database_name",
                        entity: "my_entity_type",
                        id: "my_entity_id"
                        });
                    })
                .catch(function(error)
                    {
                    console.error('Update failed', error);
                    });
                });
            });
</code>```

And I added the following line:

```<code>    indexedDB.webkitGetDatabaseNames().onsuccess = function(sender,args){ console.log("data.get all dbs:",sender.target.result); };
</code>```

Just at the beginning of the data look up part:

```<code>    else if(event.data.command=="data.get")
        {
</code>```

To list all the IndexedDBs on Chrome as explained here : https://stackoverflow.com/a/15234833/2360577
And I get all the databases I created previously!

```<code>data.get all dbs: DOMStringList {0: "db1", 1: "db2", 2: "db3", 3: "db4", length: 4}
</code>```

Then I proceeded to list all ObjectStores in these dbs, also as explained in the previous link, by adding the following line :

```<code>indexedDB.open(<databaseName>).onsuccess = function(sender,args)
{"<databaseName>'s object stores",console.log(sender.target.result.objectStoreNames); };
</code>```

And apart for one, where the data is processed and apparently does not work, they all had one object store with the same name as the db that contains it as expected ...

```<code>db1's object stores DOMStringList {0: "db1", length: 1}
db2's object stores DOMStringList {length: 0}
db3's object stores DOMStringList {0: "db3", length: 1}
db4's object stores DOMStringList {0: "db4", length: 1}
</code>```

Then I had a look inside the object stores ...

```<code>entityObjectStore.add success : Event {isTrusted: true, type: "success", target: IDBRequest, currentTarget: IDBRequest, eventPhase: 2…}
</code>```0

And the entries are there as expected! But not in Application/Storage ...

Edit 2:

The error for db2 was apparently that I did not refresh the data in the database ... this part works now ...

Edit 3:

The answer was as simple as closing and reopening the dev tools ... like @wOxxOm suggested ...

答: It works for me if I close DevTools and open again. Did you try that?</p>

ContentLicense: CC BY-SA 3.0

Body:
I am on Chrome Version 57.0.2987.110 (64-bit) on MacOS/OSX 12.3 Sierra,

I managed to get a service worker working, but I must say I am new at this.

I now try to get it to use an IndexedDB and store data in it.

It fetches data from a local web server in http and retrieve it without problem in json format.

The data format is :

[{"id":"1", "...":"...", ...},
 {"id":"2", "...":"...", ...},
 {"id":"3", "...":"...", ...},
 ...
 {"id":"n", "...":"...", ...}]

it then adds the data to an IndexedDB without problem apparently because the onsuccess callback is triggered ...

entityObjectStore.add success : Event {isTrusted: true, type: "success", target: IDBRequest, currentTarget: IDBRequest, eventPhase: 2…}

But it does not appear in the Chrome dev tools!

Here is my service worker:

self.addEventListener('install',function(event)
    {
    event.waitUntil(
        (new Promise(function(resolve,reject)resolve()}))
        .then(function()
            {return self.skipWaiting();}));
    });

self.addEventListener('activate', function(event)
    {
    event.waitUntil(
        (new Promise(function(resolve,reject){resolve()}))
        .then(function() {return self.clients.claim();}));
    });

self.addEventListener('message', function(event)
    {
    if(event.data.command=="data.load")
        {
        var options = event.data.options
        var url = new URL(event.data.host+options.source);
        var parameters = {entity:options.name,
                          options:encodeURIComponent(options.options)};
        Object.keys(parameters)
            .forEach(key => url.searchParams.append(key,
                                                    parameters[key]))
        fetch(url).then(function(response)
            {
            if(response.ok)
                {
                response.json().then(function(data_json)
                    {
                    var entityData = data_json;
                    var request = indexedDB.open(options.name);
                    request.onerror = function(event)
                        {
                        console.log("indexedDB.open error :",event);
                        };
                    request.onsuccess = function(event)
                        {
                        console.log("indexedDB.open success :",event)
                        var db = event.target.result;
                        }
                    request.onupgradeneeded = function(event)
                        {
                        console.log("indexedDB.open upgrade :",event)
                        var db = event.target.result;
                        db.createObjectStore(options.options.id, { keyPath: "id" });
                        objectStore.transaction.oncomplete = function(event)
                            {
                            var entityObjectStore = db.transaction(options.options.id, "readwrite").objectStore(options.options.id);
                            for (var i in entityData)
                                {
                                var addRequest = entityObjectStore.add(entityData[i]);
                                addRequest.onerror = function(event)
                                    {
                                    console.log("entityObjectStore.add error :",event);
                                    };
                                addRequest.onsuccess = function(event)
                                    {
                                    console.log("entityObjectStore.add success :",event);
                                    };
                                }
                            }
                        };

                    });
                }
            });
        }
    else if(event.data.command=="data.get")
        {
        var command = event.data;
        var request = indexedDB.open(command.domain);
        request.onerror = function(event)
            {
            console.log("indexedDB.open error :",event);
            };
        request.onsuccess = function(event)
            {
            console.log("indexedDB.open success :", event)
            var db = event.target.result;
            var transaction = db.transaction([command.domain]);
            var objectStore = transaction.objectStore(command.entity);
            var request = objectStore.get(command.id);
            request.onerror = function(event)
                {
                console.log("objectStore.get error :",event);
                };
            request.onsuccess = function(event)
                {
                console.log("objectStore.get success :",event);
                console.log("request.result=" + request.result);
                };
            }
        }
    });

Here is the HTML file I use with it :

<!DOCTYPE html>

        <title>My service worker app</title>

        <button id="update">Update</button>

Any idea about what I am, doing wrong?

Edit 1:

I modified the script in the html file so that update mechanism sends another message to the service worker asking for data :

    document.querySelector('#update').addEventListener('click',
    function()
        {
        navigator.serviceWorker.ready.then(function(registration)
            {
            registration.update()
                .then(function()
                    {
                    console.log('Checked for update');
                    sendMessage({
                        command:"data.get",
                        domain:"database_name",
                        entity: "my_entity_type",
                        id: "my_entity_id"
                        });
                    })
                .catch(function(error)
                    {
                    console.error('Update failed', error);
                    });
                });
            });

And I added the following line:

    indexedDB.webkitGetDatabaseNames().onsuccess = function(sender,args){ console.log("data.get all dbs:",sender.target.result); };

Just at the beginning of the data look up part:

    else if(event.data.command=="data.get")
        {

To list all the IndexedDBs on Chrome as explained here : https://stackoverflow.com/a/15234833/2360577
And I get all the databases I created previously!

data.get all dbs: DOMStringList {0: "db1", 1: "db2", 2: "db3", 3: "db4", length: 4}

Then I proceeded to list all ObjectStores in these dbs, also as explained in the previous link, by adding the following line :

indexedDB.open(<databaseName>).onsuccess = function(sender,args)
{"<databaseName>'s object stores",console.log(sender.target.result.objectStoreNames); };

And apart for one, where the data is processed and apparently does not work, they all had one object store with the same name as the db that contains it as expected ...

db1's object stores DOMStringList {0: "db1", length: 1}
db2's object stores DOMStringList {length: 0}
db3's object stores DOMStringList {0: "db3", length: 1}
db4's object stores DOMStringList {0: "db4", length: 1}

Then I had a look inside the object stores ...

indexedDB.open("db3").onsuccess = function(event)
{event.target.result.transaction(["db3"]).objectStore("db3")
    .getAll().onsuccess = function(event)
    {console.log("objectStore.getAll() success :",event.target.result)};};

And the entries are there as expected! But not in Application/Storage ...

Edit 2:

The error for db2 was apparently that I did not refresh the data in the database ... this part works now ...

Edit 3:

The answer was as simple as closing and reopening the dev tools ... like @wOxxOm suggested ...


问:
Number of Duplicate Rows in multiple columns (more than 10) in SQL Server
I have a table in SQL Server and I need to find the number of customers and accounts who have different values across the row.

For example

```<code>Customer  Account    X   Y   Z
-------------------------------
A             001   X1   Y1  Z1
A             002   X2   Y1  Z1
A             003   X1   Y1  Z1
B             004   X3   Y2  Z2
B             005   X4   Y2  Z2
C             006   X5   Y3  Z3
C             007   X5   Y3  Z3
</code>```

and I want the result to be Number of Customers with different X,Y,Z are 2, Number of accounts affected are 5.

```<code>Customer  Account   X   Y   Z
-------------------------------
A            001    X1  Y1  Z1
A            002    X2  Y1  Z1
A            003    X1  Y1  Z1
B            004    X3  Y2  Z2
B            005    X4  Y2  Z2
</code>```

答:
In Tableau, put Customer on the filter shelf, and on the condition tab for the filter, enter the condition countd([X]) = 1 and countd([Y]) = 1 and countd([Z]) = 1

That will only include customers who only have one unique value in each of the columns you mention (X, Y and Z). It causes Tableau to emit SQL that is equivalent to "group by customer having count(distinct X) = 1 and ..."

If your columns are allowed to have null values and if that affects what customers you want to include (say if occasionally having a null value for Z should exclude a customer), then you can adjust your condition accordingly, say using the count() function also or ifnull() function.

Body:
I have a table in SQL Server and I need to find the number of customers and accounts who have different values across the row.

For example

Customer  Account    X   Y   Z
-------------------------------
A             001   X1   Y1  Z1
A             002   X2   Y1  Z1
A             003   X1   Y1  Z1
B             004   X3   Y2  Z2
B             005   X4   Y2  Z2
C             006   X5   Y3  Z3
C             007   X5   Y3  Z3

and I want the result to be Number of Customers with different X,Y,Z are 2, Number of accounts affected are 5.

Customer  Account   X   Y   Z
-------------------------------
A            001    X1  Y1  Z1
A            002    X2  Y1  Z1
A            003    X1  Y1  Z1
B            004    X3  Y2  Z2
B            005    X4  Y2  Z2


问:
How to change DataTable Rows to Columns in C#
How to Change dataTable Rows to Columns

```<code>DataTable dt=new DataTable();
dt = getData(); //Pull data from source file
</code>```

I have below format rows in a dataTable.

Now I want change ANC_TYPE rows into columns?
How i can convert into below format ?

答:
You want a pivot table :</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication49
{
    class Program
    {

        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("OPR_DT", typeof(DateTime));
            dt.Columns.Add("OPR_HR", typeof(int));
            dt.Columns.Add("ANC_TYPE", typeof(string));
            dt.Columns.Add("ANC_REGION", typeof(string));
            dt.Columns.Add("MARKET_RUN_ID", typeof(string));
            dt.Columns.Add("XML_DATE_ITEM", typeof(string));
            dt.Columns.Add("MW", typeof(decimal));
            dt.Columns.Add("GROUP", typeof(int));

            dt.Rows.Add(new object[] { DateTime.Parse("2/23/2017"), 1, "NR", "AS_CAISO_EXP", "DAM", "NS_CLR_PRC", 0.09, 1});
            dt.Rows.Add(new object[] { DateTime.Parse("2/23/2017"), 1, "RD", "AS_CAISO_EXP", "DAM", "RD_CLR_PRC", 2.83, 2 });
            dt.Rows.Add(new object[] { DateTime.Parse("2/23/2017"), 2, "NR", "AS_CAISO_EXP", "DAM", "NS_CLR_PRC", 0.01, 3 });
            dt.Rows.Add(new object[] { DateTime.Parse("2/23/2017"), 2, "RD", "AS_CAISO_EXP", "DAM", "RD_CLR_PRC", 0.1, 4 });

            string[] uniqueAncType = dt.AsEnumerable().Select(x => x.Field<string>("ANC_TYPE")).Distinct().ToArray();

            DataTable pivot = new DataTable();
            pivot.Columns.Add("OPR_DT", typeof(DateTime));
            pivot.Columns.Add("OPR_HR", typeof(int));
            pivot.Columns.Add("ANC_REGION", typeof(string));
            pivot.Columns.Add("MARKET_RUN_ID", typeof(string));
            foreach (string col in uniqueAncType)
            {
                pivot.Columns.Add(col, typeof(string));
            }

            var groups = dt.AsEnumerable()
                .GroupBy(x => new {
                    opr_dt = x.Field<DateTime>("OPR_DT"),
                    opr_hr = x.Field<int>("OPR_HR"),
                    anc_region = x.Field<string>("ANC_REGION"),
                    run_id = x.Field<string>("MARKET_RUN_ID")
                }).ToList();

            foreach (var group in groups)
            {
                DataRow newRow =  pivot.Rows.Add();
                newRow["OPR_DT"] = group.Key.opr_dt;
                newRow["OPR_HR"] = group.Key.opr_hr;
                newRow["ANC_REGION"] = group.Key.anc_region;
                newRow["MARKET_RUN_ID"] = group.Key.run_id;
                foreach (DataRow ancType in group)
                {
                    newRow[ancType.Field<string>("ANC_TYPE")] = ancType.Field<decimal>("MW");
                }

            }

        }
    }

}
</code>```

Body:
How to Change dataTable Rows to Columns

DataTable dt=new DataTable();
dt = getData(); //Pull data from source file

I have below format rows in a dataTable.

Now I want change ANC_TYPE rows into columns?
How i can convert into below format ?

Body:
You want a pivot table :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication49
{
    class Program
    {

        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("OPR_DT", typeof(DateTime));
            dt.Columns.Add("OPR_HR", typeof(int));
            dt.Columns.Add("ANC_TYPE", typeof(string));
            dt.Columns.Add("ANC_REGION", typeof(string));
            dt.Columns.Add("MARKET_RUN_ID", typeof(string));
            dt.Columns.Add("XML_DATE_ITEM", typeof(string));
            dt.Columns.Add("MW", typeof(decimal));
            dt.Columns.Add("GROUP", typeof(int));

            dt.Rows.Add(new object[] { DateTime.Parse("2/23/2017"), 1, "NR", "AS_CAISO_EXP", "DAM", "NS_CLR_PRC", 0.09, 1});
            dt.Rows.Add(new object[] { DateTime.Parse("2/23/2017"), 1, "RD", "AS_CAISO_EXP", "DAM", "RD_CLR_PRC", 2.83, 2 });
            dt.Rows.Add(new object[] { DateTime.Parse("2/23/2017"), 2, "NR", "AS_CAISO_EXP", "DAM", "NS_CLR_PRC", 0.01, 3 });
            dt.Rows.Add(new object[] { DateTime.Parse("2/23/2017"), 2, "RD", "AS_CAISO_EXP", "DAM", "RD_CLR_PRC", 0.1, 4 });

            string[] uniqueAncType = dt.AsEnumerable().Select(x => x.Field<string>("ANC_TYPE")).Distinct().ToArray();

            DataTable pivot = new DataTable();
            pivot.Columns.Add("OPR_DT", typeof(DateTime));
            pivot.Columns.Add("OPR_HR", typeof(int));
            pivot.Columns.Add("ANC_REGION", typeof(string));
            pivot.Columns.Add("MARKET_RUN_ID", typeof(string));
            foreach (string col in uniqueAncType)
            {
                pivot.Columns.Add(col, typeof(string));
            }

            var groups = dt.AsEnumerable()
                .GroupBy(x => new {
                    opr_dt = x.Field<DateTime>("OPR_DT"),
                    opr_hr = x.Field<int>("OPR_HR"),
                    anc_region = x.Field<string>("ANC_REGION"),
                    run_id = x.Field<string>("MARKET_RUN_ID")
                }).ToList();

            foreach (var group in groups)
            {
                DataRow newRow =  pivot.Rows.Add();
                newRow["OPR_DT"] = group.Key.opr_dt;
                newRow["OPR_HR"] = group.Key.opr_hr;
                newRow["ANC_REGION"] = group.Key.anc_region;
                newRow["MARKET_RUN_ID"] = group.Key.run_id;
                foreach (DataRow ancType in group)
                {
                    newRow[ancType.Field<string>("ANC_TYPE")] = ancType.Field<decimal>("MW");
                }

            }

        }
    }

}


问:
Print shell environment functions on a single line
In bash, running set will display all environment settings. I want to display my functions as a single line for each function. So instead of running set and getting this (for example):

```<code>gcm ()
{
    git commit -m "$@";
    git --no-pager log -1 | grep --color ^commit
}
gcma ()
{
    git commit -a -m "$@";
    git --no-pager log -1 | grep --color ^commit
}
</code>```

I want to see this:

```<code>gcm () { git commit -m "$@"; git --no-pager log -1 | grep --color ^commit }
gcma () { git commit -a -m "$@"; git --no-pager log -1 | grep --color ^commit }
</code>```

So I think I want a sed/awk command that will look for regex ' ()$' and concatenate every line following (with a space separation char) until the regex '^}$' is matched, and anything else should just print as is.

UPDATE: All of the examples submitted so far take all the input and render it on a single line, and that's not exactly right. I want each function (the set of ' ()$' to '^}$', inclusive) as a single line.

答:
Try this - </p>

```<code>awk  '{gsub(/[[:space:]]+/," ") ;ORS=(/}/?RS:FS)}1' f
gcm () {  git commit -m "$@";  git --no-pager log -1 | grep --color ^commit }
gcma () {  git commit -a -m "$@";  git --no-pager log -1 | grep --color ^commit }
</code>```

Body:
In bash, running set will display all environment settings. I want to display my functions as a single line for each function. So instead of running set and getting this (for example):

gcm ()
{
    git commit -m "$@";
    git --no-pager log -1 | grep --color ^commit
}
gcma ()
{
    git commit -a -m "$@";
    git --no-pager log -1 | grep --color ^commit
}

I want to see this:

gcm () { git commit -m "$@"; git --no-pager log -1 | grep --color ^commit }
gcma () { git commit -a -m "$@"; git --no-pager log -1 | grep --color ^commit }

So I think I want a sed/awk command that will look for regex ' ()$' and concatenate every line following (with a space separation char) until the regex '^}$' is matched, and anything else should just print as is.

UPDATE: All of the examples submitted so far take all the input and render it on a single line, and that's not exactly right. I want each function (the set of ' ()$' to '^}$', inclusive) as a single line.

Body:
Try this -

awk  '{gsub(/[[:space:]]+/," ") ;ORS=(/}/?RS:FS)}1' f
gcm () {  git commit -m "$@";  git --no-pager log -1 | grep --color ^commit }
gcma () {  git commit -a -m "$@";  git --no-pager log -1 | grep --color ^commit }


问:
storing pointer to member function does not work for clang++
when i use clang++ i can only call the pointer-to-member function i can't cast it or assign it to a variable to call i when needed (i want to store this variable to an array of functions) but with g++ i can do that take this for example

```<code>class Base {
    public:
        typedef void (Base::*A)();
        virtual void some_func() = 0;
};
class B: public Base {
    public:
        void some_func() {
            return
        }
};
int main() {
    B b;
    auto h = (Base::A)&Base::some_func;
    typedef void (*my_function)();
    auto some_func = (my_function)(b.*h);
    some_func();
    return 0;
}
</code>```

with g++ this do compile and run, but with clang++ i get
reference to non-static member function must be called; did you mean to call it with no arguments? ( please note that i can't use any std::x functions in my code because the code run on bare metal

答:
Apparently in g++, it permits you to cast a pointer to member function with 0 arguments to a function pointer, and calling it will result in invoking that member function with a corrupt/missing this pointer.

In addition, the expression b.*m, where m is a member function and b is a class will evaluate virtual dispatch, and the resulting object can be then cast to a function pointer that has evaluated that virtual dispatch.  It will still have a corrupt this value.

Both of these are illegal operations under the standard; the program is either ill defined, or using it is undefined behavior.

In g++, the fact that the this pointer is garbage is a good reason why this isn't a very useful strategy.  Here is an example of it being built with some state in B and it not compiling on clang++ and segfaulting on g++.

A member function and a pointer to object are two things.  Storing them both in one thing (a function pointer) is not going to work, regardless of how you hack it.

There are a number of ways to approach this.  The simplest is to use std::function, but you are banned from using the standard library.

The next easiest way is to write your own std::function variant.  I've done this -- a "delegate" that supports storing pointers-to-lambdas, pointers to functions, (pointers to objects + pointers to member functions) that are call compatible with a given signature.

All of these are trivial "plain old data", so you can create a simple buffer, copy their value into the buffer, and save a function that knows how to take a pointer-to-the-buffer and invoke it.

```<code>template<class Sig, unsigned Sz=3*sizeof(void*)>
struct fun;
template<class R, class...Args, unsigned Sz>
struct fun<R(Args...), Sz> {
  using invoker_t = R(*)(void*, Args&&...);
  invoker_t invoker;
  unsigned char buffer[Sz];
  template<class D>
  struct invoker_base_t {
    using invoker_sig = R(*)(void* self, Args&&...args);
    static invoker_sig invoker() {
      return [](void* self, Args&&...args)->R {
        return (*static_cast<D*>(self))(static_cast<Args&&>(args)...);
      };
    }
  };
  template<class T, class M>
  struct mem_fun_invoker_t:invoker_base_t<mem_fun_invoker_t<T,M>> {
    T* t;
    M m;
    mem_fun_invoker_t(T* tin, M min):t(tin), m(min) {}
    mem_fun_invoker_t(mem_fun_invoker_t const&)=default;
    R operator()(Args&&...args) {
      return (t->*m)(static_cast<Args&&>(args)...);
    }
  };
  template<class T, class M>
  static mem_fun_invoker_t<T, M> mem_fun_invoker(T* t, M m){ return {t, m}; }
  template<class T>
  struct ptr_invoker_t:invoker_base_t<ptr_invoker_t<T>> {
    T* t;
    ptr_invoker_t(T* tin):t(tin) {}
    ptr_invoker_t(ptr_invoker_t const&)=default;
    R operator()(Args&&...args) {
      return (*t)(static_cast<Args&&>(args)...);
    }
  };
  template<class T>
  static ptr_invoker_t<T> ptr_invoker(T* t){ return {t}; }
  template<class T, class U, class Ret, class...Ts>
  fun(T* t, Ret(U::*mem)(Ts...)) {
    auto invoke = mem_fun_invoker( t, mem );
    static_assert(sizeof(invoke) <= Sz);
    ::new( (void*)buffer ) decltype(invoke)(invoke);
    invoker = invoke.invoker();
  }
  template<class T, class U, class Ret, class...Ts>
  fun(T const* t, Ret(U::*mem)(Ts...)const) {
    auto invoke = mem_fun_invoker( t, mem );
    static_assert(sizeof(invoke) <= Sz);
    ::new( (void*)buffer ) decltype(invoke)(invoke);
    invoker = invoke.invoker();
  }

  template<class Ret, class...Ts>
  fun(Ret(*f)(Ts...)) {
    auto invoke = ptr_invoker( f );
    static_assert(sizeof(invoke) <= Sz);
    ::new( (void*)buffer ) decltype(invoke)(invoke);
    invoker = invoke.invoker();
  }
  // TODO: SFINAE
  template<class Lambda>
  fun(Lambda&& lambda) {
    auto invoke = ptr_invoker( &lambda );
    static_assert(sizeof(invoke) <= Sz);
    ::new( (void*)buffer ) decltype(invoke)(invoke);
    invoker = invoke.invoker();
  }
  R operator()(Args...args) {
    return invoker(&buffer, static_cast<Args&&>(args)...);
  }
  explicit operator bool()const {return invoker;}
};
</code>```

the above needs a quality sweep and more asserts and some SFINAE.

But it works.

fun<Sig> is a bare bones variant of std::function that has almost no state.  The missing SFINAE needs to test if Lambda is signature compatible and not equal to fun type itself.

These objects are roughly 4 pointers in size; you can configure how big with the Sz argument.  2 may be enough to fit member functions and a this pointer.  I rounded up to 3.

These things can also store pointers to functions.

They can store pointers to lambdas, or variations of fun, but do not extend the lifetime of said lambda.  This is dangerous, but often useful.

Like std::function they do not require signatures to match exactly.  Unlike C++14's std::function, if R is void, the stored objects must also return void.  Fixing this is more work:

```<code>namespace details {
  template<class Sig, class D>
  struct invoker_base_t;
  template<class R, class...Args, class D>
  struct invoker_base_t<R(Args...), D> {
    using invoker_sig = R(*)(void* self, Args&&...args);
    static invoker_sig invoker() {
      return [](void* self, Args&&...args)->R {
        return (*static_cast<D*>(self))(static_cast<Args&&>(args)...);
      };
    }
  };
  template<class...Args, class D>
  struct invoker_base_t<void(Args...), D> {
    using invoker_sig = void(*)(void* self, Args&&...args);
    static invoker_sig invoker() {
      return [](void* self, Args&&...args)->void {
        (*static_cast<D*>(self))(static_cast<Args&&>(args)...);
      };
    }
  };
  template<class Sig, class T, class M>
  struct mem_fun_invoker_t;
  template<class R, class...Args, class T, class M>
  struct mem_fun_invoker_t<R(Args...), T, M>:
    invoker_base_t<R(Args...), mem_fun_invoker_t<R(Args...),T,M> >
  {
    T* t;
    M m;
    mem_fun_invoker_t(T* tin, M min):t(tin), m(min) {}
    mem_fun_invoker_t(mem_fun_invoker_t const&)=default;
    R operator()(Args&&...args) {
      return (t->*m)(static_cast<Args&&>(args)...);
    }
  };
  template<class...Args, class T, class M>
  struct mem_fun_invoker_t<void(Args...), T, M>:
    invoker_base_t<void(Args...), mem_fun_invoker_t<void(Args...),T,M> >
  {
    T* t;
    M m;
    mem_fun_invoker_t(T* tin, M min):t(tin), m(min) {}
    mem_fun_invoker_t(mem_fun_invoker_t const&)=default;
    void operator()(Args&&...args) {
      (t->*m)(static_cast<Args&&>(args)...);
    }
  };
  template<class Sig, class T>
  struct ptr_invoker_t;
  template<class R, class...Args, class T>
  struct ptr_invoker_t<R(Args...), T>:
    invoker_base_t<R(Args...), ptr_invoker_t<R(Args...),T> >
  {
    T* t;
    ptr_invoker_t(T* tin):t(tin) {}
    ptr_invoker_t(ptr_invoker_t const&)=default;
    R operator()(Args&&...args) {
      return (*t)(static_cast<Args&&>(args)...);
    }
  };
  template<class...Args, class T>
  struct ptr_invoker_t<void(Args...), T>:
    invoker_base_t<void(Args...), ptr_invoker_t<void(Args...),T> >
  {
    T* t;
    ptr_invoker_t(T* tin):t(tin) {}
    ptr_invoker_t(ptr_invoker_t const&)=default;
    void operator()(Args&&...args) {
      (*t)(static_cast<Args&&>(args)...);
    }
  };
}
template<class Sig, unsigned Sz=3*sizeof(void*)>
struct fun;
template<class R, class...Args, unsigned Sz>
struct fun<R(Args...), Sz> {
  using invoker_t = R(*)(void*, Args&&...);
  invoker_t invoker;
  unsigned char buffer[Sz];
  template<class T, class M>
  static details::mem_fun_invoker_t<R(Args...), T, M> mem_fun_invoker(T* t, M m){ return {t, m}; }
  template<class T>
  static details::ptr_invoker_t<R(Args...), T> ptr_invoker(T* t){ return {t}; }
  template<class T, class U, class Ret, class...Ts>
  fun(T* t, Ret(U::*mem)(Ts...)) {
    auto invoke = mem_fun_invoker( t, mem );
    static_assert(sizeof(invoke) <= Sz);
    ::new( (void*)buffer ) decltype(invoke)(invoke);
    invoker = invoke.invoker();
  }
  template<class T, class U, class Ret, class...Ts>
  fun(T const* t, Ret(U::*mem)(Ts...)const) {
    auto invoke = mem_fun_invoker( t, mem );
    static_assert(sizeof(invoke) <= Sz);
    ::new( (void*)buffer ) decltype(invoke)(invoke);
    invoker = invoke.invoker();
  }

  template<class Ret, class...Ts>
  fun(Ret(*f)(Ts...)) {
    auto invoke = ptr_invoker( f );
    static_assert(sizeof(invoke) <= Sz);
    ::new( (void*)buffer ) decltype(invoke)(invoke);
    invoker = invoke.invoker();
  }
  // TODO: SFINAE
  template<class Lambda>
  fun(Lambda&& lambda) {
    auto invoke = ptr_invoker( &lambda );
    static_assert(sizeof(invoke) <= Sz);
    ::new( (void*)buffer ) decltype(invoke)(invoke);
    invoker = invoke.invoker();
  }
  R operator()(Args...args) {
    return invoker(&buffer, static_cast<Args&&>(args)...);
  }
  explicit operator bool()const {return invoker;}
};
</code>```

live example.

The above is standards compliant and does not rely upon std.  Writing the SFINAE to ensure the Lambda&& overload isn't called in bad situation may require rewriting some of std, like std::is_same and enable_if.

Body:
when i use clang++ i can only call the pointer-to-member function i can't cast it or assign it to a variable to call i when needed (i want to store this variable to an array of functions) but with g++ i can do that take this for example

class Base {
    public:
        typedef void (Base::*A)();
        virtual void some_func() = 0;
};
class B: public Base {
    public:
        void some_func() {
            return
        }
};
int main() {
    B b;
    auto h = (Base::A)&Base::some_func;
    typedef void (*my_function)();
    auto some_func = (my_function)(b.*h);
    some_func();
    return 0;
}

with g++ this do compile and run, but with clang++ i get
reference to non-static member function must be called; did you mean to call it with no arguments? ( please note that i can't use any std::x functions in my code because the code run on bare metal

Body:
Apparently in g++, it permits you to cast a pointer to member function with 0 arguments to a function pointer, and calling it will result in invoking that member function with a corrupt/missing this pointer.

In addition, the expression b.*m, where m is a member function and b is a class will evaluate virtual dispatch, and the resulting object can be then cast to a function pointer that has evaluated that virtual dispatch.  It will still have a corrupt this value.

Both of these are illegal operations under the standard; the program is either ill defined, or using it is undefined behavior.

In g++, the fact that the this pointer is garbage is a good reason why this isn't a very useful strategy.  Here is an example of it being built with some state in B and it not compiling on clang++ and segfaulting on g++.

A member function and a pointer to object are two things.  Storing them both in one thing (a function pointer) is not going to work, regardless of how you hack it.

There are a number of ways to approach this.  The simplest is to use std::function, but you are banned from using the standard library.

The next easiest way is to write your own std::function variant.  I've done this -- a "delegate" that supports storing pointers-to-lambdas, pointers to functions, (pointers to objects + pointers to member functions) that are call compatible with a given signature.

All of these are trivial "plain old data", so you can create a simple buffer, copy their value into the buffer, and save a function that knows how to take a pointer-to-the-buffer and invoke it.

template<class Sig, unsigned Sz=3*sizeof(void*)>
struct fun;
template<class R, class...Args, unsigned Sz>
struct fun<R(Args...), Sz> {
  using invoker_t = R(*)(void*, Args&&...);
  invoker_t invoker;
  unsigned char buffer[Sz];
  template<class D>
  struct invoker_base_t {
    using invoker_sig = R(*)(void* self, Args&&...args);
    static invoker_sig invoker() {
      return [](void* self, Args&&...args)->R {
        return (*static_cast<D*>(self))(static_cast<Args&&>(args)...);
      };
    }
  };
  template<class T, class M>
  struct mem_fun_invoker_t:invoker_base_t<mem_fun_invoker_t<T,M>> {
    T* t;
    M m;
    mem_fun_invoker_t(T* tin, M min):t(tin), m(min) {}
    mem_fun_invoker_t(mem_fun_invoker_t const&)=default;
    R operator()(Args&&...args) {
      return (t->*m)(static_cast<Args&&>(args)...);
    }
  };
  template<class T, class M>
  static mem_fun_invoker_t<T, M> mem_fun_invoker(T* t, M m){ return {t, m}; }
  template<class T>
  struct ptr_invoker_t:invoker_base_t<ptr_invoker_t<T>> {
    T* t;
    ptr_invoker_t(T* tin):t(tin) {}
    ptr_invoker_t(ptr_invoker_t const&)=default;
    R operator()(Args&&...args) {
      return (*t)(static_cast<Args&&>(args)...);
    }
  };
  template<class T>
  static ptr_invoker_t<T> ptr_invoker(T* t){ return {t}; }
  template<class T, class U, class Ret, class...Ts>
  fun(T* t, Ret(U::*mem)(Ts...)) {
    auto invoke = mem_fun_invoker( t, mem );
    static_assert(sizeof(invoke) <= Sz);
    ::new( (void*)buffer ) decltype(invoke)(invoke);
    invoker = invoke.invoker();
  }
  template<class T, class U, class Ret, class...Ts>
  fun(T const* t, Ret(U::*mem)(Ts...)const) {
    auto invoke = mem_fun_invoker( t, mem );
    static_assert(sizeof(invoke) <= Sz);
    ::new( (void*)buffer ) decltype(invoke)(invoke);
    invoker = invoke.invoker();
  }

  template<class Ret, class...Ts>
  fun(Ret(*f)(Ts...)) {
    auto invoke = ptr_invoker( f );
    static_assert(sizeof(invoke) <= Sz);
    ::new( (void*)buffer ) decltype(invoke)(invoke);
    invoker = invoke.invoker();
  }
  // TODO: SFINAE
  template<class Lambda>
  fun(Lambda&& lambda) {
    auto invoke = ptr_invoker( &lambda );
    static_assert(sizeof(invoke) <= Sz);
    ::new( (void*)buffer ) decltype(invoke)(invoke);
    invoker = invoke.invoker();
  }
  R operator()(Args...args) {
    return invoker(&buffer, static_cast<Args&&>(args)...);
  }
  explicit operator bool()const {return invoker;}
};

the above needs a quality sweep and more asserts and some SFINAE.

But it works.

fun<Sig> is a bare bones variant of std::function that has almost no state.  The missing SFINAE needs to test if Lambda is signature compatible and not equal to fun type itself.

These objects are roughly 4 pointers in size; you can configure how big with the Sz argument.  2 may be enough to fit member functions and a this pointer.  I rounded up to 3.

These things can also store pointers to functions.

They can store pointers to lambdas, or variations of fun, but do not extend the lifetime of said lambda.  This is dangerous, but often useful.

Like std::function they do not require signatures to match exactly.  Unlike C++14's std::function, if R is void, the stored objects must also return void.  Fixing this is more work:

namespace details {
  template<class Sig, class D>
  struct invoker_base_t;
  template<class R, class...Args, class D>
  struct invoker_base_t<R(Args...), D> {
    using invoker_sig = R(*)(void* self, Args&&...args);
    static invoker_sig invoker() {
      return [](void* self, Args&&...args)->R {
        return (*static_cast<D*>(self))(static_cast<Args&&>(args)...);
      };
    }
  };
  template<class...Args, class D>
  struct invoker_base_t<void(Args...), D> {
    using invoker_sig = void(*)(void* self, Args&&...args);
    static invoker_sig invoker() {
      return [](void* self, Args&&...args)->void {
        (*static_cast<D*>(self))(static_cast<Args&&>(args)...);
      };
    }
  };
  template<class Sig, class T, class M>
  struct mem_fun_invoker_t;
  template<class R, class...Args, class T, class M>
  struct mem_fun_invoker_t<R(Args...), T, M>:
    invoker_base_t<R(Args...), mem_fun_invoker_t<R(Args...),T,M> >
  {
    T* t;
    M m;
    mem_fun_invoker_t(T* tin, M min):t(tin), m(min) {}
    mem_fun_invoker_t(mem_fun_invoker_t const&)=default;
    R operator()(Args&&...args) {
      return (t->*m)(static_cast<Args&&>(args)...);
    }
  };
  template<class...Args, class T, class M>
  struct mem_fun_invoker_t<void(Args...), T, M>:
    invoker_base_t<void(Args...), mem_fun_invoker_t<void(Args...),T,M> >
  {
    T* t;
    M m;
    mem_fun_invoker_t(T* tin, M min):t(tin), m(min) {}
    mem_fun_invoker_t(mem_fun_invoker_t const&)=default;
    void operator()(Args&&...args) {
      (t->*m)(static_cast<Args&&>(args)...);
    }
  };
  template<class Sig, class T>
  struct ptr_invoker_t;
  template<class R, class...Args, class T>
  struct ptr_invoker_t<R(Args...), T>:
    invoker_base_t<R(Args...), ptr_invoker_t<R(Args...),T> >
  {
    T* t;
    ptr_invoker_t(T* tin):t(tin) {}
    ptr_invoker_t(ptr_invoker_t const&)=default;
    R operator()(Args&&...args) {
      return (*t)(static_cast<Args&&>(args)...);
    }
  };
  template<class...Args, class T>
  struct ptr_invoker_t<void(Args...), T>:
    invoker_base_t<void(Args...), ptr_invoker_t<void(Args...),T> >
  {
    T* t;
    ptr_invoker_t(T* tin):t(tin) {}
    ptr_invoker_t(ptr_invoker_t const&)=default;
    void operator()(Args&&...args) {
      (*t)(static_cast<Args&&>(args)...);
    }
  };
}
template<class Sig, unsigned Sz=3*sizeof(void*)>
struct fun;
template<class R, class...Args, unsigned Sz>
struct fun<R(Args...), Sz> {
  using invoker_t = R(*)(void*, Args&&...);
  invoker_t invoker;
  unsigned char buffer[Sz];
  template<class T, class M>
  static details::mem_fun_invoker_t<R(Args...), T, M> mem_fun_invoker(T* t, M m){ return {t, m}; }
  template<class T>
  static details::ptr_invoker_t<R(Args...), T> ptr_invoker(T* t){ return {t}; }
  template<class T, class U, class Ret, class...Ts>
  fun(T* t, Ret(U::*mem)(Ts...)) {
    auto invoke = mem_fun_invoker( t, mem );
    static_assert(sizeof(invoke) <= Sz);
    ::new( (void*)buffer ) decltype(invoke)(invoke);
    invoker = invoke.invoker();
  }
  template<class T, class U, class Ret, class...Ts>
  fun(T const* t, Ret(U::*mem)(Ts...)const) {
    auto invoke = mem_fun_invoker( t, mem );
    static_assert(sizeof(invoke) <= Sz);
    ::new( (void*)buffer ) decltype(invoke)(invoke);
    invoker = invoke.invoker();
  }

  template<class Ret, class...Ts>
  fun(Ret(*f)(Ts...)) {
    auto invoke = ptr_invoker( f );
    static_assert(sizeof(invoke) <= Sz);
    ::new( (void*)buffer ) decltype(invoke)(invoke);
    invoker = invoke.invoker();
  }
  // TODO: SFINAE
  template<class Lambda>
  fun(Lambda&& lambda) {
    auto invoke = ptr_invoker( &lambda );
    static_assert(sizeof(invoke) <= Sz);
    ::new( (void*)buffer ) decltype(invoke)(invoke);
    invoker = invoke.invoker();
  }
  R operator()(Args...args) {
    return invoker(&buffer, static_cast<Args&&>(args)...);
  }
  explicit operator bool()const {return invoker;}
};

live example.

The above is standards compliant and does not rely upon std.  Writing the SFINAE to ensure the Lambda&& overload isn't called in bad situation may require rewriting some of std, like std::is_same and enable_if.


问:
How to properly validate 2 or more fields together in Javascript?
I want to validate 2 fields together using JavaScript code.
What i'm doing is disabling the submit button when user enters invalid data.

Something like this:

Disabled Button when incorrect data is entered

The problem is that when i enter invalid data in field 1 the button is disabled but when i add proper form data in second field the button gets enabled again, i even used global variable but the problem still persists.

Button enabled even if data in first field is wrong

My JavaScript code is :

```<code><script>
var sw=0;
function valqid(qid){

 if(isNaN(qid) || parseInt(qid)<0){
  alert("Please Enter Valid Question ID!");
  document.getElementById("button").disabled = true;
  window.sw=1;
 }
 else{
  if(window.sw==0){
  document.getElementById("button").disabled = false;
 }
 }

}

function valans(ans){

 if(parseInt(ans)!=0 && parseInt(ans)!=1){
  alert("Please Enter Valid Answer!");
  document.getElementById("button").disabled = true;
  window.sw=1;
 }
 else{
  if(window.sw==0){
  document.getElementById("button").disabled = false;
 }
 }

}
</script>
</code>```

Here qid and ans are values inputted by user.

Kindly tell me how to make it work properly.
(Validation rules are listed below in image files)

Thanks in advance.

Complete Code HTML is given below:

```<code><html>
 <body>
  <center>
   <form action="add_questions.php" method="POST" name="form4"> <br /> <br />
    <table cellspacing="10" cellpadding="10" border="1">
     <tr> <th> Question ID </th> <th> Question </th> <th> Answer </th> </tr>
     <tr> <td> <input type="text" name="question_id" maxlength="3" minlength="1" onchange="valqid(this.value)" required /> </td> <td> <input type="text" name="question" maxlength="200" minlength="10" id="ques" required /> </td> <td> <input type="text" name="answer" maxlength="1" onchange="valans(this.value)" required /> </td> </tr>
    </table> <br /> <br />
    <input type="submit" value="Add Question" name="add_question" id="button" />
   </form> <br /> <br />
  <p> * Enter Question Id, Question & Answer of the question you want to add. </p>
  <p> * All three are mandatory fields (cannot be empty). </p>
  <p> * Question Id can be 3 numbers (Whole Numbers only) long at most and should be atleast 1 number (character).</p>
  <p> * Question can be 200 characters long at most and should be atleast 10 characters. </p>
  <p> * Answer field should be '1' for 'True' & '0' for 'False'.</p>
  <p> * Question Id must be unique.</p>

<script>
var sw=0;
function valqid(qid){

 if(isNaN(qid) || parseInt(qid)<0){
  alert("Please Enter Valid Question ID!");
  document.getElementById("button").disabled = true;
  window.sw=1;
 }
 else{
  if(window.sw==0){
  document.getElementById("button").disabled = false;
 }
 }

}

function valans(ans){

 if(parseInt(ans)!=0 && parseInt(ans)!=1){
  alert("Please Enter Valid Answer!");
  document.getElementById("button").disabled = true;
  window.sw=1;
 }
 else{
  if(window.sw==0){
  document.getElementById("button").disabled = false;
 }
 }

}
</script>

 </body>
</html> ;
</code>```

答:
You can use this simple way</p>

```<code><script>
function valqid(qid){
 if(isNaN(qid) || parseInt(qid)<0){
  alert("Please Enter Valid Question ID!");
  document.getElementById("button").disabled = true;
 }
 else if(parseInt(ans)!=0 && parseInt(ans)!=1){
  alert("Please Enter Valid Answer!");
  document.getElementById("button").disabled = true;
  }
 else{
     document.getElementById("button").disabled = false;
  }
 }
</script>
</code>```

Body:
I want to validate 2 fields together using JavaScript code.
What i'm doing is disabling the submit button when user enters invalid data.

Something like this:

Disabled Button when incorrect data is entered

The problem is that when i enter invalid data in field 1 the button is disabled but when i add proper form data in second field the button gets enabled again, i even used global variable but the problem still persists.

Button enabled even if data in first field is wrong

My JavaScript code is :

Here qid and ans are values inputted by user.

Kindly tell me how to make it work properly.
(Validation rules are listed below in image files)

Thanks in advance.

Complete Code HTML is given below:

   <form action="add_questions.php" method="POST" name="form4">

  Question ID 	  Question 	  Answer

  <input type="text" name="question_id" maxlength="3" minlength="1" onchange="valqid(this.value)" required /> 	  <input type="text" name="question" maxlength="200" minlength="10" id="ques" required /> 	  <input type="text" name="answer" maxlength="1" onchange="valans(this.value)" required />

    <input type="submit" value="Add Question" name="add_question" id="button" />
   </form>

 * Enter Question Id, Question & Answer of the question you want to add.

 * All three are mandatory fields (cannot be empty).

 * Question Id can be 3 numbers (Whole Numbers only) long at most and should be atleast 1 number (character).

 * Question can be 200 characters long at most and should be atleast 10 characters.

 * Answer field should be '1' for 'True' & '0' for 'False'.

 * Question Id must be unique.

 ;

Body:
You can use this simple way

<script>
function valqid(qid){
 if(isNaN(qid) || parseInt(qid)<0){
  alert("Please Enter Valid Question ID!");
  document.getElementById("button").disabled = true;
 }
 else if(parseInt(ans)!=0 && parseInt(ans)!=1){
  alert("Please Enter Valid Answer!");
  document.getElementById("button").disabled = true;
  }
 else{
     document.getElementById("button").disabled = false;
  }
 }
</script>


问:
Accessing data from the root of a json object JSRender
I am currently creating a report using JSReport. I am now stuck in a scenario wherein I need to access data from inside the for loop. Here is a sample of the json

```<code>{
    "report_date": "",
    "account": "",
    "account_number": "",
    "data_retention": "",
    "data_purged": "",
    "sms_camp_del": "",
    "numbers_purged": "",
    "message_del": "",
    "reports": [{
        "count": 1,
        "campaign_name": "",
        "date": "",
        "start_time": "",
        "messages": "",
        "numbers": ""
    ...
</code>```

And I already have this code

```<code>{{for reports}}
    ...
{{/for}}
</code>```

and from the inside of the for loop I want to access the report_date and the account by using {{:report_date}} and {{:account}}, but the problem is that I cannot seem to output their respective values. How could I possibly access everything outside of the reports? Thank you in advance

答:
Yes, you can use contextual parameters:

```<code>{{for reports ~rd=report_date ~ac=account}}...{{/for}}
</code>```

and access using {{:~rd}} and {{:~ac}}

Another way is to use {{:~root.report_date}} and {{:~root.account}}.

See Accessing parent data and Accessing root data: the built-in '~root' contextual parameter.

Body:
I am currently creating a report using JSReport. I am now stuck in a scenario wherein I need to access data from inside the for loop. Here is a sample of the json

{
    "report_date": "",
    "account": "",
    "account_number": "",
    "data_retention": "",
    "data_purged": "",
    "sms_camp_del": "",
    "numbers_purged": "",
    "message_del": "",
    "reports": [{
        "count": 1,
        "campaign_name": "",
        "date": "",
        "start_time": "",
        "messages": "",
        "numbers": ""
    ...

And I already have this code

{{for reports}}
    ...
{{/for}}

and from the inside of the for loop I want to access the report_date and the account by using {{:report_date}} and {{:account}}, but the problem is that I cannot seem to output their respective values. How could I possibly access everything outside of the reports? Thank you in advance

Body:
Yes, you can use contextual parameters:

{{for reports ~rd=report_date ~ac=account}}...{{/for}}

and access using {{:~rd}} and {{:~ac}}

Another way is to use {{:~root.report_date}} and {{:~root.account}}.

See Accessing parent data and Accessing root data: the built-in '~root' contextual parameter.


问:
Hadoop, Mapreduce - Cannot obtain block length for LocatedBlock
I've a file on hdfs in the path 'test/test.txt' which is 1.3G

output of ls and du commands is:

hadoop fs -du test/test.txt -> 1379081672  test/test.txt

hadoop fs -ls test/test.txt ->

```<code>Found 1 items
-rw-r--r--   3 testuser supergroup 1379081672 2014-05-06 20:27 test/test.txt
</code>```

I want to run a mapreduce job on this file but when i start the mapreduce job on this file the job fails with the following error:

hadoop jar myjar.jar test.TestMapReduceDriver test output

```<code>14/05/29 16:42:03 WARN mapred.JobClient: Use GenericOptionsParser for parsing the
arguments. Applications should implement Tool for the same.
14/05/29 16:42:03 INFO input.FileInputFormat: Total input paths to process : 1
14/05/29 16:42:03 INFO mapred.JobClient: Running job: job_201405271131_9661
14/05/29 16:42:04 INFO mapred.JobClient:  map 0% reduce 0%
14/05/29 16:42:17 INFO mapred.JobClient: Task Id : attempt_201405271131_9661_m_000004_0, Status : FAILED
java.io.IOException: Cannot obtain block length for LocatedBlock{BP-428948818-namenode-1392736828725:blk_-6790192659948575136_8493225; getBlockSize()=36904392; corrupt=false; offset=1342177280; locs=[datanode4:50010, datanode3:50010, datanode1:50010]}
at org.apache.hadoop.hdfs.DFSInputStream.readBlockLength(DFSInputStream.java:319)
at org.apache.hadoop.hdfs.DFSInputStream.fetchLocatedBlocksAndGetLastBlockLength(DFSInputStream.java:263)
at org.apache.hadoop.hdfs.DFSInputStream.openInfo(DFSInputStream.java:205)
at org.apache.hadoop.hdfs.DFSInputStream.<init>(DFSInputStream.java:198)
at org.apache.hadoop.hdfs.DFSClient.open(DFSClient.java:1117)
at org.apache.hadoop.hdfs.DistributedFileSystem.open(DistributedFileSystem.java:249)
at org.apache.hadoop.hdfs.DistributedFileSystem.open(DistributedFileSystem.java:82)
at org.apache.hadoop.fs.FileSystem.open(FileSystem.java:746)
at org.apache.hadoop.mapreduce.lib.input.LineRecordReader.initialize(LineRecordReader.java:83)
at org.apache.hadoop.mapred.Ma`
</code>```

i tried the following commands:

hadoop fs -cat test/test.txt gives the following error

```<code>cat: Cannot obtain block length for LocatedBlock{BP-428948818-10.17.56.16-1392736828725:blk_-6790192659948575136_8493225; getBlockSize()=36904392; corrupt=false; offset=1342177280; locs=[datanode3:50010, datanode1:50010, datanode4:50010]}
</code>```

additionally i can't copy the file hadoop fs -cp test/test.txt tmp gives same error:

```<code>cp: Cannot obtain block length for LocatedBlock{BP-428948818-10.17.56.16-1392736828725:blk_-6790192659948575136_8493225; getBlockSize()=36904392; corrupt=false; offset=1342177280; locs=[datanode1:50010, datanode3:50010, datanode4:50010]}
</code>```

output of the hdfs fsck /user/testuser/test/test.txt command:

```<code>Connecting to namenode via `http://namenode:50070`
FSCK started by testuser (auth:SIMPLE) from /10.17.56.16 for path
/user/testuser/test/test.txt at Thu May 29 17:00:44 EEST 2014
Status: HEALTHY
Total size: 0 B (Total open files size: 1379081672 B)
Total dirs: 0
Total files:    0 (Files currently being written: 1)
Total blocks (validated):   0 (Total open file blocks (not validated): 21)
Minimally replicated blocks:    0
Over-replicated blocks: 0
Under-replicated blocks:    0
Mis-replicated blocks:      0
Default replication factor: 3
Average block replication:  0.0
Corrupt blocks:     0
Missing replicas:       0
Number of data-nodes:       5
Number of racks:        1
FSCK ended at Thu May 29 17:00:44 EEST 2014 in 0 milliseconds
The filesystem under path /user/testuser/test/test.txt is HEALTHY
</code>```

by the way i can see the content of the test.txt file from the web browser.

hadoop version is: Hadoop 2.0.0-cdh4.5.0

答:
I had the same error, but it was not due to the full disk problem, and I think the inverse, where there were files and blocks referenced by in the namenode that did not exist on any datanodes.

Thus, hdfs dfs -ls shows the files, but any operation on them fails, e.g. hdfs dfs -copyToLocal.

In my case, the hard part was isolating which files were listed but corrupted, as they existed in a tree having thousands of files.  Oddly, hdfs fsck /path/to/files/ did not report any problems.

My solution was:

Isolate the location using copyToLocal which resulted in copyToLocal: Cannot obtain block length for LocatedBlock{BP-1918381527-10.74.2.77-1420822494740:blk_1120909039_47667041; getBlockSize()=1231; corrupt=false; offset=0; locs=[10.74.2.168:50010, 10.74.2.166:50010, 10.74.2.164:50010]} for several files

Get a list of the local directories using ls -1 > baddirs.out

get rid of the local files from the first copyToLocal

use for files incat baddirs.out;do echo $files; hdfs dfs -copyToLocal $files This will produce a list of directories checks, and errors where files are found.

get rid of the local files again, and now get lists of files from each affected subdirectory.  Use that as input to a file-by-file copyToLocal, at which point you can echo each file as it's copied, then see where the error occurs.

use hdfs dfs -rm <file> for each file.

Confirm you got 'em all be removing all local files again, and using the original copyToLocal on the top level directory where you had problems.

A simple two hour process!

Body:
I've a file on hdfs in the path 'test/test.txt' which is 1.3G

output of ls and du commands is:

hadoop fs -du test/test.txt -> 1379081672  test/test.txt

hadoop fs -ls test/test.txt ->

Found 1 items
-rw-r--r--   3 testuser supergroup 1379081672 2014-05-06 20:27 test/test.txt

I want to run a mapreduce job on this file but when i start the mapreduce job on this file the job fails with the following error:

hadoop jar myjar.jar test.TestMapReduceDriver test output

14/05/29 16:42:03 WARN mapred.JobClient: Use GenericOptionsParser for parsing the
arguments. Applications should implement Tool for the same.
14/05/29 16:42:03 INFO input.FileInputFormat: Total input paths to process : 1
14/05/29 16:42:03 INFO mapred.JobClient: Running job: job_201405271131_9661
14/05/29 16:42:04 INFO mapred.JobClient:  map 0% reduce 0%
14/05/29 16:42:17 INFO mapred.JobClient: Task Id : attempt_201405271131_9661_m_000004_0, Status : FAILED
java.io.IOException: Cannot obtain block length for LocatedBlock{BP-428948818-namenode-1392736828725:blk_-6790192659948575136_8493225; getBlockSize()=36904392; corrupt=false; offset=1342177280; locs=[datanode4:50010, datanode3:50010, datanode1:50010]}
at org.apache.hadoop.hdfs.DFSInputStream.readBlockLength(DFSInputStream.java:319)
at org.apache.hadoop.hdfs.DFSInputStream.fetchLocatedBlocksAndGetLastBlockLength(DFSInputStream.java:263)
at org.apache.hadoop.hdfs.DFSInputStream.openInfo(DFSInputStream.java:205)
at org.apache.hadoop.hdfs.DFSInputStream.<init>(DFSInputStream.java:198)
at org.apache.hadoop.hdfs.DFSClient.open(DFSClient.java:1117)
at org.apache.hadoop.hdfs.DistributedFileSystem.open(DistributedFileSystem.java:249)
at org.apache.hadoop.hdfs.DistributedFileSystem.open(DistributedFileSystem.java:82)
at org.apache.hadoop.fs.FileSystem.open(FileSystem.java:746)
at org.apache.hadoop.mapreduce.lib.input.LineRecordReader.initialize(LineRecordReader.java:83)
at org.apache.hadoop.mapred.Ma`

i tried the following commands:

hadoop fs -cat test/test.txt gives the following error

cat: Cannot obtain block length for LocatedBlock{BP-428948818-10.17.56.16-1392736828725:blk_-6790192659948575136_8493225; getBlockSize()=36904392; corrupt=false; offset=1342177280; locs=[datanode3:50010, datanode1:50010, datanode4:50010]}

additionally i can't copy the file hadoop fs -cp test/test.txt tmp gives same error:

cp: Cannot obtain block length for LocatedBlock{BP-428948818-10.17.56.16-1392736828725:blk_-6790192659948575136_8493225; getBlockSize()=36904392; corrupt=false; offset=1342177280; locs=[datanode1:50010, datanode3:50010, datanode4:50010]}

output of the hdfs fsck /user/testuser/test/test.txt command:

Connecting to namenode via `http://namenode:50070`
FSCK started by testuser (auth:SIMPLE) from /10.17.56.16 for path
/user/testuser/test/test.txt at Thu May 29 17:00:44 EEST 2014
Status: HEALTHY
Total size: 0 B (Total open files size: 1379081672 B)
Total dirs: 0
Total files:    0 (Files currently being written: 1)
Total blocks (validated):   0 (Total open file blocks (not validated): 21)
Minimally replicated blocks:    0
Over-replicated blocks: 0
Under-replicated blocks:    0
Mis-replicated blocks:      0
Default replication factor: 3
Average block replication:  0.0
Corrupt blocks:     0
Missing replicas:       0
Number of data-nodes:       5
Number of racks:        1
FSCK ended at Thu May 29 17:00:44 EEST 2014 in 0 milliseconds
The filesystem under path /user/testuser/test/test.txt is HEALTHY

by the way i can see the content of the test.txt file from the web browser.

hadoop version is: Hadoop 2.0.0-cdh4.5.0


问:
Get full Url when using Angular2
I would have thought finding this information would be simple with all the work that has gone into Angular2 but apparently not...

1) How can I get the full url of the activated route in Angular2? I know I can call window.location.href but was wondering if there was an Angular way.

2) Is there a way to "build out" a url? If I know when route I want and the parameters for said route, can I construct the full url?

答:
If you build the url and wanna navigate you can use navigateByUrl method

```<code>router.navigateByUrl("/team/33/user/11");
// Navigate without updating the URL
router.navigateByUrl("/team/33/user/11", { skipLocationChange: true});
</code>```

https://angular.io/docs/ts/latest/api/router/index/Router-class.html#!#navigateByUrl-anchor

Title: Get full Url when using Angular2

Body:
If you build the url and wanna navigate you can use navigateByUrl method

router.navigateByUrl("/team/33/user/11");
// Navigate without updating the URL
router.navigateByUrl("/team/33/user/11", { skipLocationChange: true});

https://angular.io/docs/ts/latest/api/router/index/Router-class.html#!#navigateByUrl-anchor


问:
How do I restart airflow webserver?
I am using airflow for my data pipeline project. I have configured my project in airflow and start the airflow server as a backend process using following command

```<code>airflow webserver -p 8080 -D True
</code>```

Server running successfully in backend. Now I want to enable authentication in airflow and done configuration changes in airflow.cfg, but authentication functionality is not reflected in server. when I stop and start airflow server in my local machine it works.

So How can I restart my daemon airflow webserver process in my server??

答:
Use Airflow webserver's (gunicorn) signal handling

Airflow uses gunicorn as it's HTTP server, so you can send it standard POSIX-style signals. A signal commonly used by daemons to restart is HUP.

You'll need to locate the pid file for the airflow webserver daemon in order to get the right process id to send the signal to. This file could be in $AIRFLOW_HOME or also /var/run, which is where you'll find a lot of pids.

Assuming the pid file is in /var/run, you could run the command:

```<code>cat /var/run/airflow-webserver.pid | xargs kill -HUP
</code>```

gunicorn uses a preforking model, so it has master and worker processes. The HUP signal is sent to the master process, which performs these actions:

HUP: Reload the configuration, start the new worker processes with a new configuration and gracefully shutdown older workers. If the application is not preloaded (using the preload_app option), Gunicorn will also load the new version of it.

More information in the gunicorn signal handling docs.

This is mostly an expanded version of captaincapsaicin's answer, but using HUP (SIGHUP) instead of KILL (SIGKILL) to reload the process instead of actually killing it and restarting it.

ContentLicense: CC BY-SA 4.0

Title: How do I restart airflow webserver?

Body:
I am using airflow for my data pipeline project. I have configured my project in airflow and start the airflow server as a backend process using following command

airflow webserver -p 8080 -D True

Server running successfully in backend. Now I want to enable authentication in airflow and done configuration changes in airflow.cfg, but authentication functionality is not reflected in server. when I stop and start airflow server in my local machine it works.

So How can I restart my daemon airflow webserver process in my server??

Body:
Use Airflow webserver's (gunicorn) signal handling

Airflow uses gunicorn as it's HTTP server, so you can send it standard POSIX-style signals. A signal commonly used by daemons to restart is HUP.

You'll need to locate the pid file for the airflow webserver daemon in order to get the right process id to send the signal to. This file could be in $AIRFLOW_HOME or also /var/run, which is where you'll find a lot of pids.

Assuming the pid file is in /var/run, you could run the command:

cat /var/run/airflow-webserver.pid | xargs kill -HUP

gunicorn uses a preforking model, so it has master and worker processes. The HUP signal is sent to the master process, which performs these actions:

HUP: Reload the configuration, start the new worker processes with a new configuration and gracefully shutdown older workers. If the application is not preloaded (using the preload_app option), Gunicorn will also load the new version of it.

More information in the gunicorn signal handling docs.

This is mostly an expanded version of captaincapsaicin's answer, but using HUP (SIGHUP) instead of KILL (SIGKILL) to reload the process instead of actually killing it and restarting it.


问:
Issue with code in .spacemacs file on Spacemacs startup
I have code in the bottom of my .spacemacs file to create some keybindings and such related to evil-mode. The code is as follows:

```<code>;; Evil mode
(use-package evil
  :ensure t
  :config
  (evil-mode 1)

  (use-package evil-escape
    :ensure t
    :config
    (evil-escape-mode 1)
    (setq-default evil-escape-key-sequence "fd")
    (setq-default evil-escape-delay 0.2))

  (use-package evil-leader
    :ensure t
    :config
    (global-evil-leader-mode)
    (evil-leader/set-leader "<SPC>")
    (evil-leader/set-key
      "e" 'find-file
      "bb" 'switch-to-buffer
      "bd" 'kill-buffer-and-window
      "by" 'copy-whole-buffer
      "cy" 'clipboard-kill-ring-save
      "cp" 'clipboard-yank
      "fs" 'save-buffer
      "ms" 'magit-status
      "hs" 'split-window-horizontally
      "iu" 'insert-char
      "lf" 'load-file
      "ne" 'flycheck-next-error
      "pe" 'flycheck-previous-error
      "rm" 'notmuch
      "sm" 'message-send-and-exit
      "si" 'whitespace-mode
      "tn" 'linum-mode
      "tt" 'term
      "w1" 'delete-other-windows
      "wk" 'windmove-left
      "wj" 'windmove-right
      "qq" 'save-buffers-kill-emacs
      "zp" 'zeal-at-point
      )
    )

  (use-package evil-surround
    :ensure t
    :config
    (global-evil-surround-mode))

  (use-package evil-indent-textobject
    :ensure t))
</code>```

For some reason, when I open up Spacemacs with the code in my .spacemacs file, I see the following:

If I remove the code, it opens up correctly, but I can add it back then run M-x eval-region and everything works as expected. I am brand new to Spacemacs from Vim so any help would be much appreciated!

答: You shouldn't have to import the evil package directly. You just need to set the variable dotspacemacs-editing-style to 'vim. Also, any existing packages should be specified in the dotspacemacs-configuration-layers variable. Any packages that don't come with spacemacs can be added via dotspacemacs-additional-packages or you could create a layer if they need additional configuration. For more info see the docs here http://spacemacs.org/doc/DOCUMENTATION.html#dotfile-configuration

Body:
I have code in the bottom of my .spacemacs file to create some keybindings and such related to evil-mode. The code is as follows:

;; Evil mode
(use-package evil
  :ensure t
  :config
  (evil-mode 1)

  (use-package evil-escape
    :ensure t
    :config
    (evil-escape-mode 1)
    (setq-default evil-escape-key-sequence "fd")
    (setq-default evil-escape-delay 0.2))

  (use-package evil-leader
    :ensure t
    :config
    (global-evil-leader-mode)
    (evil-leader/set-leader "<SPC>")
    (evil-leader/set-key
      "e" 'find-file
      "bb" 'switch-to-buffer
      "bd" 'kill-buffer-and-window
      "by" 'copy-whole-buffer
      "cy" 'clipboard-kill-ring-save
      "cp" 'clipboard-yank
      "fs" 'save-buffer
      "ms" 'magit-status
      "hs" 'split-window-horizontally
      "iu" 'insert-char
      "lf" 'load-file
      "ne" 'flycheck-next-error
      "pe" 'flycheck-previous-error
      "rm" 'notmuch
      "sm" 'message-send-and-exit
      "si" 'whitespace-mode
      "tn" 'linum-mode
      "tt" 'term
      "w1" 'delete-other-windows
      "wk" 'windmove-left
      "wj" 'windmove-right
      "qq" 'save-buffers-kill-emacs
      "zp" 'zeal-at-point
      )
    )

  (use-package evil-surround
    :ensure t
    :config
    (global-evil-surround-mode))

  (use-package evil-indent-textobject
    :ensure t))

For some reason, when I open up Spacemacs with the code in my .spacemacs file, I see the following:

If I remove the code, it opens up correctly, but I can add it back then run M-x eval-region and everything works as expected. I am brand new to Spacemacs from Vim so any help would be much appreciated!


问:
Forms in SharePoint
If I want to put a form up on SharePoint, is it easier to use InfoPath or build a custom web part in C#?  Are there other options that I should consider?

What are the requirements and hurdles for each option?

答:
It may deppends on the way you are thinking for

For eg,
 1. you can go for Infopath, if you are trying to give the control to end user inorder to customize the form by own.

Infopath is very easy to understand, develop. In order to use the infopath you have to learn Infopath, Infopath Form Services, and Sharepoint api to integerate Dotnet (C#) and Sharepoint.

OwnerDisplayName: Maitus

ContentLicense: CC BY-SA 2.5

Title: Forms in SharePoint

OwnerDisplayName: guna Samba


问:
Can a git repository be created where branches are clones from other repositories?
Here is the situation:
I have inherited two separate machines, one used for "development" the other is the production machine.  The problem: They are of course out of sync.  In order to bring some sanity to situation I made independent git repositories of the application directory on each machine.

I now wish to be able to compare those repos so I can find out what is different between them.  My idea was to make a third repository that contained two branches, one from the repository of the "dev" machine and one from the repository of the "prod" machine.

Is this or an equivalent solution possible with git ?

Thanks.

答:
This would use what Git calls "remotes," which are references to what a remote repository contains in order for you to be able to pull it into your own branch, push your branch into the remote repository, etc. You can set up a remote for each of the other machines, and then diff between them to compare them, and you can create one or more local branches from those remotes if you want to do local work.

What I'd suggest for your situation is cloning your development repository, which will create your third repository that you'll be working in, and automatically create a remote named origin which points to your development repository (this is the conventional name for the default "upstream" place you will be pulling from an pushing to). Then, add a remote for prod, and now you can compare them and work with them locally. For example:

```<code>git clone me@dev-server:/path/to/repo.git
cd repo
git remote add prod me@prod-server:/path/to/repo.git
git remote update
git diff origin/master prod/master
</code>```

Body:
This would use what Git calls "remotes," which are references to what a remote repository contains in order for you to be able to pull it into your own branch, push your branch into the remote repository, etc. You can set up a remote for each of the other machines, and then diff between them to compare them, and you can create one or more local branches from those remotes if you want to do local work.

What I'd suggest for your situation is cloning your development repository, which will create your third repository that you'll be working in, and automatically create a remote named origin which points to your development repository (this is the conventional name for the default "upstream" place you will be pulling from an pushing to). Then, add a remote for prod, and now you can compare them and work with them locally. For example:

git clone me@dev-server:/path/to/repo.git
cd repo
git remote add prod me@prod-server:/path/to/repo.git
git remote update
git diff origin/master prod/master


问:
Application lifecycle when app is killed in the background
Some background on a problem that I have been encountering: in my app I have a singleton object that I use regularly to access things like id and token for network calls.  Sometimes when the app is killed in the background, this singleton loses its state. However, when the app is opened again and starts up in some Activity past the launcher Activity, the singleton is null.

I am in the process of refactoring this, but have been agonizing over how to ensure that the singleton will always be present even in app restart, but I'm not sure what Android does when the app restarts from being backgrounded.

I went through source code in some of the libraries we use in the app (Facebook, Intercom) to see how they manage their singletons and why their static variables seemed to just always be present, and came upon a theory.

So on a normal app cold start, the app behaves like this:

```<code>Application.onCreate() -> Launcher.onCreate() -> Activity A -> Activity B
</code>```

Say the user was in Activity B and backgrounds the app.  After using some other apps, they come back to my app but it has been killed at some point in between. The lifecycle then becomes this:

```<code>Application.onCreate() -> Activity B
</code>```

I think the problem is that I initialize the singleton in the launcher Activity, and as a result, when B tries to get a value from the singleton, it comes up null.  If I initialize the singleton in Application.onCreate(), it will always be initialized when the app is pulled up again.  Is this correct?

TL;DR An application that is killed and brought to foreground again will always call its Application.onCreate() and then forward directly to the Activity it was on. Therefore, app initializations that are critical to the app functioning should live in the Application onCreate().

答:
A application that is killed and brought to foreground again will always call its Application.onCreate() and then forward directly to the activity it was on. Therefore, app initializations that are critical to the app functioning should live in the Application onCreate().

Correct.

I think the problem is that I initialize the singleton in the LauncherActivity, and as a result, when B tries to get a value from the singleton, it comes up null. If I initialize the Singleton in Application.onCreate(), it will always be initialized when the app is pulled up again. Is this correct?

In your case the problem is really in that. However, if by "it comes up null" you mean the singleton instance is null then it is not how a singleton is supposed to work. No matter where you call singleton's methods from, its instance should not be null.

Body:
Some background on a problem that I have been encountering: in my app I have a singleton object that I use regularly to access things like id and token for network calls.  Sometimes when the app is killed in the background, this singleton loses its state. However, when the app is opened again and starts up in some Activity past the launcher Activity, the singleton is null.

I am in the process of refactoring this, but have been agonizing over how to ensure that the singleton will always be present even in app restart, but I'm not sure what Android does when the app restarts from being backgrounded.

I went through source code in some of the libraries we use in the app (Facebook, Intercom) to see how they manage their singletons and why their static variables seemed to just always be present, and came upon a theory.

So on a normal app cold start, the app behaves like this:

Application.onCreate() -> Launcher.onCreate() -> Activity A -> Activity B

Say the user was in Activity B and backgrounds the app.  After using some other apps, they come back to my app but it has been killed at some point in between. The lifecycle then becomes this:

Application.onCreate() -> Activity B

I think the problem is that I initialize the singleton in the launcher Activity, and as a result, when B tries to get a value from the singleton, it comes up null.  If I initialize the singleton in Application.onCreate(), it will always be initialized when the app is pulled up again.  Is this correct?

TL;DR An application that is killed and brought to foreground again will always call its Application.onCreate() and then forward directly to the Activity it was on. Therefore, app initializations that are critical to the app functioning should live in the Application onCreate().


问:
Recursion trick in ShaderEffectSource fails when I destroy the source object in onStateChanged
I want a ShaderEffectSource called snapshotter that updates on every change of a source item, but when the source item is destroyed, I want snapshotter to retain the last state of the source item.

In my code I use a workaround for a Qt deficiency - setting snapshotter.sourceItem = snapshotter when the previous source item gets destroyed. This works fine when I destroy the old source item e.g. on key press. But when I do it in an onStateChanged handler, I get this error:

ShaderEffectSource: 'recursive' must be set to true when rendering recursively.

But I don't want to set recursive: true, because then snapshotter would start repainting as fast as possible, wasting a lot of processing power.

Any idea why that problem happens considering it works fine when using key press, and/or a workaround?

I realize I'm asking why a hacky solution fails in some cases, but since it works in some cases, I'd like to use the solution anyway as it's very useful.

My code: (main.qml)

```<code>import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480

    Loader {
        active: true
        id: loader
        sourceComponent:
            Rectangle {
                color: "red"
                border.color: "white"
                width: 100
                height: 100
                parent: row

                states: [
                    State {
                        // the condition is always true, in this example code
                        name: "theOnlyState"; when: width === 100
                    }
                ]
                onStateChanged: {
                    if(state === "theOnlyState") {
                        loader.active = false;
                    }
                }
            }
    }

    Row {
        id: row
        ShaderEffectSource {
            id: snapshotItem
            sourceItem: {
                if(loader.status === Loader.Ready) {
                    return loader.item;
                } else {
                    return snapshotItem;
                }
            }
            live: loader.status === Loader.Ready
            width: 100
            height: 100
        }
    }
}
</code>```

Note: I just had an idea: maybe setting recursive: true will not create the problem I mentioned, considering I'd only set it when live == false. Maybe Qt is smart enough not constantly redraw in that case. But I'm not sure how to check if that's true.

答:
Ok, I found an 99%-authorative answer.

The worry about recursive: true that I expressed in the question was provoked by my vague memory of reading something like that in the Qt docs.

I now went ahead and looked up the relevant passage again, and here's what it says:

Setting both this property and live to true will cause the scene graph to render continuously. Since the ShaderEffectSource depends on itself, updating it means that it immediately becomes dirty again.

Note how they say that for the bad scenario to occur, live has to be true.

So the solution is to simply use recursive: true, which makes the solution much less hacky.

Note: I'm not gonna mark this answer accepted, because I'd like people to still go over it now and then and maybe, just maybe, prove me wrong (e.g. show that I'm misinterpreting the text).

More evidence in favor of the above conclusion:

I set the env var QSG_VISUALIZE to changes and ran this trivival test app:

```<code>import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    ShaderEffectSource {
        width: 100
        height: 100
        id: shaderEffectSource
        live: false
        sourceItem: shaderEffectSource
        recursive: true
    }
}
</code>```

It showed an unchanging colored square. But when I changed live to true in this code, it started flickering in random colors.

Body:
I want a ShaderEffectSource called snapshotter that updates on every change of a source item, but when the source item is destroyed, I want snapshotter to retain the last state of the source item.

In my code I use a workaround for a Qt deficiency - setting snapshotter.sourceItem = snapshotter when the previous source item gets destroyed. This works fine when I destroy the old source item e.g. on key press. But when I do it in an onStateChanged handler, I get this error:

ShaderEffectSource: 'recursive' must be set to true when rendering recursively.

But I don't want to set recursive: true, because then snapshotter would start repainting as fast as possible, wasting a lot of processing power.

Any idea why that problem happens considering it works fine when using key press, and/or a workaround?

I realize I'm asking why a hacky solution fails in some cases, but since it works in some cases, I'd like to use the solution anyway as it's very useful.

My code: (main.qml)

import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480

    Loader {
        active: true
        id: loader
        sourceComponent:
            Rectangle {
                color: "red"
                border.color: "white"
                width: 100
                height: 100
                parent: row

                states: [
                    State {
                        // the condition is always true, in this example code
                        name: "theOnlyState"; when: width === 100
                    }
                ]
                onStateChanged: {
                    if(state === "theOnlyState") {
                        loader.active = false;
                    }
                }
            }
    }

    Row {
        id: row
        ShaderEffectSource {
            id: snapshotItem
            sourceItem: {
                if(loader.status === Loader.Ready) {
                    return loader.item;
                } else {
                    return snapshotItem;
                }
            }
            live: loader.status === Loader.Ready
            width: 100
            height: 100
        }
    }
}

Note: I just had an idea: maybe setting recursive: true will not create the problem I mentioned, considering I'd only set it when live == false. Maybe Qt is smart enough not constantly redraw in that case. But I'm not sure how to check if that's true.

Body:
Ok, I found an 99%-authorative answer.

The worry about recursive: true that I expressed in the question was provoked by my vague memory of reading something like that in the Qt docs.

I now went ahead and looked up the relevant passage again, and here's what it says:

Setting both this property and live to true will cause the scene graph to render continuously. Since the ShaderEffectSource depends on itself, updating it means that it immediately becomes dirty again.

Note how they say that for the bad scenario to occur, live has to be true.

So the solution is to simply use recursive: true, which makes the solution much less hacky.

Note: I'm not gonna mark this answer accepted, because I'd like people to still go over it now and then and maybe, just maybe, prove me wrong (e.g. show that I'm misinterpreting the text).

More evidence in favor of the above conclusion:

I set the env var QSG_VISUALIZE to changes and ran this trivival test app:

import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    ShaderEffectSource {
        width: 100
        height: 100
        id: shaderEffectSource
        live: false
        sourceItem: shaderEffectSource
        recursive: true
    }
}

It showed an unchanging colored square. But when I changed live to true in this code, it started flickering in random colors.


问:
Input won't trim
Brand new to this but I'm not sure what I am doing wrong as the output will not trim.</p>

```<code>package cs520.hw3.part1;

import javax.swing.JOptionPane;

public class StringTest {

    public static void main(String[] args) {

        String input = JOptionPane.showInputDialog("Enter data using the format Name, Age, City");
        //String delimiter = ",";
        //String[] tokens = input.split(delimiter);
        System.out.println(input.trim());
    }
}
</code>```

答:
The trim() method returns a copy of your string with leading and trailing white space removed, or the same string if it has no leading or trailing white space.

Example:

```<code>import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str = new String("   Some string with whitespace in front and after it.   ");

      System.out.print("Return Value :" );
      System.out.println(Str.trim() );
   }
}
</code>```

Output:

```<code>Return Value :Some string with whitespace in front and after it.
</code>```

Title: Input won't trim

Body:
Brand new to this but I'm not sure what I am doing wrong as the output will not trim.

package cs520.hw3.part1;

import javax.swing.JOptionPane;

public class StringTest {

    public static void main(String[] args) {

        String input = JOptionPane.showInputDialog("Enter data using the format Name, Age, City");
        //String delimiter = ",";
        //String[] tokens = input.split(delimiter);
        System.out.println(input.trim());
    }
}

Body:
The trim() method returns a copy of your string with leading and trailing white space removed, or the same string if it has no leading or trailing white space.

Example:

import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str = new String("   Some string with whitespace in front and after it.   ");

      System.out.print("Return Value :" );
      System.out.println(Str.trim() );
   }
}

Output:

Return Value :Some string with whitespace in front and after it.


问:
Progress Bar with HTML and CSS
I want to create a progress bar like in the below image:

I have no idea about creating this. Should I use HTML5 techniques?

Would you please give me some help about creating this progress bar?

答:
```<code>.bar {
background - color: blue;
height: 40 px;
width: 40 px;
border - style: solid;
border - right - width: 1300 px;
border - radius: 40 px;
animation - name: Load;
animation - duration: 11 s;
position: relative;
animation - iteration - count: 1;
animation - fill - mode: forwards;
}

@keyframes Load {
100 % {
    width: 1300 px;border - right - width: 5;
}
</code>```

Title: Progress Bar with HTML and CSS


问:
Chronicle Queue: blockSize, index count and size guidance
The ChronicleQueueBuilder interface (4.5) allows parameterisation of the queue file characteristics. By default I get 80mb files for daily rollover.

Is there any guidance how one should use these values?

What are the trade-offs? Can I optimize it to let an appender seek to an index quickly?

If I know my average excerpt size and the average number
of excerpts per period, can I choose these values to avoid resizing
of the queue file during the day?

答:
Unless you have a reason to change it I would leave it as it is. If you make the chunk size smaller it might use less space on windows though on linux it uses sparse files so it won't make a difference.

You could increase the chunk size to 1 GB or more however  if you are concerned about the cost of resizing I suggest calling the pretoucher() in another thread periodically to ensure there is always headroom.


问:
Prevent flashing of full text when using Jquery dotdotdot to truncate
We're using this Jquery dotdotdot plugin to truncate some multiline HTML to a specific number of lines. It works great except that, on page load there's a flash, where the full text is initially displayed before it is truncated. We activate the plugin using the call $(".dotdot200").dotdotdot({height:200}); on window ready. How can we prevent the flash from happening?

答:
Set your element to overflow: hidden, and the height to the same height you set in the jQuery call.

This will flash only the ellipses, and not all the extra truncated text.