text:
Q: How to implement asynchronous processing with J2EE application I have an enterprise application with around 2k concurrent users every day.  These users handle customer calls so application speed is of vital importance.
When a user is wrapping up a call they commit all the information they captured. This commit can take anywhere from 10-45 seconds.
I am looking into ways to take the delay away from the user.
We have a web front end running in I.E. the backend is heavy java running on a single EJB.
I wanted to make this commit process asynchronous in that once the user submits the request they don't have to wait for the commit to finish before going on to the next customer. This is what is currently implemented.
Originally I was thinking of just spawning another thread to handle the commit but that's a no no with EJB's.
Other options I can think of would be using JMS or SIB,
What would the best solution be? Is there another alternative I am missing?

A: There are actually two alternatives for cases like that.

*

*The first one will be to use JMS. It has the advantage that the server provides all required infrastructure and you haven't to implement much yourself.

*Another way will be to register the request in a database and have a scheduled event to process all of them.

What you select depends on your requirements. If you need to serve the requests as soon as they arrive, then you need to go with JMS. In both cases you need to persist the outcome of the request in a database and design a web service at the top of it. The front end could use this (through pollling) to present the result to the user.

A: Would have liked to leave a comment, but don't have the ability.
Another possibility:
Wrap the heavy EJB's in a queue mechanism, and expose a different bean with the same API so your client-facing communications talk to the new bean and are quick. They accept the request, add the job to the queue and return to the client immediately. You don't need to change the heavy EJB's or the client communications, just put a mediator in the way, and add a layer of wrapping.


text:
Q: How to fix "Uncaught TypeError: Cannot call method 'appendChild' of null" I am attempting to grab text from a HTML text area, and call the create() method when a 'Submit' button is pressed. The method is trying to use the message from the text area, and post that to its own p tag with class, and post a date stamp in its own p tag, and its own class.
These will both be in the div 'comments'. The error I am getting (using developer tools in Chrome), is

Uncaught TypeError: Cannot call method 'appendChild' of null.

This is aimed at "cmt.appendChild(divTag);". I am very new to Javascript, and this is just practise for me to increase my skills. All help is greatly appreciated!
var cmt = document.getElementById('comments');

function create() {

    var username = 'User',
        message = document.getElementById("textBox").value,
        divTag = document.createElement('div'),
        p1 = document.createElement('p'),
        p2 = document.createElement('p');

    divTag.className = 'comment';

    p1.className = 'date';
    p1.innerHTML = new Date();
    divTag.appendChild(p1);

    p2.className = 'message';
    p2.innerHTML = username + ': ' +message;
    divTag.appendChild(p2);

    cmt.appendChild(divTag);
}

A: The error you are getting suggests that there is no element with the ID "comments" on your page. document.getElementById will return null when no element with such an ID is found, and thus cmd.appendChild(divTag) will be executed as null.appendChild(divTag).
If you are certain that the element exists, you may be executing your JavaScript that assigns the cmt variable before that element is created by the browser. To prevent that, standard practice is to place the <script> tag which includes your external JavaScript just before the closing </body> tag.
If you can't move your script tag for some reason, try running the code that assigns the variable with $(document).ready() (jQuery) or equivalent.

A: Your code works if the required elements exist. As you can see in this Fiddle.
Works if HTML is similar to:
<div id="comments">
    <input id="textBox" type="textBox" value="Hello" />
</div>

My guess is that one of the identifiers might be misspelled or the element as you expect it does not exist.
However, if you are running the script in an external file it might try to execute before the document is fully loaded, hence your script is referring to elements not yet ready in the DOM.
In jQuery you would wrap a $(document).ready(function(){// your code here..}) around.
There is some details on how to do this in just JavaScript in this SO post: Documen Ready equivalent without jQuery.

A: Actually, his code is fine. Its just that JavaScript runs BEFORE HTML. A simple fix is to nest all of your code inside of a function with any name. Then use window.onload to run the function after the HTML is loaded. so basically:
window.onload = function any_name()
{
//code to be executed
}

This is useful especially if you do not want to move your script tag. I generally like to leave the tag where it is.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extract and explode embedded json fields in apache spark I'm completely new to spark, but don't mind if the answer is in python or Scala. I can't show the actual data for privacy reasons, but basically I am reading json files with a structure like this:
    {
      "EnqueuedTimeUtc": 'some date time',
      "Properties": {},
      "SystemProperties": {
          "connectionDeviceId": "an id",
          "some other fields that we don't care about": "data"
      },
      "Body": {
        "device_id": "an id",
        "tabs": [
            {
              "selected": false,
               "title": "some title",
               "url": "https:...."
            },
            {"same again, for multiple tabs"}
        ]
     }
   }

Most of the data is of no interest. What I want is a Dataframe consisting of the time, device_id, and url. There can be multiple urls for the same device and time, so I'm looking to explode these into one row per url.
| timestamp | device_id | url |
My immediate problem is that when I read this, although it can work out the structure of SystemProperties, Body is just a string, probably because of variation. Perhaps I need to specify the schema, would that help?
root
 |-- Body: string (nullable = true)
 |-- EnqueuedTimeUtc: string (nullable = true)
 |-- SystemProperties: struct (nullable = true)
 |    |-- connectionAuthMethod: string (nullable = true)
 |    |-- connectionDeviceGenerationId: string (nullable = true)
 |    |-- connectionDeviceId: string (nullable = true)
 |    |-- contentEncoding: string (nullable = true)
 |    |-- contentType: string (nullable = true)
 |    |-- enqueuedTime: string (nullable = true)

Any idea of an efficient (there are lots and lots of these records) way to extract urls and associate with the time and device_id? Thanks in advance.

A: Here's an example for extraction. Basically you can use from_json to convert the Body to something that is more structured, and use explode(transform()) to get the URLs and expand to different rows.
# Sample dataframe

df.show(truncate=False)
+----------------------------------------------------------------------------------------------------------------------------------------------+---------------+----------------+
|Body                                                                                |EnqueuedTimeUtc|SystemProperties|
+----------------------------------------------------------------------------------------------------------------------------------------------+---------------+----------------+
|{"device_id":"an id","tabs":[{"selected":false,"title":"some title","url":"https:1"},{"selected":false,"title":"some title","url":"https:2"}]}|some date time |[an id]         |
+----------------------------------------------------------------------------------------------------------------------------------------------+---------------+----------------+

df.printSchema()
root
 |-- Body: string (nullable = true)
 |-- EnqueuedTimeUtc: string (nullable = true)
 |-- SystemProperties: struct (nullable = true)
 |    |-- connectionDeviceId: string (nullable = true)

# Extract desired properties

df2 = df.selectExpr(
    "EnqueuedTimeUtc as timestamp",
    "from_json(Body, 'device_id string, tabs array<map<string,string>>') as Body"
).selectExpr(
    "timestamp",
    "Body.device_id",
    "explode(transform(Body.tabs, x -> x.url)) as url"
)

df2.show()
+--------------+---------+-------+
|     timestamp|device_id|    url|
+--------------+---------+-------+
|some date time|    an id|https:1|
|some date time|    an id|https:2|
+--------------+---------+-------+


text:
Q: When does Moiraine say 'she asked questions'? In The Eye of the World, the first novel in The Wheel of Time saga:

[Moiraine] smiled drily at his surprise, "I told you I asked questions."

I don't recall reading that she has said that. Where and when in the novel does she say this?

A: To be frank, I cannot think of anything she said up to that point that would convey the impression that she is generally inquisitive, or that she asked a lot of questions during her stay, both of which would be reasonably valid interpretations of the phrase "I ask questions" in context. I read basically all the scenes where she appears up to that point, and here are the few candidates I found:

Her smile did fade then, slowly, as if something had been recalled to
her. For a moment she merely looked at him. "I am a student of
history," she said at last, "a collector of old stories. This place
you call the Two Rivers has always interested me. Sometimes I study
the stories of what happened here long ago, here and at other places."

In this quote, she indicates a certain curiosity with regard to Two Rivers, which is however framed as academic, and is not connected  with asking questions in particular. Also, she is talking about an interest in ancient history, specifically, which does not seem particularly related to knowing the ages of its residents in the present day.
It could also be a reference to this:

"Perhaps now," Moiraine said quietly, "you will answer a few of my
questions. I have answered yours freely enough."

However, this quote does not include a statement of a proclivity for asking questions in general, and it certainly does not set up her knowing their ages.
Short of authorial error, which seems like the most probable explanation, it is not impossible that Moiraine said this "offscreen", so to speak. and that this represents the first time that the reader is meant to be informed of it. It is a bit more subtle and experimental than I would expect from Robert Jordan, but it is not at all out of the question.


text:
Q: SendFrom feature of Bitcoind I have a server and I would like to host multiple wallets of bitcoin. I synced the node and it's fully synced.
I want to handle the balance of all the accounts individually, so that while sending coins, the node won't send the balance of any other account.
I made few experiments like I tried to first createrawtransaction, then fundrawtransaction then sign & finally sendrawtransaction.
The issue is that it sends the balance from default account and results in -ve balance of any account (this is wrong).
Then I tried to send btc using sendfrom. this works fine (deducts balance from the account) but when I made transaction, I didn't get confirmations still after 3 hrs. The fee given was $5 and the transaction amount was $20.
Using same fee and transaction amount, I made transaction through create,fund,sign & send rawtransaction & it got accepted.
How to make these transactions accepted using sendfrom?


text:
Q: How to create diagonal inputs I want to create a diagonal input like this:

I know how I make the colors and every thing but
I don't know how I make borders like that

#nameinp{
 border-right:5px #4d0026 solid;
 border-left:none;
 border-bottom:none;
 border-top:none;
 background-color:#e6e6e6;
 width:140px;
 height:25px;
 text-align:center;
 font-size:17px;
}

what I add to this

A: Use  skewX().This  skews an element along the X-axis by the given angle.

#nameinp{
 border-right:5px #4d0026 solid;
 border-left:none;
 border-bottom:none;
 border-top:none;
 background-color:#e6e6e6;
 width:140px;
 height:25px;
 text-align:center;
 font-size:17px;
  -ms-transform: skewX(20deg); /* IE 9 */
    -webkit-transform: skewX(20deg); /* Safari */
    transform: skewX(20deg);
}
<input type="text" id="nameinp"/>

If you want the placeholder straight wrap another layer over the input and skew it.Then skew the inner input the exact opposite amount.

#nameinp {
  border-right: 5px #4d0026 solid;
  border-left: none;
  border-bottom: none;
  border-top: none;
  background-color: #e6e6e6;
  width: 140px;
  text-align: center;
  font-size: 17px;
  -ms-transform: skewX(20deg);
  /* IE 9 */
  -webkit-transform: skewX(20deg);
  /* Safari */
  transform: skewX(20deg);
}

#nameinp input {
  height: 25px;
  width: 128px;
  background: #e6e6e6;
  -ms-transform: skewX(-20deg);
  /* IE 9 */
  -webkit-transform: skewX(-20deg);
  /* Safari */
  transform: skewX(-20deg);
  border: none;
}

  <input type="text" placeholder="Enter" />

A: Here is an alternate solution that skews the outer  and not the inner <input>
It is still not perfect, but it does not skew the text or placeholder in the input field.

.skewed {
  border: 1px solid transparent;
  border-right: 5px solid #4d0026;
 background-color:#e6e6e6;
  display: inline-block;
  -ms-transform: skewX(20deg); /* IE 9 */
  -webkit-transform: skewX(20deg); /* Safari */
  transform: skewX(20deg);
}

.skewed > input {
  border: none;
  background-color: transparent;
  font-size: 17px;
 height: 25px;
  margin: 0 5px;
 text-align :center;
  -ms-transform: skewX(-20deg); /* IE 9 */
  -webkit-transform: skewX(-20deg); /* Safari */
  transform: skewX(-20deg);
 width: 140px;
}
<input type="text" id="nameinp" placeholder=""/>


text:
Q: Call Method from Linq query I am using Linq query and call method Like..
oPwd = objDecryptor.DecryptIt((c.Password.ToString())

it will return null value.
Means this will not working.
how I Resolve this.
Thanks..
var q =
    from s in db.User
    join c in db.EmailAccount on s.UserId equals c.UserId
    join d in db.POPSettings
        on c.PopSettingId equals d.POPSettingsId
    where s.UserId == UserId && c.EmailId == EmailId
    select new
    {
        oUserId = s.UserId,
        oUserName = s.Name,
        oEmailId = c.EmailId,
        oEmailAccId = c.EmailAccId,
        oPwd = objDecryptor.DecryptIt(c.Password.ToString()),
        oServerName = d.ServerName,
        oServerAdd = d.ServerAddress,
        oPOPSettingId = d.POPSettingsId,
    };

A: If that is LINQ-to-SQL or Entity Framework. You'll need to break it into steps (as it can't execute that at the DB). For example:
var q = from s in db.User
        join c in db.EmailAccount on s.UserId equals c.UserId
        join d in db.POPSettings on c.PopSettingId equals d.POPSettingsId
        where s.UserId == UserId && c.EmailId == EmailId
        select new
        {
            oUserId = s.UserId,
            oUserName = s.Name,
            oEmailId = c.EmailId,
            oEmailAccId = c.EmailAccId,
            oPwd = c.Password,
            oServerName = d.ServerName,
            oServerAdd = d.ServerAddress,
            oPOPSettingId = d.POPSettingsId,
        };

then use AsEnumerable() to break "composition" against the back-end store:
var query2 = from row in q.AsEnumerable()
        select new
        {
            row.oUserId,
            row.oUserName,
            row.oEmailId,
            row.oEmailAccId,
            oPwd = objDecryptor.DecryptIt(row.oPwd),
            row.oServerName,
            row.oServerAdd,
            row.oPOPSettingId
        };

A: var q = from s in db.User
    join c in db.EmailAccount on s.UserId equals c.UserId
    join d in db.POPSettings on c.PopSettingId equals d.POPSettingsId
    where s.UserId == UserId && c.EmailId == EmailId
    select new
    {
        oUserId = s.UserId,
        oUserName = s.Name,
        oEmailId = c.EmailId,
        oEmailAccId = c.EmailAccId,
        oPwd = c.Password,
        oServerName = d.ServerName,
        oServerAdd = d.ServerAddress,
        oPOPSettingId = d.POPSettingsId,
    };

foreach (var item in q)
        {
            item.oPwd = objDecryptor.DecryptIt(row.oPwd),
        }

we can use a foreach loop also to update a single property. do not need to select all property in next query.

A: This has nothing about Linq query. you need to debug method objDecryptor.DecryptIt


text:
Q: Many-to-many relationship multiple drop-downs widget I am using Django1.9. I have a many-to-many relationship in my model between Person and Language. I want to find a way to select a language in html  widget(drop-down), and after selecting one language another drop-down should appear below, allowing selecting of one more language. One person can maximum have 8 languages.
My questions is how to implement it in Django? Should I create a custom widget for such case?
Thank you for any help.

A: I guess this is what you are looking after
https://github.com/goinnn/django-multiselectfield


text:
Q: Call Function After Event Listener Completes - Javascript Is there a way to call a function in Javascript when an EventListener has completed running any attached code? I am using an external library with an EventListener, which performs a specific action when the Listener is called. I need to run my function after the external library's code finishes running.
I'm asking for a sort of EventListener that I can place on an EventListener to see when an EventListener has completed its task.
I cannot take the source code and put it in my file, and I cannot directly place my function call at the end of the external library's EventListenerHandler in their code. I also do not initiate the Event or the EventListener, so I don't think I can place a callback function on it (I'm still new to Javascript, so maybe, I'm not entirely sure). The event does not use AJAX.
EventListener --> EventListener --> Event
How can this be done?

Here is a picture of my EventListeners. In my specific case, I want to execute the following piece of code after the External Library catches the Event with the has_many_add:after EventListener, and finishes running the code in the associated Handler :
$('select.user_select').select2({
  minimumInputLength: 2
})

The external library performs a callback when the button is clicked:
$(document).on('click', 'a.button.has_many_add', function(e) {
  var before_add, fieldset, html, index, parent, regex;
  e.preventDefault();
  parent = $(this).closest('.has_many_container');
  parent.trigger(before_add = $.Event('has_many_add:before'), [parent]);
  if (!before_add.isDefaultPrevented()) {
    index = parent.data('has_many_index') || parent.children('fieldset').length - 1;
    parent.data({
      has_many_index: ++index
    });
    regex = new RegExp($(this).data('placeholder'), 'g');
    html = $(this).data('html').replace(regex, index);
    fieldset = $(html).insertBefore(this);
    recompute_positions(parent);
    return parent.trigger('has_many_add:after', [fieldset, parent]);
  }
});

I can't change this code, and I need my function to go after this call to has_many_add:after EventListener. I tried using the following:
$(".button has_many_add").click(function(){
  $('select.user_select').select2({
    minimumInputLength: 2
  });
});

However, this code seems to execute before the external library's event handlers do.

A: As long as your external library doesn't stop the event from bubbling you should be able to do this:
$(document).on('has_many_add:after', function(){
    //do your stuff
});

A: This is a really common thing, especially in jQuery. Most jQuery functions actually support this through callbacks.
Here's an example:
$(document).on('click', 'div', function() {
    console.log("a div got clicked, so naturally we're running cool stuff when it completes");
});

In that example, the console.log and everything between those callback braces will run only when a div is clicked on your document.
You can also define a function outside of this listener, then call it from inside when the callback is triggered:
function myFunction (){
    console.log("doing more stuff after the event listener is triggered");
});

$(document).on('click', 'div', function() {
    console.log("a div got clicked, so naturally we're running cool stuff when it completes");
    myFunction(); // invokes our other function
});


text:
Q: If I run any command on the toplevel window of tkinter, then it get automatically destroyed. I want to keep it unless user destroy it I have imported different files as make it as a toplevel in a function. That function is being called in menubar. Whenever I try to login then either if it is successfull or not it directly goes to parent window. Here goes some lines.
class Interface:
    def __init__(self,master):
        self.master=master
        self.master.title('Omen Retail Store')
        self.master.state('zoomed')
        self.style = ttk.Style()
        self.style = ThemedStyle(self.master)
        self.style.set_theme('scidgreen')

        #Here Are some Buttons to call function ignore that#

    def register(self):
        master=Toplevel()
        Register.Register_Interface(master)
        master.bind('<Escape>', lambda e: master.destroy())

    def login(self):
        master=Toplevel()
        Login.Login_Interface(master)
        master.bind('<Escape>', lambda e: master.destroy())
    def images(self):
        master=Toplevel()
        slideshow.Slide_Image(master)
        master.bind('<Escape>', lambda e: master.destroy())

    def admin_login(self):
        master=Toplevel()
        admin_login.Admin_Interface(master)
        master.bind('<Escape>', lambda e: master.destroy())

def main():
    master=Tk()
    root=Interface(master)
    master.wm_attributes('-alpha',1)
    master.mainloop()

if __name__ == '__main__':main()


text:
Q: Redefine variables inside if and use it outside like php I need to pass a variables depend on if, I wrote this code
var firstFoo  = 2;

$('div').click(function() {
    if(firstFoo == 1){
        var
            var1 = 'var1',
            var2 = 'var2',
            var3 = 'var3';
    }
    else{
        var
            var1 = 'no var1',
            var2 = 'no var2',
            var3 = 'no var3';
    }

    $('',{
        'data-var1': var1,
        'data-var2': var2,
        'data-var3': var3
    }).insertAfter(this);
});

The code works fine see example on jsfiddle http://jsfiddle.net/Xn7xG/
But when I click JSHint I got errors
(var is already defined) & (var used out of scope)

And I don't know if that mean my code not working as it should on all browsers and situations
What the right way to write this code above?

A: In javascript there is no concept of block scope, all variables will be declared in the respective function scope/global scope.
In your case you are declaring the same variables twice in the same functional scope, that is the reason for the warning.... even though you declare a variable at the bottom of the page, its scope will be the entire pages because of Hoisting also this
var firstFoo = 2;

$('div').click(function () {
    var var1, var2, var3;
    if (firstFoo == 1) {
        var1 = 'var1';
        var2 = 'var2';
        var3 = 'var3';
    } else {
        var1 = 'no var1';
        var2 = 'no var2';
        var3 = 'no var3';
    }

    $('', {
        'data-var1': var1,
        'data-var2': var2,
        'data-var3': var3
    }).insertAfter(this);
});


text:
Q: Show $\ln2 = \sum_\limits{n=1}^\infty\frac1{n2^n}$ Problem:
Show that $$\ln2 = \sum_\limits{n=1}^\infty\frac1{n2^n}.$$
My progress:
The problem before this one had me find the Taylor series for $\ln(1-x)$ which was $$-\sum\limits_{n=1}^\infty \frac{x^n}n$$
so I figured I'd use $x=-1$ and plug that into the Taylor series. However, there was a side note stating that the Taylor series I found is only valid for $x\in(-1, 1)$. And in any case, my calculation isn't going anywhere, since I end up with the series $1-\frac12+\frac13-\frac14\cdots$
Question 1: How can I use this to solve the problem stated initially, and in the title?
Question 2: I can see why $x$ is restricted to be less than 1, to prevent taking the log of zero or a negative. Why is it not valid for x greater than 1?

A: Hint: $\ln 2 = - \ln (1/2)$. Can you use that and your result on the series for $\ln (1-x)$ to solve the problem?

A: A different perspective: Your series is the Euler transform of $$ 1-\frac{1}{2}+\frac{1}{3}-\frac{1}{4}+\ldots$$ and so it has an equal sum.

A: Hint:
$$\frac1{1-x}=\sum_{n=0}^\infty x^n\;,\;\;|x|<1\implies-\log(1-x)=\sum_{n=0}^\infty\frac{x^{n+1}}{n+1}=x+\sum_{n=2}^\infty\frac{x^n}n$$

A: For similar cases, where you cannot simply evaluate inside the radius of convergence... There is Abel's theorem with conditions that let you evaluate exactly on the radius of convergence.


text:
Q: Firebase Realtime Database rules not working on the website I have been searching in this forum that has helped me a lot to develop my entire project in firebase but I have not been able to find the answer to my question.
I have created a small voting app where users register and can only vote if they have verified their email. Every time a user registers, a verification email is sent with the sendEmailVerification() method.  Obviously I can (and I will) hide/show the UI based on user.emailVerified value (true or false) but for more security, I have configured the following rules:
{
"rules": {
  //only users can write, noone can read
  ".read": false,
  ".write": "auth.uid != null",
    "users": {
      "$uid": {
      //Inside /users, users can read/write in child /$uid only if the $uid of the user matches with the /$uid that is the branch name    for each user
      ".read": "$uid === auth.uid",
      ".validate": "$uid === auth.uid",
        "votos": {
        //only users that verified the email can read/write in this child object
        ".validate": "auth.token.email_verified === true",

        }
      }
    },

    "lists": {
    //only users that verified the email can read/write here
    //read is public because you dont need to be logged in to see the votes of the lists
    ".read": true,
    ".validate": "auth.token.email_verified == true",
    }
  }
}

I have done tests in the console simulator and everything seems to work correctly but when I go to the web it does not let me vote even though I have verified my email.
Basically I can only think of:

*

*I have not configured the rules correctly (but the console simulator gives me the results I expect)

*I have not configured the validations correctly

*It is not enough to send the verification email. Could it be that when the user verifies the mail, a token or something should be included in the url or in the user's data? I believe that ".validate": "auth.token.email_verified === true", is done with the true or false value of user.emailVerified of the user, but I am not an expert in this...

The only thing I've seen similar is problems related to user.emailVerified not being updated after clicking the verification link and this made the value always false. But again, I have no idea.
If anyone can help me, I really appreciate it. This is my first question on the forum, sorry if I did something wrong.


text:
Q: ajax loading do not working with async:false I'm trying to make loading appear before making a request using ajax and even then the screen is only locked.
JS:
function showEstoque(productId) {
    if (url !== '' && url != '-1') {
        if (active) {
            hideEstoques(active);
        }
        var target = document.getElementById("productInfo" + productId);

        target.innerHTML = generateRows(productId);
        target.style.display = "block";
        active = productId;
    }
}

function hideEstoques(productId) {
    document.getElementById("productInfo" + productId).style.display = "none";
    active = null;
}

function generateRows(productId) {
    var rows = '';

    rows += generateRowsEstoque(productId);
    rows += generateRowsReserva(productId);

    return rows;
}

function generateRowsEstoque(productId) {
    var textContent = searchE(productId);
    var parse = JSON.parse(textContent);

    var data = parse.length ? parse[0].nothing : null;

    if (!data)
        return 'Nothing

Nothing

';

    var rows = 'Nothing

 Nothing

';

    for(var n=0; n < data.length; n++) {
        rows += '
' +
            '' + data[n].nothing + '	' +
            '
';
    }
    rows += '

';

    return rows;
}

function searchE(productId) {

    var view_data = "[]";
    jQuery.ajax({
        url: url + "product/" + productId,
        type: "GET",
        dataType: "text",
        async: false,
        success: function (response_data) {
            if (response_data == undefined){
                view_data=0;
                return view_data;
            }
            view_data = response_data.replace(/\r\n/g, "");
        },
        error: function (xhr, textStatus, thrownError){
            if(xhr.status == 404){
                view_data=0;
            }else{
                 view_data=0;
            }
        }
    });

    return view_data;
}

function generateRowsReserva(productId) {

    var textContent = searchEReserva(productId);
    var parse = JSON.parse(textContent);

    var data = parse.length ? parse : null;

    if (!data)
        return '

Nothing

';

    var foo = data.filter(function(p) { return p.idType === 'foo' });
    var bar = data.filter(function(p) { return p.idType === 'bar' });

    var fooQtd = foo.length ? foo[0].nothing : 0;
    var barQtd = bar.length ? bar[0].nothing : 0;

    var rows = '

 Nothing

';
    rows += '
' +
        '' + fooQtd + '	' +
        '' + barQtd + '	' +
        '
';
    rows += '

';

    return rows;
}

function searchEReserva(productId) {

    var view_data = "[]";
    $j.ajax({
        url: "url" + productId,
        type: "GET",
        dataType: "text",
        async: false,
        success: function (response_data) {
            if (response_data == undefined){
                view_data=0;
                return view_data;
            }
            view_data = response_data.replace(/\r\n/g, "");
        },
        error: function (xhr, textStatus, thrownError){
            if(xhr.status == 404){
                view_data=0;
            }else{
                 view_data=0;
            }
        }
    });

    return view_data;
}

function startLoading(productId) {

    var imgEstoqueProduto = document.getElementById("imgEstoqueProduto" + productId);
    if (imgEstoqueProduto) {
        imgEstoqueProduto.style.display = "";
    }
}

function stopLoading(productId) {
    var imgEstoqueProduto = document.getElementById("imgEstoqueProduto" + productId);
    if (imgEstoqueProduto) {
        imgEstoqueProduto.style.display = "none";
    }
}

HTML:

">1

<img id="imgEstoqueProduto"
                                style="vertical-align: middle; display: none;"
                                src="<c:url value="/images/ajaxLoader.gif"/>">

I tried to use the beforeSend, call before the ajax method starts, ajaxStart and even then it doesn't work and the screen just hangs. Could you help me please?
I called startLoading before everything and it still doesn't work
I removed async: false but, I need to wait for the data to be returned from the API


text:
Q: Struts2 + Bootstrap datatable: how to paginate without load all data I'm working in some app that uses Struts2 framework and in the action i load all the data that we need in some List<Object> and then in the JSP file this list is iterated and displayed in a datatable using bootstrap framework.
This works fine, but i would know how to do this without load the full data in the resulting HTML, like if i have 1.000.000 (one million) of records.
I don't want that all the records are in the resulting HTML output from the JSP, only the 10 first, and with the pagination load (with jQuery?) the rest of the dataset if is needed.

A: The best way is to create a method in your DAO that have as additional parameters start & end for example :
getCustomers( int start,int end){
// get all customers
// sublist the result and get the data from start index to end index
}

in your controller you'll do almost the same and you will give start and end parameters through POST or GET request
@RequestMapping(value = "/sublistedCustomers", method = RequestMethod.GET)
public String getSublistedCustomers(@RequestParam("start") final int start,@RequestParam("end") final int end){
 model.addAttribute("cutomersResult",yourDAO.getCustomers(start,end));
}

now you have a part of customers record on your JSP file and it s up to you to decide how to display this sublisted result.

A: To add to the Enrique San Martín's comment: http://legacy.datatables.net/usage/server-side
Any good example should use iDisplayStart and iDisplayLength parameters, and of course "bServerSide": true property of datatable().
Here the link to the blog-post: Using jQuery Datatable with Struts2 action class using Ajax.

A: Well, this is some good aproach, but i have to convert the request.getParameter to struts variable (declared as privated and then generate getters y setters):
FROM: https://datatables.net/development/server-side/jsp
edit: This link have some request.gP with old values from the datatables, instead we have to use the params from:
https://datatables.net/manual/server-side#Sent-parameters
Like in an action:
private String draw;

private String length;

private String order;

private String search;

private String start;

getters&setters{} //or make it public

Then in the actionMethod that is called by the ajax make the query to the db and return the dataset.
I will edit this answer when i have the full pagination working with struts2+datatables,
In the datatable there is some configurations that are necesary (see the docs from datatables.net):
<script>
$(document).ready( function() {
    $('#datatable').dataTable( {
      "iDisplayLength": 5,
      "processing": true,
      "serverSide": true,
      "ajax": "paginateTableAction"
    } );
  } );
</script>


text:
Q: How to create an Airflow task where I start a Docker container with GPU support How could I create an Airflow task where I would start a Docker container that is using GPU. When running from the terminal I would just use --gpus all flag. I can`t do that using DockerOperator, because it does not support device_requests parameter, which is used underneath when calling docker run with --gpus all flag.

A: Okay, for anyone in the future - I figured it out. First, you need to mount the docker daemon socket inside an airflow docker container. Do this by changing docker-compose file by adding in the volumes section of airflow:
- /var/run/docker.sock:/var/run/docker.sock

Then you need to create a new docker image based on airflow docker image and install docker python SDK, eg.:
# syntax=docker/dockerfile:1
FROM apache/airflow:2.2.0-python3.7

RUN pip install docker

then you can create tasks based on PythonOperator, where you use the docker library to create new containers. Example task (output is not pretty)
def start_gpu_container(**kwargs):
     client = docker.from_env()
     response = client.containers.run(
         'tensorflow/tensorflow:latest-gpu',
         'nvidia-smi',
         device_requests=[
             docker.types.DeviceRequest(count=-1, capabilities=[['gpu']])
         ]
     )

     return str(response)


text:
Q: Suppress system() output First off, I do mostly C#, .Net development so go easy on me if this is a stupid question.
I am implementing an Ericcson open source project to convert an image to another format. The problem is that on conversion an output to a console happens as follows...
1 file(s) copied.

I need to suppress this dialog that pops up. I just want to execute the system command with no output. I think I have isolated the area of the code causing this.
void writeOutputFile(char *dstfile, uint8* img, uint8* alphaimg, int width, int height)

{
    char str[300];
if(format!=ETC2PACKAGE_R_NO_MIPMAPS&&format!=ETC2PACKAGE_RG_NO_MIPMAPS)
{
    fWritePPM("tmp.ppm",width,height,img,8,false);
    //PRINTF("Saved file tmp.ppm \n\n");
}
else if(format==ETC2PACKAGE_RG_NO_MIPMAPS)
{
    fWritePPM("tmp.ppm",width,height,img,16,false);
}
if(format==ETC2PACKAGE_RGBA_NO_MIPMAPS||format==ETC2PACKAGE_RGBA1_NO_MIPMAPS||format==ETC2PACKAGE_sRGBA_NO_MIPMAPS||format==ETC2PACKAGE_sRGBA1_NO_MIPMAPS)
    fWritePGM("alphaout.pgm",width,height,alphaimg,false,8);
if(format==ETC2PACKAGE_R_NO_MIPMAPS)
    fWritePGM("alphaout.pgm",width,height,alphaimg,false,16);

// Delete destination file if it exists
if(fileExist(dstfile))
{
    sprintf(str, "del %s\n",dstfile);
    system(str);
}

int q = find_pos_of_extension(dstfile);
if(!strcmp(&dstfile[q],".ppm")&&format!=ETC2PACKAGE_R_NO_MIPMAPS)
{
    // Already a .ppm file. Just rename.
    sprintf(str,"move tmp.ppm %s\n",dstfile);
    //PRINTF("Renaming destination file to %s\n",dstfile);
}
else
{
    // Converting from .ppm to other file format
    //
    // Use your favorite command line image converter program,
    // for instance Image Magick. Just make sure the syntax can
    // be written as below:
    //
    // C:\imconv source.ppm dest.jpg
    //
    if(format==ETC2PACKAGE_RGBA_NO_MIPMAPS||format==ETC2PACKAGE_RGBA1_NO_MIPMAPS||format==ETC2PACKAGE_sRGBA_NO_MIPMAPS||format==ETC2PACKAGE_sRGBA1_NO_MIPMAPS)
    {
        // Somewhere after version 6.7.1-2 of ImageMagick the following command gives the wrong result due to a bug.
        // sprintf(str,"composite -compose CopyOpacity alphaout.pgm tmp.ppm %s\n",dstfile);
        // Instead we read the file and write a tga.

        //PRINTF("Converting destination file from .ppm/.pgm to %s with alpha\n",dstfile);
        int rw, rh;
        unsigned char *pixelsRGB;
        unsigned char *pixelsA;
        fReadPPM("tmp.ppm", rw, rh, pixelsRGB, 8);
        fReadPGM("alphaout.pgm", rw, rh, pixelsA, 8);
        fWriteTGAfromRGBandA(dstfile, rw, rh, pixelsRGB, pixelsA, true);
        free(pixelsRGB);
        free(pixelsA);
        sprintf(str,""); // Nothing to execute.
    }
    else if(format==ETC2PACKAGE_R_NO_MIPMAPS)
    {
        sprintf(str,"imconv alphaout.pgm %s\n",dstfile);
        //PRINTF("Converting destination file from .pgm to %s\n",dstfile);
    }
    else
    {
        sprintf(str,"imconv tmp.ppm %s\n",dstfile);
        //PRINTF("Converting destination file from .ppm to %s\n",dstfile);
    }
}
// Execute system call
system(str);

free(img);
if(alphaimg!=NULL)
    free(alphaimg);

}
I am lost at this point about how to suppress the console that pops up. As we iterate through images via a reference to the dll, many many console windows flash on the screen. Need to stop this from happening.
Help is greatly appreciated.

A: To fully suppress the output, redirect both stdout and stderr:
system("command >nul 2>nul");

A: Try doing:
strcat( str, " > nul" )         // for Windows or
//strcat( str, " > /dev/null" ) // for Unix

system( str )

If it doesn't help then this may help:
#include <string>
#include <ShellAPI.h>

int system_no_output( std::string command )
{
    command.insert( 0, "/C " );

    SHELLEXECUTEINFOA ShExecInfo = {0};
    ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
    ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
    ShExecInfo.hwnd = NULL;
    ShExecInfo.lpVerb = NULL;
    ShExecInfo.lpFile = "cmd.exe";
    ShExecInfo.lpParameters = command.c_str();
    ShExecInfo.lpDirectory = NULL;
    ShExecInfo.nShow = SW_HIDE;
    ShExecInfo.hInstApp = NULL;

    if( ShellExecuteExA( &ShExecInfo ) == FALSE )
        return -1;

    WaitForSingleObject( ShExecInfo.hProcess, INFINITE );

    DWORD rv;
    GetExitCodeProcess( ShExecInfo.hProcess, &rv );
    CloseHandle( ShExecInfo.hProcess );

    return rv;
}

and replace all your system() calls to system_no_output() ones.

A: Take a look here if you're using C#.  The class used in C# is ProcessStartInfo.
In the example in the link, look at the OpenWithStartInfo member function which will minimize the console.
As far as doing this in C++, take a look at the spawn family of functions here.


text:
Q: How to deal with this error AVAudioSessionErrorCodeMissingEntitlement? I'm trying to integrate with iOS10's CallKit, however when I'm trying to initialize the audio session after accept a phone call, this "AudioUnitInitialize" API will throw out this error "AVAudioSessionErrorCodeMissingEntitlement".
According to the document, it's just one line explanation:
https://developer.apple.com/reference/avfoundation/avaudiosessionerrorcode/avaudiosessionerrorcodemissingentitlement
How should I update the entitlement for support this? Does any body has any experience?

A: I also ran into this issue in iOS10 Beta 6, and was able to resolve it by moving the "AudioUnitInitialize" API from the performAnswerCallAction: method (as implemented in SpeakerBox) to the init routine of the ProviderDelegate.
By moving initialization earlier in the lifecycle of the ProviderDelegate, somehow the 'entitlement' problem is avoided.

A: I've downloaded Apple's Speakerbox sample app to examine the entitlements and background modes used for CallKit.
It looks like they add the Background Modes -> voice over IP entitlement and the "App provides Voice over IP services" key to the app's Info.plist:
<key>UIBackgroundModes</key>
<array>
    <string>voip</string>
</array>

It also adds the INStartAudioCallIntent key to NSUserActivityTypes and the following Microphone Usage Description:
<key>NSMicrophoneUsageDescription</key>
<string>$(PRODUCT_NAME) uses the Microphone for call audio</string>
<key>NSCallKitUsageDescription</key>
<string>$(PRODUCT_NAME) makes and receives calls</string>
<key>NSUserActivityTypes</key>
<array>
    <string>INStartAudioCallIntent</string>
</array>


text:
Q: c++ sizeof() not returning correct size I'm trying to get the size of a string in my program, so then I can convert it into a char later using a loop, but the size that the program is returning is 5 numbers lesser than the actual size. Why would this be happening?
std::string theFileName = fileNames[ curTab ];
int size = sizeof( theFileName );

When debugging my program, it stores this in theFileName:
theFileName = "C:\Users\Vincent\Desktop\Untitled.txt"
And this in size:
size = 32
If you count the characters in theFileName, its actually 37. What is causing this to happen? I'm using MS Visual C++ 2010 Express, creating a notepad program.

A: sizeof tells you the size of the data structure and all its member data. However, a string object will typically store the string data on the heap -- i.e. it's not member data, but the object owns it and stores a pointer to it.
The correct way to get the size of your string object is to call the size() or length() member function.

A: std::string is not an array of chars. Is a dynamic array managed by the std::string object. sizeof returns the size of the specified data type, in the case of string, the pointer to the array plus an amount of statically allocated chars (Thats a common string optimization).
What you should use is the builtin function size(), which returns the length of the string.

A: The size of the content is determined with
theFileName.size()

while sizeof returns the size of the object std::string. The object could, for example, contain a pointer to the location of the content and an unsigned integer to represent the length. sizeof would therefore contain the size of one pointer and the unsigned integer. This would not vary if you change the content.

A: The size of a std::string object is unrelated to the size of the string it contains. Use the std::string member function provided for this purpose.

A: sizeof is used to calculate the size of any datatype measured in bytes.
The function you have to use in your program is size.


text:
Q: "They slipped from my hands the moment I picked them [up]"
They were like puzzle pieces that slipped from my hands the moment I picked them [up].

Is the up necessary? Why or why not?

A: 'up' describes completeness. When you use 'up' it shows you are selecting something and lifting it up whereas when you use 'pick' alone it shows you are just selecting which seems sort of incomplete.

A: 'to pick', and 'to pick up' are two different verbs. 'to pick up' is what's called a phrasal verb, formed by modifying the simple verb 'to pick'.
But they have different meanings! 'pick up' is to take something and raise it, or to collect someone in your car. 'I picked up the litter'. 'I picked her up from the station.'
'pick' is to choose. 'I picked my favourite'.
So without the 'up', your sentence means 'They slipped from my hands the moment I selected them'.
Presumably once upon a time, the meanings were much closer, and 'pick up' really was 'pick' with an extra adverb. But not in modern English.

A: Actually to pick something and to pick something up have two distinct meanings:

*

*To pick something coneys the idea of selecting something out of a group of things.

*To pick something up  refers to the action of taking something up from somewhere (the floor, the table etc.)

In your sentences you are specifically referring to 'pieces that slipped from my hands' so pick up is the correct verb to use.

A: I can't make this a "comment" due to lack of rep.
@John Lawrence Aspden
In a phrasal verb like "pick up", the particle "up" is not "an extra preposition".   It happens that the word "up" can be used as a preposition, but it can also be an adverb:
"Look up!  Look down!  Look left!  Look right!"  The word "up" in this case is an adverb modifying the verb "look".  (Note that this does not mean at all the same thing as the transitive phrasal verb "look up" as in "Look that up in your Funk & Wagnalls".)
However "Look up the street at the woman in the red dress." is using "up" as a preposition.
This happens to be a bit of a peeve of mine due to people using it as some sort of "proof" that the rule against ending a sentence with a preposition is wrong (citing Winston Churchill as some sort of authority).  When you use "up" as a particle in a phrasal verb, it isn't being used as a preposition at all, so it does not in any way invalidate the idea that a preposition ought to be pre-positioned before its object.


text:
Q: fastest way to remove whitespace from a rendered PHP file I tried a performance check tool "DOM Monster" to analyze my php site. There is one information which says "50% of nodes are whitespace-only text nodes".
Ok I unterstand the problem but what is the fastest way to cleanup whitespace in php?
I think a good start is to use the "Output Control" like ob_start() and then replace the whitespace before releasing it with ob_end_flush(). In the moment I do everything with echo echo ... I never read much about this ob_* things is it useful?
I guess using preg_replace() is a performance killer for this job or?
So what is the best practice for this?

A: The fastest way to remove whitespace-only nodes is to not create them in the first place. Just remove all the whitespace immediately before and after each HTML tag.
You certainly could remove the spaces from your code after the fact using an output handler (look at the callback bit in ob_start), but if your goal is performance, then that kind of defeats the purpose.
A whitespace-only node is in the DOM tree parsed by the browser when it reads your HTML. It's where there's an HTML tag, then nothing but whitespace, then another HTML tag. It's a waste of browser resources, but not a huge deal.

A: The function trim() will solve your problem, isn't it?
http://www.php.net/manual/en/function.trim.php

A: Well, I guess you talk about HTML, and HTML is as is a meta language full of whitespace (attributes, texts).
By the way, you probably use newlines for readability.
I rather advise you to compress your page with deflate/gzip and webserver rules, ie an .htaccess rule:
<FilesMatch "\\.(js|css|html|htm|php|xml)$">
SetOutputFilter DEFLATE
</FilesMatch>

You can also take a look at Tidy which is a library to help you to check and cleanup your HTML code.

A: preg_replace will of course slow things down a little. But probably it's the fastest way anyway. The problem is more that preg_replace may be unreliable because it is very hard to write regular expression that works on all possible cases.
If you are createing XML/XHTML output, you could parse all your data using a fast stream parser SAX or StAX, php has both builtin usually, and then write the data back to the output without the whitespaces. That's simple, effective, reliable und at least medium fast. It's still not going to blow you off with speed.
Another option would be to just use gzip. (ob_handler('gz_handler') is the call in php if I remember correctly). This will compress your data and compression works extremely well on problems with data that repeats a lot within a document. That come with a litte performance penalty as well, but the reduced size of the output document may make up for it.
Though beware that the output will not be send to the browser before all output is available. This makes partial loading of webpages much harder ;-).

A: The problem with using ob_* and then trimming whitespace is that you'll have to make sure to not remove displayed whitespace like in <pre> tags or <textarea>s etc. You'll need a syntactical parser which understands where it should not trim.
With an (performance-)expensive parser you should also cache output where possible.

A: The following is code to remove all space characters but the first of a sequence of spaces. So 1 space will be kept, 3 spaces pruned to 1, etc.
at the top of you php file do
ob_start();

At the end do
function StripExtraSpace($s)
{
  $newstr = "";
  for($i = 0; $i < strlen($s); $i++)
  {
    $newstr = $newstr . substr($s, $i, 1);
    if(substr($s, $i, 1) == ' ')
      while(substr($s, $i + 1, 1) == ' ')
        $i++;
  }

  return $newstr;
}

$content = ob_get_clean();
echo StripExtraSpace($content);


text:
Q: Python logging to file The following code prints both to the console and to the specified log-file - why? How can I tell logger to only use the filehandler? I tried to disable printing to console by commenting out line 8 (logger.setLevel(logging.INFO)), but the result of that was that the log file was created but empty. (I'm using logger in main() and in the class defined in the file)
if __name__ == "__main__":
    HOME_DIR = '/mydir'
    LOG_FILENAME = HOME_DIR + '/my.log'

    logging.info('Starting...')

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

    fh = logging.FileHandler(LOG_FILENAME)
    fh = logging.handlers.RotatingFileHandler(LOG_FILENAME,
                   maxBytes=10000,
                   backupCount=1,)
    fh.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    logger.addHandler(fh)

    main()


text:
Q: Animate entry of (only new) elements in a virtualized list I am using react-window FixedSizedList and react-virtualized-auto-sizer Autosizer components to build a list/table UI element that may contain thousands of items that also receives new items via a websocket connection and prepends them to the list. I now have a requirement to animate the entry of new elements in this list.
Here is a codesandbox link with a minimal (and not quite working) example: codesandbox.
Note how the .row animation is triggered for every child of FixedSizedList each time the data list receives a new item. Also note how the .row animation is again triggered for every child of FixedSizedList when the list is scrolled.
I understand that the reason this is happening is because of how list virtualization works using absolute positioning of the children rows. Every time a new item is inserted into data, or the list is scrolled, react-window needs to re-compute the style prop for each row, which recreates every DOM element and hence re-triggers the .row animation.
I would like to animate only the new .row DOM elements when they appear.
Things I have tried:

*

*Add animation-iteration-count: 1; to the .row class. This doesn't work for the same reason mentioned above as every element is re-created on a new item insert.

*Animate only the first row (example using red background in the code sandbox). While this "works", it's not quite suitable. In my production site, updates are not guaranteed to come through one at a time - multiple rows might be inserted at the same time. All new rows should be animated when they are added to the DOM. This can be replicated in the code sandbox by inserting two UUID's at once in the hook.

*Not use list virtualization. This of course works fine, but is not suitable. In my production site this list could contain thousands of items.

*Reading this previous question. The previous question is sparse of information, does not have a minimal example, and has no useful answers or comments. Additionally, it is over 5 years old.

How is it possible to achieve the result I'm looking for here?
EDIT:
A further attempt I have tried, extending on 2) above:

*

*Save a copy of the "old" list of items each render. When an update is received, subtract the length of the old list from the length of the new list (call this number n). Animate the top n items of the new list. This "works", but the production system has some intricacies making this solution insufficient - each list item is dated with an ISO timestamp, and the list is sorted according to timestamp new -> old. Updates received via websocket also have a timestamp, but there is no guarantee the new item will always be newer than the current top of the list - in some cases, new items are inserted into position 2, 3 or further down in the list. In this case, animating the top n items based on the length change would not be accurate.

A: Don´t know how costly it can be for you, but one way to do that is on every state change add a specific className to the new insert rows and a className to the already inserted rows.
So that way you can handle using the className related to the new inserted lines.
Something like this:
const mappedObject = (data, className) => {
  return {
    item: data,
    className
  };
};

React.useEffect(() => {
    const interval = setInterval(() => {
      const alreadyInsertedData = data.map((item) => {
        item.className = "already-inserted";

        return item;
      });

      setData((prev) => [
        mappedObject(uuidv4(), "first-insert"),
        mappedObject(uuidv4(), "first-insert"),
        mappedObject(uuidv4(), "first-insert"),
        ...alreadyInsertedData
      ]);
    }, 3000);

    return () => {
      clearTimeout(interval);
    };
  }, [setData, data]);

Here's a code sample to you check.


text:
Q: Trying to get a whole table row to highlight on mouseover I have a gradient row in a table, and I would like to change the gradient of the entire row when the mouse is over any cell in that row. As far as I've been able to read, the CSS I'm using now should work, but nothing happens upon mouseover (but the original gradient looks perfect). Here is the CSS:
td {
  font-family: 'Roboto Slab', serif;
  font-size: 18px;
  padding: 3px 15px;
  text-align: center;
}

.silvergrad {
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFF', endColorstr='#CCC');
  background: -webkit-gradient(linear, left top, left bottom, from(#FFF), to(#CCC));
  background: -moz-linear-gradient(top, #FFF, #CCC);
}

.silvergrad tr:hover td {
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#999', endColorstr='#CCC');
  background: -webkit-gradient(linear, left top, left bottom, from(#999), to(#CCC));
  background: -moz-linear-gradient(top, #999, #CCC);
}

I have tried it with and without the td after the .silvergrad tr:hover.
Here is the HTML for the row:

  Some stuff
  Some stuff
  Some stuff

Can anyone see what I'm doing wrong? Thanks in advance.

A: Change your one CSS rule from:
.silvergrad tr:hover td {

to
.silvergrad:hover td {

jsFiddle example
There is no tr element that's a descendant of .silvergrad. silvergrad is the tr.

A: You are specifying the table row as a descendant of the element with the silvergrad class, whereas it is the element with the silvergrad class. Try using this:
tr.silvergrad:hover td {
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#999', endColorstr='#CCC');
  background: -webkit-gradient(linear, left top, left bottom, from(#999), to(#CCC));
  background: -moz-linear-gradient(top, #999, #CCC);
}

A: Your CSS is looking for a tr that is inside an element with the .silvergrad class, not for one that has it. Try this:
tr.silvergrad:hover>td

A: Maybe its changing but you cant see.
please try this for gradient code.
.silvergrad tr:hover>td{

 background-color: #999;
 background-image: -moz-linear-gradient(top, #999, #ccc);
 background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#999), to(#ccc));
 background-image: -webkit-linear-gradient(top, #999, #ccc);
 background-image: -o-linear-gradient(top, #999, #ccc);
 background-image: linear-gradient(to bottom, #999, #ccc);
 background-repeat: repeat-x;
 filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff999',endColorstr='#ffccc', GradientType=0);
}

please reply after testing :)

A: Now it works, although I could SWEAR this is one of the many variations I tried. All I did was to change:
.silvergrad tr:hover td {

to simply
.silvergrad:hover {

and now it works beautifully. Thanks to all of you who responded so quickly.


text:
Q: NSMutableDictionary instance variable not retaining key values outside of loop sorry if this question has already come up but I couldn't find anything that addressed the specific problem I'm having here.
I'm working in objective-c on iOS and I have declared an NSMutableDictionary instance variable, a property for it, synthesized it, and allocated space for it in my init method:
SettingsViewController.h
@interface SettingsViewController : UITableViewController <UIAlertViewDelegate> {
    NSMutableDictionary *settingsData;
    UISwitch *emailSwitch;
    UISwitch *phoneSwitch;
    NSMutableData *receivedData;
}

@property (nonatomic, retain) NSMutableDictionary *settingsData;
@property (nonatomic, retain) UISwitch *emailSwitch;
@property (nonatomic, retain) UISwitch *phoneSwitch;
@property (nonatomic, retain) NSMutableData *receivedData;

SettingsViewController.m init method
@synthesize settingsData, emailSwitch, phoneSwitch, receivedData;

# the initialization method, where settingsData is allocated
- (id)initWithStyle:(UITableViewStyle)style {
    self = [super initWithStyle:style];
    if (self) {
        self.navigationItem.title = @"Settings";
        [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]     initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneEditing:)] autorelease]];
        settingsData = [[NSMutableDictionary alloc] init];
    }
    return self;
}

The potion of the method in SettingsViewController.m that uses settingsData (it's just a very simple parser for a block of data formatted key=value&):
NSMutableString *element = [NSMutableString string];
NSMutableString *value = [NSMutableString string];
bool cap_element = true;
char index;
for (int i = 0; i < [response length]; i++) {
    index = [response characterAtIndex:i];
    if (cap_element && index != '=') {
        [element appendFormat:@"%c", index];
        continue; // skip back to the top
    }
    if (index == '=') {
        cap_element = false;
        continue;
    }
    if (!cap_element && index != '&') {
        [value appendFormat:@"%c", index];
        continue;
    }
    if (index == '&') {
        // store the value in the dict and move onto the next element
        # this output is always correct...
        NSLog(@"Key:%@, Value:%@", element, value);
        [self.settingsData setObject:value forKey:element];
        # ...as is this (the value printed above matches the result here)
        NSLog(@"Result:%@", [settingsData objectForKey:element]);
        [value setString:@""];
        [element setString:@""];
        cap_element = true;
    }
    # but this will output an empty string (username prints correctly above)
    NSLog(@"%@", [self.settingsData objectForKey@"username"]);

The first 2 NSLog() comments output as expected, but as soon as I leave the for loop all of the keys remain and their values become empty strings (so output reads username = "" instead of username = "tester"). I would understand this if the dictionary was not initialized, but I take care of that in the init method shown above. What am I missing?

A: In the dictionary you are storing a reference to the "value" and "element" variables, not a copy. When you set them to empty string:
[value setString:@""];
[element setString:@""];

you also are updating the values in the dictionary as well.
EDIT: To solve, change this line:
[self.settingsData setObject:value forKey:element];

to this to create new strings (stringWithString should give you autoreleased values):
[self.settingsData setObject: [NSString stringWithString: value] forKey: [NSString stringWithString: element]];

A: The problem lies here:
[value setString:@""];
[element setString:@""];

You're setting element/value to empty strings after you've given the dictionary references to both. The dictionary is holding onto those references, not their values. Because of this, when you change the element/value values, you're unexpectedly (at least in this case) changing the behavior of your dictionary in that it no longer will respond to the key you've set and it will not return the value that was initially defined.
If you don't want this to happen, then you need to copy the strings before you reset them.

A: You are setting the values of the two string to "" here:
[value setString:@""];
[element setString:@""];

The NSMutableDictionary only has references to the original objects so changes you make are reflected where ever there is a reference to that object. It is common to copy mutable objects if you want to ensure that there values are not changed underneath you.


text:
Q: Formulas related to "Cooling a cup of coffee with help of a spoon" I was recently going through some of the top voted questions on the thermodynamics tab. And, I came across Cooling a cup of coffee with help of a spoon. I found this question really interesting. In fact, I plan on carrying out my own experiment related to it.
However, to write my experiments and results in a formal research paper for my school, I must have an investigation involving a few independent and  one dependent variables. Therefore, I cannot work with comparing methods of cooling coffee, as they are not quantifiable.
My dependent variable would be time, since I want to find the fastest method of cooling coffee.

What are the dependent variables I can use?

It would be great if you guys could provide some relevant thermodynamics formula related to cooling rate which can be applied to this scenario of cooling a cup. I have thought about optimal stirring speed or area of stirrer, but I am yet to find a mathematical relationship between them and the time taken for cooling.
Note: Although this question is tagged as homework. It is not. It is just a request for help in an experiment I may carry out in school.
Note: I am not only restricting methods of cooling to methods using spoons. The method used for cooling a cup of coffee does not need to include a spoon.

A:
It would be great if you guys could provide some relevant
  thermodynamics formula related to cooling rate which can be applied to
  this scenario of cooling a cup.

The 'go to' Law for this kind of cooling is Newton's Cooling Law:
$$\boxed{\frac{\text{d}Q}{\text{d}t}=-hA\Delta T}$$
where:

*

*$\frac{\text{d}Q}{\text{d}t}$ is the heat energy loss per unit of time (aka the heat flux) of the cup. Obviously the higher the heat flux, the faster the cup will cool down (faster temperature loss).

*$\Delta T$ is the temperature difference between the 'hot' object (the cup) and the 'cold' object (the surrounding air).

*$A$: the surface area shared between the 'hot' object (the cup) and the 'cold' object (the surrounding air). The heat flows from hot to cold through that surface.

*$h$ the heat transfer coefficient.

Having understood that in order to maximize cooling we need to maximize the product of the three factors on the RHS of the equation we can now suggest some factors to investigate.

*

*$\Delta T$ can be maximized by minimizing the temperature of the air. Experiment by cooling the cup in the refrigerator v. normal ambient air.

*It's is well know that the heat transfer coefficient $h$ can be increased by introducing turbulence, both inside the cup and outside of it. Experiment with controlled stirring, perhaps at different speeds. Experiment with air fans blowing on the cup.

*Greater surface area promotes heat flux and thus cooling rate.  Note that a sphere has the lowest surface area to volume ratio of all regular shapes. Elongated cylindrical shapes will have higher surface area to volume ratios. Consider experimenting with cooling fins to boost $A$.

With these suggestions carry out some screening experiments to identify the most important factors affecting cooling rate. Finally, by combining those, the fastest cooling rate scenario can be determined.
This kind of investigation is very well suited for the application of Factorial Experimental Designs (FED).
In this approach factors suspected to influence one or more measuring responses ('cooling rate' in our case) are identified. To each factor is assigned two values (symbolically represented by $-$ and $+$).
We've identified 4 factors and can assign two values to each of them. This allows the running of a so-called $2^{4-1}$ FED, which requires a mere $8$ experiment runs.
The FED matrix looks like this ($A$, $B$, $C$ etc represent the factors):

Once the $8$ runs have been performed, the effects of each factor, as well as first order interactions (e.g. $AC$), are easily calculated.
The advantage of this kind of experiment design is that it yields a high degree of information compared to one-variable-at-a-time designs.


text:
Q: innerHTML value in input type Form

function addRow() {

    var SpielerNR = document.getElementById("spielernr");
    var SpielerName = document.getElementById("speilername");
  var groesse = document.getElementById("groesse");
    var table = document.getElementById("myTableData");

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);

    row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
    row.insertCell(1).innerHTML= SpielerNR.value
    row.insertCell(2).innerHTML= SpielerName.value
 row.insertCell(3).innerHTML=  groesse.value

}

function deleteRow(obj) {

    var index = obj.parentNode.parentNode.rowIndex;
    var table = document.getElementById("myTableData");
    table.deleteRow(index);

}

function addTable() {

    var myTableDiv = document.getElementById("myDynamicTable");

    var table = document.createElement('TABLE');
    table.border='1';

    var tableBody = document.createElement('TBODY');
    table.appendChild(tableBody);

    for (var i=0; i<3; i++){
       var tr = document.createElement('TR');
       tableBody.appendChild(tr);

       for (var j=0; j<4; j++){
           var td = document.createElement('TD');
           td.width='75';
           td.appendChild(document.createTextNode("Cell " + i + "," + j));
           tr.appendChild(td);
       }
    }
    myTableDiv.appendChild(table);

}

function load() {

    console.log("Page load finished");

}
<!DOCTYPE html>

    <title>HTML dynamic table using JavaScript</title>

        NR:
        <input type="text" id="spielernr">

        Name:
        <input type="text" id="speilername">

        Select:

  <select id="groesse" name="groesse" style="width: 150px">
  <option> </option>
  <option value="XXS">XXS  </option>
  <option value="XS">XS </option>
  <option value="S">S  </option>
  <option value="M">M  </option>
  <option value=" L">L </option>
  <option value="XL">XL </option></select>
  </select>
        <input type="button" id="add" value="Add" onclick="Javascript:addRow()">

Current data in the system ...

        NR
        Name:
        Grösse

My Prob is, when i add NR NAME AND GROESSE.. i will get a plan TEXT.
what i need is a INPUT form like
 with the added info.
Means:
after i added all infos like Nr NAME and GROESE, i want to show input form instead of plan text.
Any idea, how to do that?

A: You are already using the CreateElement() function in your code a number of times.  Why not use that to create your input element?  All of these things can be done in Javascript.  Maybe use jQuery or some other tool to help simplify some of your DOM manipulation efforts.
Here's another example from a different StackOverflow question:
How insert an input field in a table cell?


text:
Q: timeout during the post-login phase connecting to SQL Server 2012 I am trying to connect from desktop to SQL Server 2012 (on a different server) and getting the following error:

Connection Timeout Expired. The timeout period elapsed during the post-login phase. The connection could have timed out while waiting for server to complete the login process and respond; Or it could have timed out while attempting to create multiple active connections. The duration spent while attempting to connect to this server was - [Pre-Login] initialization=190; handshake=4; [Login] initialization=0; authentication=102; [Post-Login] complete=14002; (Microsoft SQL Server)

The client is SQL Server Management Studio 2012. Firewall on the server is turned off. I can telnet to port 1433. And connecting from Studio on the server itself works fine. Desktop and Server are on the same segment; using Windows authentication.
Both Windows Server 2008R2 and SQL Server are just built from scratch.
What puzzles me is that post-login phase. I have a feeling that I am looking in the wrong place (that is, network connectivity); but don't know what the right place would be...

A: Adapted from my comment that found your answer:
Check the event log. You will probably see something in there that points to the problem.


text:
Q: How to add field to notification laravel I am using laravel and use notification system
so I add a column "URL" to notifications table and want to store it in database but it does not work and really I do not know how can I add field and store in database
here is my notification class and notify when new comment submitted :
<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

class NewComment extends Notification
{
    use Queueable;
    private $details;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
     public function __construct($details)
     {
       $this->details = $details;

     }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
      return ['database'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
      //
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
      return [
       'message' => $this->details['message'],
       'product' => $this->details['product'],
       'url' => 'test'
   ];

    }
}

here is controller
  $details = [
          'message' => 'یک نظر جدید برای محصول',
          'product' => $product->title
      ];
    $user->notify(new NewComment($details));

it gives me this error :

General error: 1364 Field 'url' doesn't have a default value

A: The result returned from toArray (or toDatabase) method is stored as JSON in an existing column called data; So you don't need to (and better not to) add a new column to your existing table.
Just remove that column and it should work. later you can read that url from decoding the JSON from data column.
$data = json_decode(DB::table('notifications')->first()->data);
$url = $data->url;


text:
Q: CakePHP: How to require admin role for a specific page? We are using the Auth component. We are currently able to prevent non-logged in users from visiting our "admin" page (adminhome.ctp). But we can't figure out how to make isAuthorized() prevent non-admins from visiting the page also.
Inside the AppController:
public function beforeFilter() {
    $this->Auth->allow('index', 'view', 'login', 'logout', 'display');
    $this->Auth->authorize = array('Controller');
    //$this->Auth->autoRedirect = false;
}

public function isAuthorized($user_id) {
    $this->loadModel('User');
    $user = $this->User->findById($this->Auth->user());
    if ( $user['User']['role'] === 'admin') {
        $this->Session->setFlash('isAuthorized');
        return true;
    }
    $this->Session->setFlash('!isAuthorized');
    return false;
}

Here the beforeFilter() in PagesController:
function beforeFilter() {
    $this->Auth->deny('adminhome');
}

What are we doing wrong?

A: I have just used Aryan answer however I have made some minor changes which could be helpful for others:
if($this->Session->read('Auth.User.role') != 'admin')
    {
        $this->Session->setFlash('You are not authorized to visit this page');
        $this->redirect('/');
    }

A: I believe that your way it doesn't work because you should use Auth->deny() to restrict access to methods, and adminhome is not a method in the PagesController. Try this:
# in app/controller/PagesController.php
public function display() {
  $page = empty($this->request->params['pass'][0]) ? null : $this->request->params['pass'][0];
  if($page == 'adminhome' || $this->User->isAuthorized()) {
    $this->render($page);
  } else {
    # redirect the user somewhere else
  }
}

I hope this  helps

A: You'll have role field in user table. In particular action add this line
if($this->Session->read('Auht.User.role') != 'admin') {
      ...............................
}

If you want only admin can see every actions in some controller like admincontroller
you can add this code in that controller in beforeRender action
if($this->Session->read('Auth.User.role') != 'admin')
            {
                $this->Session->setFlash(You are not authorized to visit this page,'flash',array('alert'=>'info'));
                $this->redirect('/');
            }


text:
Q: Where can I find Cultist Blood? I recently found the plans for a Blood-magic edge that requires Cultist blood.
Where can I find that legendary crafting material?

A: You can farm this off of the Cultist Grand Inquisitor in the Halls of Agony Level 1. He spawns every time you launch a game.
Source


text:
Q: How do I make my HTML5 video player autoplay on iPad, like filmon.com? I'm trying to create an HTML5 video player to automatically start streaming video. I searched a lot but I didn't achieve my goal.
Then I found www.filmon.com, where all videos start to play automatically on iPad.
Does anyone know how they did it? I looked at their JS files, but I cannot make mine start automatically.

A: Apple has specifically disabled every method and workaround to autoplay video on iPads and iPhones (the "autoplay" attribute, and Javascript solutions like triggering hidden link's "onclick" event).
I have yet to find a way to autoplay on iPads and it looks like Apple is continuing to squash all efforts to do it.  They state, "In Safari on iPhone OS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, autobuffering and autoplay are disabled. No data is loaded until the user initiates it."
As a quick update I just checked out Filmon.com and the videos there no longer seem to be autoplaying on an iPad.  Example:  http://demand.filmon.com/distant-roads-173-cnd-ontario-ca-1 autoplays on Chrome, but not on the iPad.

A: I don't think that iphone or ipad play streams automatically due to high traffic.
Why don't you play it manually using script at document ready?
somewhat like this:
window.onload=function(){
  var audio = document.getElementById('audio');
  audio.play();
}


text:
Q: how can to convert array from jsp to javascript please i work in project and i want to display many markers on map , i  want to display arr[][] from jsp to javascrpit like this code,
please i work in project and i want to display many markers on map , i  want to display arr[][] from jsp to javascrpit like this code
for ex:
    i want to replace this code :
 for (var i = 0; i < 3; i++) {

         var marker = new google.maps.Marker({
             position: new google.maps.LatLng( 17.088291,78.442383 ),
             map: map,
         });

to :
for (var i = 0; i < 3; i++) {

         var marker = new google.maps.Marker({
             position: new google.maps.LatLng( arr[i][0],arr[i][1] ),
             map: map,
          });

<!DOCTYPE html>

A: I think you have got two options here:
A. Use out.print in the loop, it I think you already tried that but forgot something very important - <% and %>
So the final line of code should look like:
new google.maps.LatLng(<% out.print(arr[i][0]); %>, <% out.print(arr[i][1]); %>

B. Convert the whole JSP array to JSON and decode back. Although not the simplest solution but can be useful in many places like external services etc. You can use a library like Gson.

A: the simple answer
add this line in jsp code
 String json = new Gson().toJson(array);
and in javascript add this line
 var arr=<%=json%>;
code will work


text:
Q: Stuck creating a 0/1 flag that works correctly. Finally giving in Evening all.
I am trying to create a very basic case statement which buckets three scenarios with a 0 or a 1 in mySQL.
I have three fields found in the reference table link below.
Essentially I am trying to bucket any ProductID that has a StatusCD of 'I' and 'O' as 1, only 'I' as 1 and then anything with only an 'O' result and no corresponding 'I' as a 0. What this data is showing is a product coming into the warehouse ('I') and then exiting the warehouse ('O'). I have other fields which are capturing date differences but ultimately I am trying to create a flag to ignore scenarios where we only have Product#'s with an 'O' statusCD which would indicate their arrival to the warehouse was not logged appropriately and would skew our "Age in warehouse" buckets.
Any insight is greatly appreciated!
Reference Table with fields:
Date       | ProductID | StatusCD
2021-01-01 | U1000     | I
2021-01-10 | U1000     | O
2021-01-10 | U2000     | I
2021-01-15 | U3000     | O

A: Assuming you want to retain every original record, you could use analytic functions here:
SELECT Date, ProductID, StatusCD,
       CASE WHEN SUM(StatusCD <> 'O') OVER (PARTITION BY ProductID) = 0
            THEN 0 ELSE 1 END As Label
FROM yourTable
ORDER BY Date;

Demo
For versions of MySQL earlier than 8+:
SELECT t1.Date, t1.ProductID, t1.StatusCD,
       CASE WHEN t2.OpenCount = 0 THEN 0 ELSE 1 END AS Label
FROM yourTable t1
INNER JOIN
(
    SELECT ProductID, SUM(StatusCD <> 'O') AS OpenCount
    FROM yourTable
    GROUP BY ProductID
) t2
    ON t2.ProductID = t1.ProductID
ORDER BY
    t1.Date;

Demo


text:
Q: Defining new datum in ArcGIS with seven parameter translation? Is there a way to define a new datum in ArcGIS with seven parameter translation?

A: Yes it is very much possible to create a new datum in ArcGIS, and then create a 7-p transformation to convert to/from that datum.  Please see example workflow here for a fictional case:
Step 1. In the coordinate system tab select New>Geographic Coordinate System:

Step 2. Enter the details for the new GCS including datum name and spheroid information:

Step 3. Once the new datum and GCS has been created, select the Transformations button and then choose the from and to GCS.  Press New to create the new transformation:

Step 4. Select the transformation type and enter the details:

Step 5. The new datum is ready for use.  If you need it projected then create a new projected CRS and change the GCS to use the new datum:

Also see: ESRI Create Custom Geographic Transformation

A: As commented by @Vince:

No, the Projection Engine is a DLL. Only Esri developers can add a datum.


text:
Q: Enumerate a enum I have a enum:
class Model1 < ActiveRecord::Base
  enum enum1: [:var1, :var2, :var3]
end

How can I enumerate enum1 to get all the values of enum1 which are [var1, var2, var3]?

A: The simplest option is to not do anything with the enum, but rather extract that static array to a constant
class Model1 < ActiveRecord::Base
  ENUM_OPTIONS = [:var1, :var2, :var3]

  enum enum1: ENUM_OPTIONS
end

Then you'll be able to do Model1::ENUM_OPTIONS

A: Alternative to Sergio's answer:
 Model1.defined_enums['enum1'].keys


text:
Q: Is it possible to create and open a new html from a javascript function of a different html? This is the first html file, which on clicking the submit button is supposed to call the js function. But I don't know if it does, because I am not getting the expected output.
<!DOCTYPE html>

<title>Loan</title>

Details to enter

Value1
Value2
Value3

<input name="number1" type="text" size=10 id='num1'/>
<input name="number2" type="text" size=10 id='num2'/>
<input name="number3" type="text" size=10 id='num3'/>

<button onclick="loancalculate()">Submit</button>

This is the "loan.js" file that attempts to create and open a new html file by window.open("filename"). Is it at all possible to do this?
function loancalculate (){
var a=parseFloat(document.getElementById('num1').value);
var r=parseFloat(document.getElementById('num2').value);
var p=parseFloat(document.getElementById('num3').value);
var res;

var principal_portion = [];
var interest_paid = [];
var payment = (r*a)/(1-(1+r)**(-p));
payment = payment.toFixed(2);
var ob = [];
for (i = 1; i < p+1; i++) {
    ppn = payment*(1+p-i).toFixed(2);
    interest = (payment - ppn).toFixed(2);
    principal_portion.push(ppn);
    interest_paid.push(interest);
}
ob.push(a-principal_portion[0]);
for (i = 1; i < p; i++){
    ob.push(ob[i-1]-principal_portion[i]);
}

var fs = require('fs');

var htmlContent = '
\n
Sl no	Amount	Total Amount	Interest Amount	Balance
\n';
for (i = 0; i < p; i++){
    htmlContent = htmlContent + '
' + string(slno) + '	' + payment + '	' + principal_portion[i] + '	' + interest_paid[i] + '	' + ob[i] + '
\n';
}
htmlContent = htmlContent + '
';
fs.writeFile('result.html', htmlContent, (error) => { /* handle error */ });
window.open("result.html");
}

A: I think that maybe you can solve the problem by writing the HTML code directly on the document:
function loancalculate() {
    var a = parseFloat(document.getElementById('num1').value);
    var r = parseFloat(document.getElementById('num2').value);
    var p = parseFloat(document.getElementById('num3').value);
    var res;

    var principal_portion = [];
    var interest_paid = [];
    var payment = (r * a) / (1 - (1 + r) ** (-p));
    payment = payment.toFixed(2);
    var ob = [];
    for (i = 1; i < p + 1; i++) {
        ppn = payment * (1 + p - i).toFixed(2);
        interest = (payment - ppn).toFixed(2);
        principal_portion.push(ppn);
        interest_paid.push(interest);
    }
    ob.push(a - principal_portion[0]);
    for (i = 1; i < p; i++) {
        ob.push(ob[i - 1] - principal_portion[i]);
    }

    //var fs = require('fs');

    var htmlContent = '
\n
Sl no	Amount	Total Amount	Interest Amount	Balance
\n';
    for (i = 0; i < p; i++) {
        htmlContent = htmlContent + '
' + i + '	' + payment + '	' + principal_portion[i] + '	' + interest_paid[i] + '	' + ob[i] + '
\n';
    }
    htmlContent = htmlContent + '
';

    document.write(htmlContent);

    //fs.writeFile('result.html', htmlContent, (error) => { /* handle error */ });
    //window.open("result.html");
}

I made some modifications in your code to exemplify how it could be achieved.


text:
Q: What is the hotkey to open Build explorer in Team Explorer pane in Visual Studio 2012? Currently to get to Build page, we open Team Explorer and hit Home button and go for Build.
What is the hotkey for that?

A: (from user admdrew)
This seems to be the closest you can get (also seen here).


text:
Q: How to redirect to localized route in node.js express I'm using the official i18n library to localize my Angular Universal app and am using a proxy to serve the localized versions.
My app works fine as long as there is a language present in the url (e.g: /en/page), but doesn't work otherwise (e.g: / or /page). I get the error Cannot GET / whenever I try to access a page without the locale in the url.
How do I redirect the user to the localized version of the page using the accept-language header of the request? If I try it with the code below, it creates a redirect loop and the page doesn't load.
server.run.js
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');

function app() {
  const server = express();

  server.use(cookieParser());

  server.use('/', (req, res, next) => {
    const languages = ['en', 'de', 'fr'];

    languages.forEach((locale) => {
      const appServerModule = require(path.join(__dirname, locale, 'main.js'));
      server.use(`/${locale}`, appServerModule.app(locale));
    });

    locale = (req.headers['accept-language'] || '').substring(0, 2);

    if (!languages.includes(locale)) {
      locale = 'en';
    }

    res.redirect(`/${locale}`)
  });

  return server;
}

function run() {
  app().listen(4200, () => {
    console.log(`Node Express server listening on http://localhost:4200`);
  });
}

run();

A: I managed to solve it like this:
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');

function app() {
  const server = express();

  server.use(cookieParser());

  const languages = ['en', 'de', 'fr'];

  languages.forEach((locale) => {
    const appServerModule = require(path.join(__dirname, locale, 'main.js'));
    server.use(`/${locale}`, appServerModule.app(locale));
  });

  server.get('/(:locale(en|fr|de)/)?*', (req, res, next) => {
    const { urlLocale } = req.params;
    const userLocale = (req.headers['accept-language'] || '').substring(0, 2);

    if (urlLocale !== userLocale) {
      res.redirect(userLocale + req.url);
    }
  });

  return server;
}

function run() {
  app().listen(4200, () => {
    console.log(`Node Express server listening on http://localhost:4200`);
  });
}

run();


text:
Q: Bash script - display file from the "c"th line I have a script, that display "n" lines and display form "c" line.
#!/bin/bash
hn=5
tn=1
while getopts ":n:c:" opt
do
    case $opt in
        h) echo Pomocy
            exit 1
            ;;
        n) hn=$OPTARG ;;
        c) tn=$OPTARG ;;
        \?) echo Nieznana opcja $OPTARG;;
        :) echo Brakuje argumentu opcji $OPTARG ;;
    esac
done

shift $(($OPTIND-1))
for i do
    if [[ -f $1 ]];
    then

        cat $i | head -n $hn
    else
        echo "plik nie istnieje"
    fi
done

exit 0

how to make it display from c line?
display "n" lines iw work. what command to do "c" line?
it displays from 1 line by default
Thanks for help. This command works good
cat $i |head -n $hn | tail -n +$tn

A: A simple way with tail, wc and awk:
a=`wc -l $file | awk '{print $1}'`
tail -n $(( a - tn)) $hn

And if I put that in your original file:
#!/bin/bash
hn=5
tn=1
while getopts ":n:c:" opt
do
    case $opt in
        h) echo Pomocy
            exit 1
            ;;
        n) hn=$OPTARG ;;
        c) tn=$OPTARG ;;
        \?) echo Nieznana opcja $OPTARG;;
        :) echo Brakuje argumentu opcji $OPTARG ;;
    esac
done

shift $(($OPTIND-1))
for i do
    if [[ -f $1 ]];
    then
        a=`wc -l $file | awk '{print $1}'`
        tail -n $(( a - tn)) $hn
    else
        echo "plik nie istnieje"
    fi
done
exit 0


text:
Q: ping does not resolve the host - always appends a domain The problem seems to be relatively easy, but I can't find good solution.
Configuration
I have local DHCP and DNS server running on ADSL router. It assigns IP addresses to local hosts and also keeps DNS records for assigned IPs.
This modem also registers itself via DynDNS services.
Let's assume I have no control over this modem, as it serves several groups.
Problem
When I look the host via nslookup it works fine:
$ nslookup vanja
Server:         192.168.1.1
Address:        192.168.1.1#53

Name:   vanja
Address: 192.168.1.12

but with ping it fails:
$ ping vanja
ping: unknown host vanja

This happens, because ping appends the local domain to the host, but DNS server does not know this domain (and I have no ways to set it), see strace output:
$ strace ping vanja
open("/lib/i686/cmov/libnss_dns.so.2", O_RDONLY) = 4
stat64("/etc/resolv.conf", {st_mode=S_IFREG|0644, st_size=23, ...}) = 0
socket(PF_INET, SOCK_DGRAM|SOCK_NONBLOCK, IPPROTO_IP) = 4
connect(4, {sa_family=AF_INET, sin_port=htons(53), sin_addr=inet_addr("192.168.1.1")}, 28) = 0
send(4, "\377N\1\0\0\1\0\0\0\0\0\0\5vanja\10dynalias\3com\0"..., 36, MSG_NOSIGNAL) = 36
recvfrom(4, "\377N\201\203\0\1\0\0\0\1\0\0\5vanja\10dynalias\3com\0"..., 1024, 0, {sa_family=AF_INET, sin_port=htons(53), sin_addr=inet_addr("192.168.1.1")}, [16]) = 97

Also note that nslookup vanja.dynalias.com will also fail on the same reason: DNS only maps dynamically assigned IPs to short PC names (which are passed from MS Windows workstations).
When I set the hostname to name without domain (# hostname centurion) ping magically starts working, but I cannot leave hostname not in FQDN form, as otherwise it may confuse apache & postfix or break other things.
Question: How can I make ping working together with having hostname in FQDN form?
Note: My attempts to play with search and domain options of /etc/resolv.conf haven't succeeded. My goal was to force NSS library not to append domain name to the passed argument, or, better, make two tries: without and with domain appended.
Relative settings
$ hostname
centurion.dynalias.com
$ cat /etc/resolv.conf
nameserver 192.168.1.1
$ grep hosts /etc/nsswitch.conf
hosts:          files dns

A: You may try
search . domainname.ext

to see if just adding the '.' works.
Also
$ ping vanja.

would give you some clues.

A: Your resolver search path needs to be set.
In /etc/resolv.conf, add the line:
search domainname.ext

(Of course, replace domainname.net above with your domain name).
This will ensure that ping hostname also looks up hostname.domainname.ext. Note that, you can add multiple domain names to the search path if you want.


text:
Q: Creating dynamically scheduled functions I have a list of 10 time stamps which keeps on updating dynamically. In total there are 3 such lists for 3 users. I want to build a utility to trigger a function at the next upcoming time stamp. (preferably everything over server-less compute)
I am stuck in finding out how to achieve this over aws or firebase

A: On Firebase/Google Cloud Functions the two most common options are either to store the schedule in a database and then periodically trigger a Cloud Function and run the tasks that are due, or to use Cloud Tasks to dynamically schedule a callback to a separate Cloud Function for each task.
I recommend also reading:

*

*Doug's blog post on How to schedule a Cloud Function to run in the future with Cloud Tasks (to build a Firestore document TTL)

*Fireship.io's tutorial on Dynamic Scheduled Background Jobs in Firebase

*How can scheduled Firebase Cloud Messaging notifications be made outside of the Firebase Console?

*Previous questions on dynamically scheduling functions, as this has been covered quite well before.

Update (late 2022): there is now also a built-in way to schedule Cloud Functions dynamically: enqueue functions with Cloud Tasks.


text:
Q: Wordpress plugins for making gallery I wish to make a gallery similar to http://welovewp.com
Can anyone guess, how this is made ?
Is there any already existing plugin or do we need to code for that ourselves.
Thanks :)

A: Some gallery plugins for WP:
http://wordpress.org/extend/plugins/wordpress-gallery-plugin/screenshots/
http://wordpress.org/extend/plugins/nextgen-gallery/
For an extensive list of gallery plugins, try the WordPress.org plugins site:
http://wordpress.org/extend/plugins/
BTW, the site you're linking to doesn't seem to be using a gallery plugin.
They're using a list of posts with a featured image and URL styled in HTML & CSS.

A: Indranil has given you options for generating galleries out of photos stored on your server. If your photos are stored on some photo sharing website, you'll have search for those kind of specific plugins.
For example, if your photos are stored on Flickr, you can try any of these 3 plugins -

*

*Awesome Flickr Gallery

*Slickr-Flickr

*Flickr Gallery


text:
Q: Applying DRY to a set of similar functions Applying DRY is my biggest struggle. Can anyone help me create a single function that achieves the same as those 4 functions as well as how to call it for each .symbol?
$(".symbol:nth-child(1)").click(function(){
  $("body").removeClass();
  $("body").addClass("gradient1");
})

$(".symbol:nth-child(2)").click(function(){
  $("body").removeClass();
  $("body").addClass("gradient2");
})

$(".symbol:nth-child(3)").click(function(){
  $("body").removeClass();
  $("body").addClass("gradient3");
})

$(".symbol:nth-child(4)").click(function(){
  $("body").removeClass();
  $("body").addClass("gradient4");
})

A: You can create a function that takes an index and assigns a click handler:
function applyNthClick( n ) {
   $(".symbol:nth-child(" + n + ")").click(function(){
     $("body").removeClass();
     $("body").addClass("gradient" + n);
   })
}

And then use it like this:
applyNthClick(1);
applyNthClick(2);
applyNthClick(3);
applyNthClick(4);

Or, if you know all the ns, you could make an array of them, and then map the function over it:
[1,2,3,4].forEach( applyNthClick );

A: Can use the index of each element within the whole symbol collection
var $symbols = $(".symbol").click(function(){
     var symbolIndex = $symbols.index(this);
     $("body").removeClass().addClass("gradient" + (symbolIndex +1) );
 });

Reference: index()


text:
Q: Close votes are counting as flags (again) Questions that have been deleted, which I voted to close in addition to flagging, are showing my close votes as if they were flags on MSO.
For instance this question

and this one

Answers which I've flagged as spam don't show this...
The same was sort of showing yesterday when things were broken but without the close reason.

This is now broken again, save on Stack Overflow not MSO:

A: We moved close votes into the same table that flags reside in (close votes are essentially another form of content flagging) and the close votes were slipping through here.
It is now fixed.


text:
Q: Jquery change event in Datalist[html5] this is my code:
<input name="cmbname" type="text" id="cmbname" list="listcmbname" autocomplete="off" runat="server">
<datalist id="listcmbname">
         <option data-id="1" value="a"></option>
         <option data-id="8" value="aa"></option>
         <option data-id="10" value="aaa"></option>
         <option data-id="11" value="b"></option>
         <option data-id="15" value="bb"></option>
         <option data-id="18" value="bbb"></option>
</datalist>

I used cmbname.value to get input value in the code behind.
But I also need the data-id. I've used cmbname.Attributes["data-id"] but it did not work.
I think it will be fixed with jquery change event.
please help

A: See this: http://jsfiddle.net/xttwt/48/,
you can find out the data-id of option currently selected like this:
var val=$('#cmbname').val();
var data_id= $('#listcmbProcess').find('option[value="'+val+'"]').data('id');

A: Well, Jquery has the .data() method. So to get the 'data-id' attribute, you would use $('input').data("id");

A: $('#cmbname').attr('data-id'); you can also use this to get the data id

A: Use this attr()
$('#cmbname').attr('data-id');

A: i used this:
<input id="cmbLoc" name="cmbLoc" runat="server" list="listcmbLoc" autocomplete="off" />
<datalist id="listcmbLoc">
       <option data-id="15" value="CPF"></option>
       <option data-id="18" value="HOLD"></option>
       <option data-id="19" value="CCR"></option>
 </datalist>

<input id="cmbLoc_ID" type="text" name="cmbLoc_ID" runat="server"/>

And enter cmbLoc_ID.value in the code behind it to get data-id.


text:
Q: Efficient rating system I'm building a news rating script for this website that has a lot of users. I'm trying to make this websites as efficient as possible and now I'm wondering what would be the most efficient way to keep track of the votes. Of course I don't want users to vote more than once.
My first though was to store it in a my MySQL database, but I'm worried this would have a negative influence in my website's speed because this table would get quite big.
Would storing it in a database still be the best solution or are there any better solutions.

A: If you plan on having > 1,000,000 records you should make sure the table's structure is efficient (which shouldnt be hard for your example) and that you index it correctly.
Memcached would be the simplest way to implement caching and is easy to scale if your site grows and more servers are necessary.

A: With a properly indexed vote table, you can keep reasonable performance regardless of how large your table is (of course, beyond a certain point, your tables will be too large to fit in cache, but that would involve having a very large number of users and items).
Add in some per-user caching (on the client, in $_SESSION, using memcached) and you can get a quite fast "no" response time).

A: Memcached would be a very good way  to do this. you need to synchronize from memcached once in a while (I would do this using the pull model using a cron script on you mysql server).

A: Since you can't use memcached I would say this. A decent database server ( decent hardware + decent db implementation) should be able to handle this quite well. A single table with a physical index on article-id and a second entry representing the vote will handle a few googillion (yes I made up the word) articles easily :P
Rationale :
Database servers maintain statistics -- read: self-tuning -- and only hot items (index + row-entries) remain in-memory.
Moral:
Don't worry about such things unless they become a problem -- i.e., If your company is the size of facebook I would worry.

A: Did you see this?
http://destiney.com/php#Destiney_rated_images
Demo here: http://ratedsite.com/