text:
Q: cant get data from database after multiple schema declared (mongoose + express + mongodb I'm new to node.js and I am having problem accessing to the when multiple mongoose schema were declare.
//schema.js in model
var mongoose = require('mongoose');
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;

//User Schema
var userSchema = new Schema({
id: ObjectId,
firstname: {type: String, require: true},
lastname: {type: String, require: true},
username: {type: String, unique: true, require: true},
password: {type: String, require: true},
role: {type: [String], require: true}
})

var User = mongoose.model('User', userSchema);
module.exports = User;

//Question Schema
var qnSchema = new Schema({
id: ObjectId,
question: {type: String, require: true},
module_id: {type: ObjectId, ref: 'Module'}
})

var Question = mongoose.model('Question', qnSchema);
module.exports = Question;

//Answer Schema
var ansSchema = new Schema({
id: ObjectId,
answer: String,
question: {type: ObjectId, ref: 'Question'}
})

var Answer = mongoose.model('Answer', ansSchema);
module.exports = Answer;

//Module Schema
var modSchema = new Schema({
id: ObjectId,
name: {type: String, require: true}
})

 var Module = mongoose.model('Module', modSchema);
  module.exports = Module;

//Role Schema
var roleSchema = new Schema({
id: ObjectId,
role: {type: String, require: true}
})

var Role = mongoose.model('Role', roleSchema);
module.exports = Role;

//index.js in controller
var mongoose = require('mongoose');
var User = require('../models/schema');
var db = mongoose.connect('mongodb://localhost/damai');

module.exports = function(app) {

app.get('/', function(req, res) {
    if (typeof req.session.userid == 'undefined') {
        res.render('login', { title: app.get('title') });
    } else {
        res.render('index', { title: app.get('title') });
    }
});

app.post('/login', function(req, res) {
    passwordVerification(req, res);
});
}

function passwordVerification(req, res)
{
var userid = req.param('userid');
var password = req.param('password');
User.findOne({'username': userid},{'password': 1}, function(err, cb)
{
    console.log(cb);
    if(cb!= null)
    {
        if (password == cb.password) {
            req.session.userid = userid;
            res.render('index', { title: app.get('title'), 'userid':    userid });
        } else {
            res.render('login', { title: app.get('title'), error: 'Invalid login'});
        }
    }
    else
    {
        res.render('login', { title: app.get('title'), error: 'Invalid login'});
    }
});
}

When I only have the "User Schema" in my schema.js, the database call from method "passwordVerification()" from index.js will return me the relevant password that was retrieve from the database. However, when I start adding in other schema such as "Question Schema" in schema.js, the method "passwordVerification()" will always return null.

A: When exporting multiple models from a single file like you are in schema.js, you need to give each exported model its own exports field name.
For example, replace the multiple module.exports = ... lines in schema.js with this code at the end of the file that exports all models:
module.exports = {
    User: User,
    Question: Question,
    Answer: Answer,
    Module: Module,
    Role: Role
};

And then in index.js you can access the models like so:
var models = require('./schema');
...
models.User.findOne(...


text:
Q: PayPal Checkout SDK breakdown object raising error I am attempting to handle payments using the PayPal Checkout SDK on a storefront I am developing. I am attempting to add a shipping amount of $10 USD to all orders. Looking at the SDK documentation I believe I'll need to use the amount and breakdown objects.
Code
      createOrder: (data, actions) => {
        return actions.order.create({
          purchase_units: [{
            amount: {
              breakdown: {
                item_total: {currency_code: "USD", value: "32"},
                shipping: {currency_code: "USD", value: "10"}
              }
            }
          }]
        })
      }

Error
Uncaught Error: /v2/checkout/orders returned status 400 (Corr ID: 46c2d60c192b).

{"name":"INVALID_REQUEST","message":"Request is not well-formed, syntactically incorrect, or violates schema.","debug_id":"46c2d60c192b","details":[{"field":"/purchase_units/@reference_id=='default'/amount/value","value":"","location":"body","issue":"MISSING_REQUIRED_PARAMETER","description":"A required field / parameter is missing."}],"links":[{"href":"https://developer.paypal.com/docs/api/orders/v2/#error-MISSING_REQUIRED_PARAMETER","rel":"information_link","encType":"application/json"}]}

A: The amount itself needs a value and currency_code, separate from any extra object that gives a breakdown.
See the full example in the 6th bullet of this documentation:
createOrder: function(data, actions) {
      return actions.order.create({
         "purchase_units": [{
            "amount": {
              "currency_code": "USD",
              "value": "100",
              "breakdown": {
                "item_total": {  /* Required when including the `items` array */
                  "currency_code": "USD",
                  "value": "100"
                }
              }
            },
            "items": [
              {
                "name": "First Product Name", /* Shows within upper-right dropdown during payment approval */
                "description": "Optional descriptive text..", /* Item details will also be in the completed paypal.com transaction view */
                "unit_amount": {
                  "currency_code": "USD",
                  "value": "50"
                },
                "quantity": "2"
              },
            ]
          }]
      });
    },

redpajama_set_name: RedPajamaStackExchange


text:
Q: using nav-tabs as step element twitter bootstrap I've done some sort of reverse engineering to make the nav-tabs component in Bootstrap to work as a step element. This is similiar to the step element used in semantic UI
Now, I managed to get this far (overriding the nav-tabs CSS and adding the styles for the arrows) but there are some issues I cannot figure out

*

*I don't know how to space the text out nicely, especially starting from the 2nd step text. I change the padding/margin of the arrows but it messes the positioning of the others (or that also needs to be tweaked)

*When you hover over the anchor tag its fine. but then, when an element is active, and you hover over just the arrow (the triangle sort of), that gets highlighted whereas it should highlight the entire previous step element that can be clickable (if you get the gist of how it needs to be in a step wizard sort-of)

Any tips on this? it's some pseudo class setting i'm missing or repeating somewhere!
 .nav-steps>.step:after {
    position: absolute;
    z-index: 2;
    content:'';
    top: 0em;
    right: -22px;
    border-bottom: 23px solid transparent;
    border-left: 23px solid orange;
    border-top: 24px solid transparent;
}

 .nav-steps .step:hover:after {
    border-left-color: pink;
}

http://jsfiddle.net/chou_one/NemwU/
P.S there might be a cleaner approach to this, maybe with spans?

A: YOu add 99% correct :) instead of adding the ARROW to the <li> you need to add it to the <a>, where is a working demo.
CSS code change:
.steps-headers {
    text-align: center;
}

.nav-steps {
  border: none;
  padding-bottom: 1px;
  background-color: orange;
  display: inline-block;
overflow: hidden;
}

.nav-steps>li>a {
  margin-right: 0px;
  line-height: 1.428571429;
       width: 180px;
}

/* step arrow style */
.nav-steps>.step a:after {
position: absolute;
z-index: 2;
content: '';
top: 0px;
right: -30px;
border-bottom: 23px solid transparent;
border-left: 23px solid orange;
border-top: 20px solid transparent;
width: 31px;
}

/* disable step arrow style for last item */
.nav-steps>.step:last-child a:after {
  display: none;
}

/* HOVER STYLE */

/* hover state */
.nav-steps>li a:hover {
  background-color: pink;
  color: white;
  border-radius: 0px;
}

/* step arrow color on hover:after */
.nav-steps .step:hover a:after {
  border-left-color: pink;
}

/* ACTIVE STYLE */

/* active state */
.nav-steps>li.active>a, .nav-steps>li.active>a:hover, .nav-steps>li.active>a:focus {
  background-color: yellow;
  color: black;
  border-radius: 0px;
}

/* step arrow color on active:after */
.nav-steps .step.active a:after {
  border-left-color: yellow;
}


text:
Q: circle and complex number $P$ is a point on the Argand diagram. On the circle with $OP$ as diameter two points $Q$ and $R$ are taken such that $\angle POQ = \angle QOR = \theta$. If $O$ is the origin and $P$, $Q$, $R$ are represented by the complex numbers $Z_1$, $Z_2$, $Z_3$
respectively, show that
$$Z_{2}^{2} \cos 2\theta = Z_1 \cdot Z_3 \cos^2 \theta$$
I tried it a lot but don't know how to start.  Can anybody provide a hint?

A: Assume $z_1\ne z_3$ and take $\theta \in \left( 0,\frac{\pi}{4} \right)$ as anti-clockwise whereas $\theta \in \left( -\frac{\pi}{4},0 \right)$ as clockwise.
\begin{align*}
  z_2 &= \frac{z_1}{2}(1+e^{2i\theta}) \\
  z_3 &= \frac{z_1}{2}(1+e^{4i\theta}) \\
  z_2^2 \cos 2\theta &=
  \frac{z_1^2}{4}(1+e^{2i\theta})^2 \times
  \frac{e^{2i\theta}+e^{-2i\theta}}{2} \\
  &= \frac{z_1^2}{4}(1+e^{2i\theta})^2 \times
  \frac{1+e^{4i\theta}}{2e^{2i\theta}} \\
  &= \frac{z_1^2(1+e^{4i\theta})}{2}
     \left( \frac{e^{i\theta}+e^{-i\theta}}{2} \right)^2 \\
  &= z_1 z_3 \cos^2 \theta
\end{align*}


text:
Q: Is there a utility that will greate an iPhone screenshot with hardware and reflection? I need to take screen shots of my iPhone app and load it on a web site. I know how to get the raw image of the screen but I was wondering if there is a utility out there that can take a screen shot and add the hardware image too?

A: Check out iOS Simulator Cropper.


text:
Q: SoapServer persistence fails randomly I've made SOAP WSDL service which works. I've added 2 methods to test - the first one (setX($x)) sets $this->x to $x, second one (getX()) returns $this->x. The constructor of my SOAP class sets $this->x to 'FAIL', while client code calls setX('SUCCESS').
I've added some dummy variables to make them both request-response type (one-way seem to have some weird problems with some clients).
Well, it works, client calls $s->setX('SUCCESS') and $x = $s->getX(''), and $x = 'SUCCESS'. As expected.
But to achieve this, I had to use following option with client:
'cache_wsdl' => WSDL_CACHE_MEMORY
Why? It beats me. With every other option it just doesn't work - $x = 'FAIL' (no persistence)
OK, it works, so what's the problem? Sometimes, YES, SOMETIMES it doesn't work. The code randomly returns 'FAIL' (as persistence was broken). When it start to return 'FAIL' it keeps to do so. You can start another browser, and it will MOST PROBABLY report 'SUCCESS'.
Now the weirdest part. Let's use one browser. Let's repeat following steps: start the browser, check the code output until it returns 'FAIL'. Now, press 'Ctrl+R' for about 2 seconds. Suddenly it works, now it's 'SUCCESS' every time!
WTF?!!! I really double checked the session. Session is created properly before each time SoapServer is created. Each time $server->setPersistence(SOAP_PERSISTENCE_SESSION) is called. And it works only "most of the time" - which makes it completely useless!
Any clues?
PS: My service WSDL is generated and cached. I've added sleep(1) to WSDL generator, and benchmarked client code. It seems not to regenerate WSDL (ends in ca. 10ms - not 1010ms). Invalidating WSDL cache (with TTL set to 1) doesn't make persistence work, but stupid holding Ctrl+R in browser does!
PS2: WSDL generator, SOAP class and test client are in 3 different files. WSDL class actually starts the server. It's called from the file which contains SOAP class (index.php).
PS3: I removed .htaccess which should not break anything, I removed some unused files and code, and boom - now it works everytime, with any type of wsdl_cache! Well, I don't know what it was, .htaccess? Maybe Apache server internal problems. I cannot reproduce it anymore. If you experience similar problems, my advice is to drop .htaccess and try to restart Apache. The problems happened very early morning / late night - I'm not sure but I think cron does some intensive backup tasks at the time. Maybe compulsive reloading told Linux to relax with background tasks and put more resources to Apache and PHP - this would explain weird Ctrl+R behavior.
UPDATE: It still fails randomly! Works most of the time, but I can't rely on this feature. (Tested with different service, different client, but still the same server).


text:
Q: how to avoid a particular record to be opened by anybody else in MS CRM In my application i want to prevent any other user from opening the record of particular client while somebody has already opened it. And show him somekind of error or alert.
How should i do that?? I appreciate any answers or suggestions.
Thanks,

A: There is no simple way to do this, but you can do what GCATNM mentioned before me. I would add one thing, though.
If this is an on-premise installation, you can set up an asmx service that accepts an entityid and a username. This will update the lockedOn date of the attribute with the current date. Then, have a script that runs on the entity record that calls this asmx every minute to update the lockedOn date. This tells the system that you are still actively using this record.
Then, in your code that checks to see if anyone is locking the entity, you ignore any locks that have a lockedOn date more than 5 minutes ago.

A: You could add a lookup to systemuser ("Currently opened by") to the entity, and when the form is opened, check whether it has a value. If so, display a message and close the form or forward to the readonly form. If not, set the lookup to the current user via a webservice call (so that it's actually in the database that same moment), so everyone else gets the notification when opening the form. When saving or otherwise closing the form (onbeforeunload event), do another webservice call (or, when saving, simply set the empty lookup's ForceSubmit property to true) to clear the lookup.
Note that this will not catch certain things like a crashing client (which would leave the record "locked"), so you'd need some kind of failsafe, like a workflow that clears the lookup after it has been set and the record has not been modified again for a certain time.
Also, any other logic that might modify the record (like plugins, imports, any custom development) would have to be done in a way that avoids collisions with this "locking" functionality.


text:
Q: Getting word-topic probabilities with mallet I am using mallet through the terminal. I have imported the training data in a single file format:
project5 TokenNameCOMMENT This is the actual text

and I have used the train-topics command to create topic models of several sizes.
What I want to do now is to test the trained models on a test set of the same format.
More specifically I want, if possible, to get the topic assigned to each of my test files, along with the probability of each word for that topic and test file. If it is possible to get the probability of each word for any topic as well that would be great.
Thank you


text:
Q: Eclipse Kepler crashes without any log entry I'm using Ubuntu 13.10 Saucy Salamander 64bit and Eclipse Kepler 64bit terminates after some random time without response. The windows simply disappears.
There's also no entry about the crash in .metadata/.log

A: I had same problem (Ubuntu 13.10 64-bit, Eclipse Kepler, Intel Sandybridge Mobile graphics) and this helped:
Put inside eclipse.ini:
-Dorg.eclipse.swt.browser.DefaultType=mozilla

Thanks to NVK.


text:
Q: How to pass epoch and batch size when using label powerset in keras I have a multi-label problem and with some research, I was able to use Label powerset in conjunction with ML algorithms. Now I want to use the Label powerset with neural network and as per the official website I can use Label powerset. But I am not able to understand how to modify my existing code to be able to use Label Powerset.
I want to know how can we pass epoch or batch_size or any other parameter passed in the fit function of the model.
Since I have a multi-label problem I have used MultiLabelBinarizer of sklearn so my each target row looks like this [1,0,0,1,0,0,0,0,0,0,0,0].
and lastly, if someone could explain to me what is KERAS_PARAMS and Keras() in the below line:
def create_model_multiclass(input_dim, output_dim):
    # create model
    model = Sequential()
    model.add(Dense(8, input_dim=input_dim, activation='relu'))
    model.add(Dense(output_dim, activation='softmax'))
    # Compile model
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model
clf = LabelPowerset(classifier=Keras(create_model_multiclass, True, KERAS_PARAMS), require_dense=[True,True])
clf.fit(X_train,y_train)
y_pred = clf.predict(X_test)

Below is my existing neural network code
cnn_model = Sequential()
cnn_model.add(Dropout(0.5))
cnn_model.add(Conv1D(25,7,activation='relu'))
cnn_model.add(MaxPool1D(2))
cnn_model.add(Dropout(0.2))
cnn_model.add(Conv1D(25,7,activation='relu'))
cnn_model.add(MaxPool1D(2))
cnn_model.add(Flatten())
cnn_model.add(Dense(25,activation='relu'))
cnn_model.add(Dense(12,activation='softmax'))
cnn_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
history = cnn_model.fit(X_train, y_train, validation_data=(X_test,y_test), batch_size=32, epochs=180,verbose=1)
plot_history(history)
predictions = cnn_model.predict(X_test)

I want my output row to look like this only [1,0,0,1,0,0,0,0,0,0,0,0] as later I will use my MultiLabelBinarizer for the inverse transform of this.

A: KERAS_PARAMS are parameters to the Keras scikit wrapper. The documentation for it is rather sparse.
Basically it seems to be the params that you would pass, for instance, to keras.fit.
KERAS_PARAMS = dict(epochs=10, batch_size=100, verbose=0)

From reading the docs, it seems to me that LabelPowerset transforms a multi-label problem into a multi-class problem by creating class permutations. You may consider just using a native Keras solution for a multi-label problem rather than using a wrapper.
The following tutorial seems reasonable:
https://medium.com/@vijayabhaskar96/multi-label-image-classification-tutorial-with-keras-imagedatagenerator-cd541f8eaf24
The key differences are that your output layer should have a sigmoid activation rather than softmax and the loss should be binary_crossentrophy rather than categorical.


text:
Q: Backendless swift HOW TO LOAD OBJECTS FROM AN MBAAS STORAGE I followed the example LOAD OBJECTS FROM AN MBAAS STORAGE, from Backendless site, however I've got an error (saying Value of type 'AnyObject' has no member 'name') trying to get the values (from Restaurant collection) by direct reference as in the example :
for restaurant in currentPage {
print("Restaurant name = \(restaurant.name)")
}

A: Adding a little change in the code (using Swift 2.0.+), just in case anyone has the same problem that I had.
So I added an explicit reference instead.
for restaurant in currentPage {
let rest : Restaurant = restaurant as! Restaurant
print("Restaurant name = \(rest.name!)")
}

This way you get the value wanted, no error thrown.
I hope this help some one.
Regards


text:
Q: Accessing the web page's HTTP Headers in JavaScript How do I access a page's HTTP response headers via JavaScript?
Related to this question, which was modified to ask about accessing two specific HTTP headers.

Related:
How do I access the HTTP request header fields via JavaScript?

A: You can't access the http headers, but some of the information provided in them is available in the DOM. For example, if you want to see the http referer (sic), use document.referrer. There may be others like this for other http headers. Try googling the specific thing you want, like "http referer javascript".
I know this should be obvious, but I kept searching for stuff like "http headers javascript" when all I really wanted was the referer, and didn't get any useful results. I don't know how I didn't realize I could make a more specific query.

A: Like many people I've been digging the net with no real answer :(
I've nevertheless find out a bypass that could help others. In my case I fully control my web server. In fact it is part of my application (see end reference). It is easy for me to add a script to my http response. I modified my httpd server to inject a small script within every html pages. I only push a extra 'js script' line right after my header construction, that set an existing variable from my document within my browser [I choose location], but any other option is possible. While my server is written in nodejs, I've no doubt that the same technique can be use from PHP or others.
  case ".html":
    response.setHeader("Content-Type", "text/html");
    response.write ("")
    // process the real contend of my page

Now every html pages loaded from my server, have this script executed by the browser at reception. I can then easily check from JavaScript if the variable exist or not. In my usecase I need to know if I should use JSON or JSON-P profile to avoid CORS issue, but the same technique can be used for other purposes [ie: choose in between development/production server, get from server a REST/API key, etc ....]
On the browser you just need to check variable directly from JavaScript as in my example, where I use it to select my Json/JQuery profile
 // Select direct Ajax/Json profile if using GpsdTracking/HttpAjax server otherwise use JsonP
  var corsbypass = true;
  if (location['GPSD_HTTP_AJAX']) corsbypass = false;

  if (corsbypass) { // Json & html served from two different web servers
    var gpsdApi = "http://localhost:4080/geojson.rest?jsoncallback=?";
  } else { // Json & html served from same web server [no ?jsoncallback=]
    var gpsdApi = "geojson.rest?";
  }
  var gpsdRqt =
      {key   :123456789 // user authentication key
      ,cmd   :'list'    // rest command
      ,group :'all'     // group to retreive
      ,round : true     // ask server to round numbers
   };
   $.getJSON(gpsdApi,gpsdRqt, DevListCB);

For who ever would like to check my code:
https://www.npmjs.org/package/gpsdtracking

A: Allain Lalonde's link made my day.
Just adding some simple working html code here.
Works with any reasonable browser since ages plus IE9+ and Presto-Opera 12.
<!DOCTYPE html>
<title>(XHR) Show all response headers</title>

All Response Headers with XHR

Note: You get headers of a second request, the result may differ from the initial request.

Another way is the more modern fetch() API
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
Per caniuse.com it's supported by Firefox 40, Chrome 42, Edge 14, Safari 11
Working example code:

<!DOCTYPE html>
<title>fetch() all Response Headers</title>

All Response Headers with fetch()

A: If we're talking about Request headers, you can create your own headers when doing XmlHttpRequests.
var request = new XMLHttpRequest();
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.open("GET", path, true);
request.send(null);

A: It's not possible to read the current headers. You could make another request to the same URL and read its headers, but there is no guarantee that the headers are exactly equal to the current.

Use the following JavaScript code to get all the HTTP headers by performing a get request:
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);

A: To get the headers as an object which is handier (improvement of Raja's answer):
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
headers = headers.split(/\n|\r|\r\n/g).reduce(function(a, b) {
    if (b.length) {
        var [ key, value ] = b.split(': ');
        a[key] = value;
    }
    return a;
}, {});

A: Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request. That was the original question posted here. It has been repeatedly asked, too, because some people would like to get the actual response headers of the original page request without issuing another one.
For AJAX Requests:
If an HTTP request is made over AJAX, it is possible to get the response headers with the getAllResponseHeaders() method. It's part of the XMLHttpRequest API. To see how this can be applied, check out the fetchSimilarHeaders() function below. Note that this is a work-around to the problem that won't be reliable for some applications.
myXMLHttpRequest.getAllResponseHeaders();

*

*The API was specified in the following candidate recommendation for XMLHttpRequest: XMLHttpRequest - W3C Candidate Recommendation 3 August 2010

*Specifically, the getAllResponseHeaders() method was specified in the following section: w3.org: XMLHttpRequest: the getallresponseheaders() method

*The MDN documentation is good, too: developer.mozilla.org: XMLHttpRequest.
This will not give you information about the original page request's HTTP response headers, but it could be used to make educated guesses about what those headers were. More on that is described next.
Getting header values from the Initial Page Request:
This question was first asked several years ago, asking specifically about how to get at the original HTTP response headers for the current page (i.e. the same page inside of which the javascript was running). This is quite a different question than simply getting the response headers for any HTTP request. For the initial page request, the headers aren't readily available to javascript. Whether the header values you need will be reliably and sufficiently consistent if you request the same page again via AJAX will depend on your particular application.
The following are a few suggestions for getting around that problem.
1. Requests on Resources which are largely static
If the response is largely static and the headers are not expected to change much between requests, you could make an AJAX request for the same page you're currently on and assume that they're they are the same values which were part of the page's HTTP response. This could allow you to access the headers you need using the nice XMLHttpRequest API described above.
function fetchSimilarHeaders (callback) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState === XMLHttpRequest.DONE) {
            //
            // The following headers may often be similar
            // to those of the original page request...
            //
            if (callback && typeof callback === 'function') {
                callback(request.getAllResponseHeaders());
            }
        }
    };

    //
    // Re-request the same page (document.location)
    // We hope to get the same or similar response headers to those which
    // came with the current page, but we have no guarantee.
    // Since we are only after the headers, a HEAD request may be sufficient.
    //
    request.open('HEAD', document.location, true);
    request.send(null);
}

This approach will be problematic if you truly have to rely on the values being consistent between requests, since you can't fully guarantee that they are the same. It's going to depend on your specific application and whether you know that the value you need is something that won't be changing from one request to the next.
2. Make Inferences
There are some BOM properties (Browser Object Model) which the browser determines by looking at the headers. Some of these properties reflect HTTP headers directly (e.g. navigator.userAgent is set to the value of the HTTP User-Agent header field). By sniffing around the available properties you might be able to find what you need, or some clues to indicate what the HTTP response contained.
3. Stash them
If you control the server side, you can access any header you like as you construct the full response. Values could be passed to the client with the page, stashed in some markup or perhaps in an inlined JSON structure. If you wanted to have every HTTP request header available to your javascript, you could iterate through them on the server and send them back as hidden values in the markup. It's probably not ideal to send header values this way, but you could certainly do it for the specific value you need. This solution is arguably inefficient, too, but it would do the job if you needed it.

A: Using XmlHttpRequest you can pull up the current page and then examine the http headers of the response.
Best case is to just do a HEAD request and then examine the headers.
For some examples of doing this have a look at http://www.jibbering.com/2002/4/httprequest.html
Just my 2 cents.

A: A solution with Service Workers
Service workers are able to access network information, which includes headers. The good part is that it works on any kind of request, not just XMLHttpRequest.
How it works:

*

*Add a service worker on your website.

*Watch every request that's being sent.

*Make the service worker fetch the request with the respondWith function.

*When the response arrives, read the headers.

*Send the headers from the service worker to the page with the postMessage function.

Working example:
Service workers are a bit complicated to understand, so I've built a small library that does all this. It is available on github: https://github.com/gmetais/sw-get-headers.
Limitations:

*

*the website needs to be on HTTPS

*the browser needs to support the Service Workers API

*the same-domain/cross-domain policies are in action, just like on XMLHttpRequest

A: I've just tested, and this works for me using Chrome Version 28.0.1500.95.
I was needing to download a file and read the file name. The file name is in the header so I did the following:
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.responseType = "blob";
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
        success(xhr.response); // the function to proccess the response

        console.log("++++++ reading headers ++++++++");
        var headers = xhr.getAllResponseHeaders();
        console.log(headers);
        console.log("++++++ reading headers end ++++++++");

    }
};

Output:
Date: Fri, 16 Aug 2013 16:21:33 GMT
Content-Disposition: attachment;filename=testFileName.doc
Content-Length: 20
Server: Apache-Coyote/1.1
Content-Type: application/octet-stream

A: This is my script to get all the response headers:
var url = "< URL >";

var req = new XMLHttpRequest();
req.open('HEAD', url, false);
req.send(null);
var headers = req.getAllResponseHeaders();

//Show alert with response headers.
alert(headers);

Having as a result the response headers.

This is a comparison  test using Hurl.it:

A: (2021) An answer without additional HTTP call (works everywhere except Safari)
While it's not possible in general to read arbitrary HTTP response headers of the top-level HTML navigation, if you control the server (or middleboxes on the way) and want to expose some info to JavaScript that can't be exposed easily in any other way than via a header:
You may use Server-Timing header to expose arbitrary key-value data, and it will be readable by JavaScript.
(*in supported browsers: Firefox 61, Chrome 65, Edge 79; no Safari yet and no immediate plans for shipping as of 2021.09; no IE)
Example:
server-timing: key;desc="value"

*

*You can use this header multiple times for multiple pieces of data:

server-timing: key1;desc="value1"
server-timing: key2;desc="value2"

*

*or use its compact version where you expose multiple pieces of data in one header, comma-separated.

server-timing: key1;desc="value1", key2;desc="value2"

Example of how Wikipedia uses this header to expose info about cache hit/miss:

Code example (need to account for lack of browser support in Safari and IE):
if (window.performance && performance.getEntriesByType) { // avoid error in Safari 10, IE9- and other old browsers
    let navTiming = performance.getEntriesByType('navigation')
    if (navTiming.length > 0) { // still not supported as of Safari 14...
        let serverTiming = navTiming[0].serverTiming
        if (serverTiming && serverTiming.length > 0) {
            for (let i=0; i<serverTiming.length; i++) {
                console.log(`${serverTiming[i].name} = ${serverTiming[i].description}`)
            }
        }
    }
}

This logs cache = hit-front in supported browsers.
Notes:

*

*as mentioned on MDN, the API is only supported over HTTPS

*if your JS is served from another domain, you have to add Timing-Allow-Origin response header to make the data readable to JS (Timing-Allow-Origin: * or Timing-Allow-Origin: https://www.example.com)

*Server-Timing headers support also dur(header) field, readable as duration on JS side, but it's optional and defaults to 0 in JS if not passed

*regarding Safari support: see bug 1 and bug 2 and bug 3

*You can read more on server-timing in this blog post

*Note that performance entries buffers might get cleaned by JS on the page (via an API call), or by the browser, if the page issues too many calls for subresources. For that reason, you should capture the data as soon as possible, and/or use PerformanceObserver API instead. See the blog post for details.

A: Another way to send header information to JavaScript would be through cookies. The server can extract whatever data it needs from the request headers and send them back inside a Set-Cookie response header — and cookies can be read in JavaScript. As keparo says, though, it's best to do this for just one or two headers, rather than for all of them.

A: Using mootools, you can use this.xhr.getAllResponseHeaders()

A: For those looking for a way to parse all HTTP headers into an object that can be accessed as a dictionary headers["content-type"], I've created a function parseHttpHeaders:
function parseHttpHeaders(httpHeaders) {
    return httpHeaders.split("\n")
     .map(x=>x.split(/: */,2))
     .filter(x=>x[0])
     .reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});
}

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = parseHttpHeaders(req.getAllResponseHeaders());
// Now we can do:  headers["content-type"]

A: I think the question went in the wrong way,
  If you want to take the Request header from JQuery/JavaScript the answer is simply No. The other solutions is create a aspx page or jsp page then we can easily access the request header.
  Take all the request in aspx page and put into a session/cookies then you can access the cookies in JavaScript page..

A: This is an old question. Not sure when support became more broad, but getAllResponseHeaders() and getResponseHeader() appear to now be fairly standard: http://www.w3schools.com/xml/dom_http.asp

A: As has already been mentioned, if you control the server side then it should be possible to send the initial request headers back to the client in the initial response.
In Express, for example, the following works:
app.get('/somepage', (req, res) => {
    res.render('somepage.hbs', {headers: req.headers});
})

The headers are then available within the template, so could be hidden visually but included in the markup and read by clientside javascript.


text:
Q: Invoke external function in event handler (ReactJS) Is it possible to invoke an external function within an event handler?
I simply want to run an external function on click, the kicker is that I also want to pass some state as props to the external function.
Example code below:
child.js
 import React from 'react';

 export const SomeFunction =  (props) => {
 //some logic to invoke
 };

parent.js
import React, { useState } from 'react';

import { SomeFunction} from './external';

export default function Parent = () => {
const [state, setState] = useState({
        //some state here
});

const handleSubmit = (e) => {
e.preventDefault();

//IS SOMETHING LIKE THIS POSSIBLE???
SomeFunction();

};

return (
    <>
    <button onClick={handleSubmit}>Click me</button>
    </>
);

A: Sure, all you need to do is properly pass the parent's state to the function when invoking the function
SomeFunction({ state });

and then you can do:
export const SomeFunction = (props) => {
  console.log(props.state);
};


text:
Q: Why is my write to virtual memory not visible in Virtual Device Driver? I have a custom driver that I've written meant to facilitate a custom mapping of exact hardware ram memory addresses into user land. I am trying to test that common memory mmap'd as shared between two processes to the same hardware address facilitates visible memory operations that each side can see.
My code is approximately something like this:
  //placement: in a mmap callback to a file_operations facilitated
  //    character device
  //phys_addr - a variable that I will ioremap for a virtual addr
  virtaddr = ioremap(phys_addr, size);
  if (!virtaddr) {
    printk(KERN_INFO "could not remap page!");
    goto out;
  } else {
    printk(KERN_INFO "attempting write");
    *((int *)virtaddr) = 0xdeadbeef;
    //wmb(); <--- I haven't tried this yet
  }

As it so turns out, I thought maybe the issue was the lack of a write barrier to force the cache to flush to ram. I have to boot the test on some special hardware due to OS specifics that are outside the scope of this question. I don't think that write barriers apply to main memory or ram quite like it does for device registers or device memory (ex: cache on a SSD or something). So, I haven't tested wmb, but I just wanted to get my question out there. I've searched around some as well through the Linux Device Drivers 3 book, and I've executed my code; the fragment from which I am pulling is in fact executing and I know it because I can see the printk. The driver executes the code, but then just appears to keep on going. Lastly, there's an analogous piece of code that performs on ioremap on a common piece of hardware memory, which it then tries to read from. That read doesn't contain the value that I wrote to it.
Why?

A: Can you please tell exactly what you mean by this statement "hardware ram memory addresses into user land".
What type of device you are simulating [PCIe, USB etc]
This all depends upon your CPU routing and as hardware is not connected then the translation will not cause fault instead it will send data over bus protocol which will just like fake packed generation from bus controller to device.
To verify you can check bus transactions and in case of IO port mapping you can check using signals coming from specific port address/bits.


text:
Q: Time and events in a Cox model I am going to perform survival analysis using the Cox model, but I have some doubts about the input data.
The data have the following structure:
|| id.patient || Age || Event || Time (days) || other covariates ||

*

*id.patient: numeric ID

*Age: age of the patient Event: 0= (alive), 1=(death),  2=(censored)

*Time: days until event ... but I have time just for event 1 and 2...for the patients alive at the end of the study I haven't the time variable.

*Other covariates: other measures related to the patients.

My questions are:
1) Can I perform the Cox model having 3 types of Events?
2) If yes, how can I perform a Cox model without having time for alive patients?
Any suggestions? Could you kindly provide examples in R?


text:
Q: Tomcat 8 is not able to handle get request I am using Tomcat 8. In one case I need to handle external request coming from external source
Tomcat doesnot log the request.
In this case I am getting following error.
java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
    at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:467)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:667)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

I want to ask If there is any way I can turn the logging to see which character is causing this issue? Also If I log the request Header, which field in header causes this issue.
I read the thread Tomcat 8 is not able to handle get request with '|' in query parameters?
but adding "tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}"
didnt work.


text:
Q: Windows SDK Version was not found On my Windows 7 machine, I have both the Windows SDK(10.0.14393.795) and WDK(10.0.14393.0) versions, yet, when I am building our project in Visual Studio 2015, it keeps on saying that
MSB8036 The Windows SDK version 10.0.14393.0 was not found. Install the required version of Windows SDK or change the SDK version in the project property pages or by right-clicking the solution and selecting "Retarget solution".
The options I have when I am retargeting the solutions are 10.0.10240 and 8.1 but not 10.0.14393.
How can I build this correclty?


text:
Q: Can you pass an instance of a class from inside a class in Android? I'm implementing a fragment, and on the edit of a text (using TextWatcher), I'm passing data to the parent activity using an interface.
I'm wondering though if it's possible to pass the instance of the class itself as the data being passed to the activity? So that I don't have to transfer every single String field one parameter at a time.
So could I do;
Activity:
Fragment frag = new FragmentClass();
// ... start the fragment

The in FragmentClass.java:
editText = findViewById(R.id.edittext);
editText.addTextChangedListener(new TextWatcher() {
    ...
    public void afterTextChanged(...) {
    listener.onChangedListener(PASS IN THE INSTANCE OF THE CLASS ITSELF???);
    }
});

This is to avoid needing to do:
listener.onChangedListener(String field1, String field2, String field3, etc..);

A: If i understand you corrent so you should do somethink like this
    listener.onChangedListener(FragmentClass.this);

And on other side your listener should receive the instance of this class
    interface MyListener {
        void onChangedListener(FragmentClass fragmentClass);
    }

A: You can access a public property on your parent activity from your fragment. Not sure if this is what you want to accomplish. You can try this.
In Activity
public String myText;

In Fragment
YourActivity parentActivity;
parentActivity = (YourActivity)getActivity();

//access the string property of your activity or do something else. Ex. parentActivity.myText = "Sample text"

This is just draft of a code on what I can remember as I am not on an IDE right now.

A: You can create DTO(data transfer object, just simple class) class.
class MyClass {
   String field1;
   String field2;
   String field3;
   MyClass(
       String field1,
       String field2,
       String field3
   ) {
     this.field1 = field1;
     this.field2 = field2;
     this.field3 = field3;
   }
}

And use it like:
MyClass dto = MyClass(field1, field2, field3);
listener.onChangedListener(dto);


text:
Q: Alternative to This in Javascript I have this code on codepen: https://codepen.io/RaoniSousa/pen/Zpkxbb:
var x = document.querySelectorAll('.label'), //label com ID label,
    z = document.querySelectorAll('.input'); //input com ID name;

function myFunction() {
'use strict';
if (this.value !== "" ) {
    this.style.opacity = '1';
    this.style.bottom = '4em';
    this.style.color = '#722872';
    console.log(this);
} else {
    this.style.opacity = '0';
    this.style.bottom = '1.5em';
    console.log(this);
    }
}

In the function above i'd like to change only the style of the label (var x). I know the 'this' is referring to .input (var z), but, i'd like to apply a style to label as i change his related input value, but if i use a for loop, he calls all label one the same time. Is there a way to call var x intead of var z by using 'this.style' or somebody knows another alternative to this code?
I'd like it works as happens here(roll down the bar till reach Contact Me section): https://codepen.io/freeCodeCamp/pen/YqLyXB
Thanks in advance.

A: try this
function myFunction() {
    'use strict';
    if (this.value !== "" ) {
        this.nextElementSibling.style.opacity = '1';
        this.nextElementSibling.style.bottom = '2em';
        this.nextElementSibling.style.color = '#722872';
        console.log(this.nextElementSibling);
    } else {
        this.style.opacity = '.4';
        this.style.bottom = '.5em';
        console.log(this);
    }
}


text:
Q: Method to speed up reading the contents of a file In a script I'm having I'm pulling a csv from a remote server using ftp. I save this file locally and then open the file. I loop through all the contents of the file matching a certain value against it. If it matches, the script can continue.
Enough talking. Lets show some code...
$filename = 'ftp://.....';
$localCsv = '/tmp/'.date('Ymd').'.csv';
if (!file_exists($localCsv)) {
    $content = file_get_contents($filename);
    file_put_contents($localCsv, $content);
}

Now that we have the file created. We can continue to loop.
$handle = fopen($localCsv, "r");
while(!feof($handle)) {
  $rows[] = fgets($handle);
}
fclose($handle);

$results = array();
foreach ($rows as $rid => $row) {
    $columns = explode("\t", $row);
    $results[$columns[2]] = $columns;
}

if (array_key_exists($searchValue, $results)) {
    ... Continue script ...
}

There is just one tiny little problem with this method. It's so slow it's almost going backwards.

A: Heres all baked together, maybe thats faster?
$handle = fopen($localCsv, "r");
$results = array();
while(!feof($handle)) {
    $columns = explode("\t", fgets($handle));
    $results[$columns[2]] = $columns;
    if ($columns[2] == $searchValue) {
        //SEARCH HIT
    }
}
fclose($handle);

If thats not working you could try the csv-specific methods that are in PHP


text:
Q: Modifying an item in a list of lists, changes also other lists same item position The following code is part of a function but the problem I have is on these lines.
# Global variables
NUM_MECS          = 2
MAX_MEC_CAPACITY  = 2
VNF_TYPES         = 2

# Mec capacity to hold a vnf
served_vnfs = list(range(MAX_MEC_CAPACITY+1)) # 0 does not  count as capacity
# All possible mec states as far as holded vnfs
mec_capacity_states = [list(s) for s in itertools.product(served_vnfs, repeat=VNF_TYPES)]
# All possible states with defined number of mecs
mecs_states = [list(p) for p in itertools.product(mec_capacity_states, repeat=NUM_MECS)]

and this generates a list of lists as:
out: [[[0, 0], [0, 0]], [[0, 0], [0, 1]], [[0, 0], [0, 2]], [[0, 0], [1, 0]], [[0, 0], [1, 1]], [[0, 0], [1, 2]], [[0, 0], [2, 0]], [[0, 0], [2, 1]], [[0, 0], [2, 2]], [[0, 1], [0, 0]], [[0, 1], [0, 1]], [[0, 1], [0, 2]], [[0, 1], [1, 0]], [[0, 1], [1, 1]], [[0, 1], [1, 2]], [[0, 1], [2, 0]], [[0, 1], [2, 1]], [[0, 1], [2, 2]], [[0, 2], [0, 0]], [[0, 2], [0, 1]], [[0, 2], [0, 2]], [[0, 2], [1, 0]], [[0, 2], [1, 1]], [[0, 2], [1, 2]], [[0, 2], [2, 0]], [[0, 2], [2, 1]], [[0, 2], [2, 2]], [[1, 0], [0, 0]], [[1, 0], [0, 1]], [[1, 0], [0, 2]], [[1, 0], [1, 0]], [[1, 0], [1, 1]], [[1, 0], [1, 2]], [[1, 0], [2, 0]], [[1, 0], [2, 1]], [[1, 0], [2, 2]], [[1, 1], [0, 0]], [[1, 1], [0, 1]], [[1, 1], [0, 2]], [[1, 1], [1, 0]], [[1, 1], [1, 1]], [[1, 1], [1, 2]], [[1, 1], [2, 0]], [[1, 1], [2, 1]], [[1, 1], [2, 2]], [[1, 2], [0, 0]], [[1, 2], [0, 1]], [[1, 2], [0, 2]], [[1, 2], [1, 0]], [[1, 2], [1, 1]], [[1, 2], [1, 2]], [[1, 2], [2, 0]], [[1, 2], [2, 1]], [[1, 2], [2, 2]], [[2, 0], [0, 0]], [[2, 0], [0, 1]], [[2, 0], [0, 2]], [[2, 0], [1, 0]], [[2, 0], [1, 1]], [[2, 0], [1, 2]], [[2, 0], [2, 0]], [[2, 0], [2, 1]], [[2, 0], [2, 2]], [[2, 1], [0, 0]], [[2, 1], [0, 1]], [[2, 1], [0, 2]], [[2, 1], [1, 0]], [[2, 1], [1, 1]], [[2, 1], [1, 2]], [[2, 1], [2, 0]], [[2, 1], [2, 1]], [[2, 1], [2, 2]], [[2, 2], [0, 0]], [[2, 2], [0, 1]], [[2, 2], [0, 2]], [[2, 2], [1, 0]], [[2, 2], [1, 1]], [[2, 2], [1, 2]], [[2, 2], [2, 0]], [[2, 2], [2, 1]], [[2, 2], [2, 2]]]

If for example I want to modify only the second value in the second item from the second list:
print(mecs_states[1], '-', mecs_states[1][1], '-', mecs_states[1][1][1])

mecs_states[1][1][1] = 'A'

Is not only changing the desired value but also other lists values in the same index position.
out: [[[0, 0], [0, 0]], [[0, 0], [0, 'A']], [[0, 0], [0, 2]], [[0, 0], [1, 0]], [[0, 0], [1, 1]], [[0, 0], [1, 2]], [[0, 0], [2, 0]], [[0, 0], [2, 1]], [[0, 0], [2, 2]], [[0, 'A'], [0, 0]], [[0, 'A'], [0, 'A']], [[0, 'A'], [0, 2]], [[0, 'A'], [1, 0]], [[0, 'A'], [1, 1]], [[0, 'A'], [1, 2]], [[0, 'A'], [2, 0]], [[0, 'A'], [2, 1]], [[0, 'A'], [2, 2]], [[0, 2], [0, 0]], [[0, 2], [0, 'A']], [[0, 2], [0, 2]], [[0, 2], [1, 0]], [[0, 2], [1, 1]], [[0, 2], [1, 2]], [[0, 2], [2, 0]], [[0, 2], [2, 1]], [[0, 2], [2, 2]], [[1, 0], [0, 0]], [[1, 0], [0, 'A']], [[1, 0], [0, 2]], [[1, 0], [1, 0]], [[1, 0], [1, 1]], [[1, 0], [1, 2]], [[1, 0], [2, 0]], [[1, 0], [2, 1]], [[1, 0], [2, 2]], [[1, 1], [0, 0]], [[1, 1], [0, 'A']], [[1, 1], [0, 2]], [[1, 1], [1, 0]], [[1, 1], [1, 1]], [[1, 1], [1, 2]], [[1, 1], [2, 0]], [[1, 1], [2, 1]], [[1, 1], [2, 2]], [[1, 2], [0, 0]], [[1, 2], [0, 'A']], [[1, 2], [0, 2]], [[1, 2], [1, 0]], [[1, 2], [1, 1]], [[1, 2], [1, 2]], [[1, 2], [2, 0]], [[1, 2], [2, 1]], [[1, 2], [2, 2]], [[2, 0], [0, 0]], [[2, 0], [0, 'A']], [[2, 0], [0, 2]], [[2, 0], [1, 0]], [[2, 0], [1, 1]], [[2, 0], [1, 2]], [[2, 0], [2, 0]], [[2, 0], [2, 1]], [[2, 0], [2, 2]], [[2, 1], [0, 0]], [[2, 1], [0, 'A']], [[2, 1], [0, 2]], [[2, 1], [1, 0]], [[2, 1], [1, 1]], [[2, 1], [1, 2]], [[2, 1], [2, 0]], [[2, 1], [2, 1]], [[2, 1], [2, 2]], [[2, 2], [0, 0]], [[2, 2], [0, 'A']], [[2, 2], [0, 2]], [[2, 2], [1, 0]], [[2, 2], [1, 1]], [[2, 2], [1, 2]], [[2, 2], [2, 0]], [[2, 2], [2, 1]], [[2, 2], [2, 2]]]

What am I missing? I need that each list within a list be independent. I'm guessing that the reason is in the product of itertools but I don't totally understand why.
What would be the solution?

A: When you build the mecs_states list, you're not creating new internal lists, you're referencing the same lists you created in mec_capacity_states. As a smaller example:
import itertools

nums = [1, 2]

pairs = [list(p) for p in itertools.product(nums, repeat=2)]
# pairs = [[1, 1], [1, 2], [2, 1], [2, 2]]
a, b, c, d = pairs  # unpacking 'pairs' for the example later.

nested = [list(p) for p in itertools.product(pairs, repeat=2)]
# nested = [
#     [[1, 1], [1, 1]],
#     [[1, 1], [1, 2]],
#     [[1, 1], [2, 1]],
#     [[1, 1], [2, 2]],
# ...]

The thing about the inner elements of nested is that they are the same lists, by reference, as the elements of pairs:
nested[0][0] is a
# True
nested[0][1] is a
# True

nested[0][0][0] = 'x'
# a = ['x', 1]
# nested = [
#     [['x', 1], ['x', 1]],
#     [['x', 1], ['x', 2]],
#     [['x', 1], [2, 1]],
#     [['x', 1], [2, 2]],
# ...]

So when you modify nested[0][0][0], that is modifying the list that both nested[0][0] and a point to. Essentially, it's a slightly more complex version of the problem people run into when they do [[]] * 10, and all ten lists are the same list in memory.
You could solve this by waiting until the very end, after you have constructed your collections, to turn the tuples that itertools.product gives you into lists. However, once you are getting into nested collections more than a couple levels deep, it is time to start thinking about whether a class or some other data structure might be more appropriate to encapsulate the behavior you want.

A: Just "clone" the mecs_states list item. See copy.deepcopy in the code
import itertools
import copy

NUM_MECS = 2
MAX_MEC_CAPACITY = 2
VNF_TYPES = 2

# Mec capacity to hold a vnf
served_vnfs = list(range(MAX_MEC_CAPACITY + 1))  # 0 does not  count as capacity
# All possible mec states as far as holded vnfs
mec_capacity_states = [list(s) for s in itertools.product(served_vnfs, repeat=VNF_TYPES)]
# All possible states with defined number of mecs
mecs_states = [copy.deepcopy(list(p)) for p in itertools.product(mec_capacity_states, repeat=NUM_MECS)]
print(mecs_states)
print(mecs_states[1], '-', mecs_states[1][1], '-', mecs_states[1][1][1])
mecs_states[1][1][1] = 'A'
print(mecs_states)

output
[[[0, 0], [0, 0]], [[0, 0], [0, 1]], [[0, 0], [0, 2]], [[0, 0], [1, 0]], [[0, 0], [1, 1]], [[0, 0], [1, 2]], [[0, 0], [2, 0]], [[0, 0], [2, 1]], [[0, 0], [2, 2]], [[0, 1], [0, 0]], [[0, 1], [0, 1]], [[0, 1], [0, 2]], [[0, 1], [1, 0]], [[0, 1], [1, 1]], [[0, 1], [1, 2]], [[0, 1], [2, 0]], [[0, 1], [2, 1]], [[0, 1], [2, 2]], [[0, 2], [0, 0]], [[0, 2], [0, 1]], [[0, 2], [0, 2]], [[0, 2], [1, 0]], [[0, 2], [1, 1]], [[0, 2], [1, 2]], [[0, 2], [2, 0]], [[0, 2], [2, 1]], [[0, 2], [2, 2]], [[1, 0], [0, 0]], [[1, 0], [0, 1]], [[1, 0], [0, 2]], [[1, 0], [1, 0]], [[1, 0], [1, 1]], [[1, 0], [1, 2]], [[1, 0], [2, 0]], [[1, 0], [2, 1]], [[1, 0], [2, 2]], [[1, 1], [0, 0]], [[1, 1], [0, 1]], [[1, 1], [0, 2]], [[1, 1], [1, 0]], [[1, 1], [1, 1]], [[1, 1], [1, 2]], [[1, 1], [2, 0]], [[1, 1], [2, 1]], [[1, 1], [2, 2]], [[1, 2], [0, 0]], [[1, 2], [0, 1]], [[1, 2], [0, 2]], [[1, 2], [1, 0]], [[1, 2], [1, 1]], [[1, 2], [1, 2]], [[1, 2], [2, 0]], [[1, 2], [2, 1]], [[1, 2], [2, 2]], [[2, 0], [0, 0]], [[2, 0], [0, 1]], [[2, 0], [0, 2]], [[2, 0], [1, 0]], [[2, 0], [1, 1]], [[2, 0], [1, 2]], [[2, 0], [2, 0]], [[2, 0], [2, 1]], [[2, 0], [2, 2]], [[2, 1], [0, 0]], [[2, 1], [0, 1]], [[2, 1], [0, 2]], [[2, 1], [1, 0]], [[2, 1], [1, 1]], [[2, 1], [1, 2]], [[2, 1], [2, 0]], [[2, 1], [2, 1]], [[2, 1], [2, 2]], [[2, 2], [0, 0]], [[2, 2], [0, 1]], [[2, 2], [0, 2]], [[2, 2], [1, 0]], [[2, 2], [1, 1]], [[2, 2], [1, 2]], [[2, 2], [2, 0]], [[2, 2], [2, 1]], [[2, 2], [2, 2]]]
[[0, 0], [0, 1]] - [0, 1] - 1
[[[0, 0], [0, 0]], [[0, 0], [0, 'A']], [[0, 0], [0, 2]], [[0, 0], [1, 0]], [[0, 0], [1, 1]], [[0, 0], [1, 2]], [[0, 0], [2, 0]], [[0, 0], [2, 1]], [[0, 0], [2, 2]], [[0, 1], [0, 0]], [[0, 1], [0, 1]], [[0, 1], [0, 2]], [[0, 1], [1, 0]], [[0, 1], [1, 1]], [[0, 1], [1, 2]], [[0, 1], [2, 0]], [[0, 1], [2, 1]], [[0, 1], [2, 2]], [[0, 2], [0, 0]], [[0, 2], [0, 1]], [[0, 2], [0, 2]], [[0, 2], [1, 0]], [[0, 2], [1, 1]], [[0, 2], [1, 2]], [[0, 2], [2, 0]], [[0, 2], [2, 1]], [[0, 2], [2, 2]], [[1, 0], [0, 0]], [[1, 0], [0, 1]], [[1, 0], [0, 2]], [[1, 0], [1, 0]], [[1, 0], [1, 1]], [[1, 0], [1, 2]], [[1, 0], [2, 0]], [[1, 0], [2, 1]], [[1, 0], [2, 2]], [[1, 1], [0, 0]], [[1, 1], [0, 1]], [[1, 1], [0, 2]], [[1, 1], [1, 0]], [[1, 1], [1, 1]], [[1, 1], [1, 2]], [[1, 1], [2, 0]], [[1, 1], [2, 1]], [[1, 1], [2, 2]], [[1, 2], [0, 0]], [[1, 2], [0, 1]], [[1, 2], [0, 2]], [[1, 2], [1, 0]], [[1, 2], [1, 1]], [[1, 2], [1, 2]], [[1, 2], [2, 0]], [[1, 2], [2, 1]], [[1, 2], [2, 2]], [[2, 0], [0, 0]], [[2, 0], [0, 1]], [[2, 0], [0, 2]], [[2, 0], [1, 0]], [[2, 0], [1, 1]], [[2, 0], [1, 2]], [[2, 0], [2, 0]], [[2, 0], [2, 1]], [[2, 0], [2, 2]], [[2, 1], [0, 0]], [[2, 1], [0, 1]], [[2, 1], [0, 2]], [[2, 1], [1, 0]], [[2, 1], [1, 1]], [[2, 1], [1, 2]], [[2, 1], [2, 0]], [[2, 1], [2, 1]], [[2, 1], [2, 2]], [[2, 2], [0, 0]], [[2, 2], [0, 1]], [[2, 2], [0, 2]], [[2, 2], [1, 0]], [[2, 2], [1, 1]], [[2, 2], [1, 2]], [[2, 2], [2, 0]], [[2, 2], [2, 1]], [[2, 2], [2, 2]]]

A: Using json to serialize and deserialize.
import json

# Mec capacity to hold a vnf
served_vnfs = list(range(MAX_MEC_CAPACITY + 1))  # 0 does not  count as capacity
# All possible mec states as far as holded vnfs
mec_capacity_states = [list(s) for s in itertools.product(served_vnfs, repeat=VNF_TYPES)]
# All possible states with defined number of mecs
mecs_states = [copy.deepcopy(list(p)) for p in
itertools.product(mec_capacity_states, repeat=NUM_MECS)]
mecs_states = json.loads(json.dumps(list(mecs_states)))

print(mecs_states)
mecs_states[0][0][0] = 'A'
print(mecs_states)

output
[[[0, 0], [0, 0]], [[0, 0], [0, 1]], [[0, 0], [0, 2]], [[0, 0], [1, 0]], [[0, 0], [1, 1]], [[0, 0], [1, 2]], [[0, 0], [2, 0]], [[0, 0], [2, 1]], [[0, 0], [2, 2]], [[0, 1], [0, 0]], [[0, 1], [0, 1]], [[0, 1], [0, 2]], [[0, 1], [1, 0]], [[0, 1], [1, 1]], [[0, 1], [1, 2]], [[0, 1], [2, 0]], [[0, 1], [2, 1]], [[0, 1], [2, 2]], [[0, 2], [0, 0]], [[0, 2], [0, 1]], [[0, 2], [0, 2]], [[0, 2], [1, 0]], [[0, 2], [1, 1]], [[0, 2], [1, 2]], [[0, 2], [2, 0]], [[0, 2], [2, 1]], [[0, 2], [2, 2]], [[1, 0], [0, 0]], [[1, 0], [0, 1]], [[1, 0], [0, 2]], [[1, 0], [1, 0]], [[1, 0], [1, 1]], [[1, 0], [1, 2]], [[1, 0], [2, 0]], [[1, 0], [2, 1]], [[1, 0], [2, 2]], [[1, 1], [0, 0]], [[1, 1], [0, 1]], [[1, 1], [0, 2]], [[1, 1], [1, 0]], [[1, 1], [1, 1]], [[1, 1], [1, 2]], [[1, 1], [2, 0]], [[1, 1], [2, 1]], [[1, 1], [2, 2]], [[1, 2], [0, 0]], [[1, 2], [0, 1]], [[1, 2], [0, 2]], [[1, 2], [1, 0]], [[1, 2], [1, 1]], [[1, 2], [1, 2]], [[1, 2], [2, 0]], [[1, 2], [2, 1]], [[1, 2], [2, 2]], [[2, 0], [0, 0]], [[2, 0], [0, 1]], [[2, 0], [0, 2]], [[2, 0], [1, 0]], [[2, 0], [1, 1]], [[2, 0], [1, 2]], [[2, 0], [2, 0]], [[2, 0], [2, 1]], [[2, 0], [2, 2]], [[2, 1], [0, 0]], [[2, 1], [0, 1]], [[2, 1], [0, 2]], [[2, 1], [1, 0]], [[2, 1], [1, 1]], [[2, 1], [1, 2]], [[2, 1], [2, 0]], [[2, 1], [2, 1]], [[2, 1], [2, 2]], [[2, 2], [0, 0]], [[2, 2], [0, 1]], [[2, 2], [0, 2]], [[2, 2], [1, 0]], [[2, 2], [1, 1]], [[2, 2], [1, 2]], [[2, 2], [2, 0]], [[2, 2], [2, 1]], [[2, 2], [2, 2]]]

[[['A', 0], [0, 0]], [[0, 0], [0, 1]], [[0, 0], [0, 2]], [[0, 0], [1, 0]], [[0, 0], [1, 1]], [[0, 0], [1, 2]], [[0, 0], [2, 0]], [[0, 0], [2, 1]], [[0, 0], [2, 2]], [[0, 1], [0, 0]], [[0, 1], [0, 1]], [[0, 1], [0, 2]], [[0, 1], [1, 0]], [[0, 1], [1, 1]], [[0, 1], [1, 2]], [[0, 1], [2, 0]], [[0, 1], [2, 1]], [[0, 1], [2, 2]], [[0, 2], [0, 0]], [[0, 2], [0, 1]], [[0, 2], [0, 2]], [[0, 2], [1, 0]], [[0, 2], [1, 1]], [[0, 2], [1, 2]], [[0, 2], [2, 0]], [[0, 2], [2, 1]], [[0, 2], [2, 2]], [[1, 0], [0, 0]], [[1, 0], [0, 1]], [[1, 0], [0, 2]], [[1, 0], [1, 0]], [[1, 0], [1, 1]], [[1, 0], [1, 2]], [[1, 0], [2, 0]], [[1, 0], [2, 1]], [[1, 0], [2, 2]], [[1, 1], [0, 0]], [[1, 1], [0, 1]], [[1, 1], [0, 2]], [[1, 1], [1, 0]], [[1, 1], [1, 1]], [[1, 1], [1, 2]], [[1, 1], [2, 0]], [[1, 1], [2, 1]], [[1, 1], [2, 2]], [[1, 2], [0, 0]], [[1, 2], [0, 1]], [[1, 2], [0, 2]], [[1, 2], [1, 0]], [[1, 2], [1, 1]], [[1, 2], [1, 2]], [[1, 2], [2, 0]], [[1, 2], [2, 1]], [[1, 2], [2, 2]], [[2, 0], [0, 0]], [[2, 0], [0, 1]], [[2, 0], [0, 2]], [[2, 0], [1, 0]], [[2, 0], [1, 1]], [[2, 0], [1, 2]], [[2, 0], [2, 0]], [[2, 0], [2, 1]], [[2, 0], [2, 2]], [[2, 1], [0, 0]], [[2, 1], [0, 1]], [[2, 1], [0, 2]], [[2, 1], [1, 0]], [[2, 1], [1, 1]], [[2, 1], [1, 2]], [[2, 1], [2, 0]], [[2, 1], [2, 1]], [[2, 1], [2, 2]], [[2, 2], [0, 0]], [[2, 2], [0, 1]], [[2, 2], [0, 2]], [[2, 2], [1, 0]], [[2, 2], [1, 1]], [[2, 2], [1, 2]], [[2, 2], [2, 0]], [[2, 2], [2, 1]], [[2, 2], [2, 2]]]


text:
Q: How to check the status of ping in python I am working on python project where I need to ping an ip address to check if it online or offline. For this I have referred to most of the questions and answers online. Below is what I have tried first:
response = os.system("ping -c 1 " + ip_address)

if response == 0:
    print("Online")
else:
    print("Offline")

Above approach works fine but if we have Reply from <ip>. Destination host unreachable, then also it says Online when in actual it should be Offline.
Another solution I tried is checking the output of ping command:
cmd = "ping -c 1 " + ip_address
res = (subprocess.check_output(cmd, shell=True))
res = res.decode("utf-8")
if 'unreachable' in res or 'timed out' in res or '100% packet loss' in res:
    print("Offline")
else:
    print("Online")

In this approach I am checking if the response contains unreachable or timed out or 100% packet loss (only in case of linux), then I am saying that its Offline or else Online. This solution works well in all cases but sometime it throws error Command 'ping -c 1 <ip>' returned non-zero exit status 1.
I also need to make sure that code I am writing should work both on Windows and Ubuntu.
I am not able to understand on what is the cleanest and simplest way of checking the response of ping and deciding if Online or Offline. Can anyone please help me. Thanks

A: Check out the scapy python library.
The first example here would give you some insights on how to solve the ping problem.


text:
Q: How to run a command multiple times, using bash shell? Is there a way to run a command (e.g. ps aux|grep someprocess) for n times?
Something like:
run -n 10  'ps aux|grep someprocess'

I want to use it interactively.
Update: The reason I am asking this is, that I do work on a lot of machines and I don't want to import all my adaped scripts etc into every box to get the same functionality accross every machine.

A: POSIX way
http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_04_01
x=10
while [ $x -gt 0 ]; do
    command
    x=$(($x-1))
done

which could of course be made into a one liner:
x=10; while [ $x -gt 0 ]; do command; x=$(($x-1)); done

and seems to be the most portable way, and thus less likely to make you install programs.
The following are less portable:

*

*brace expansion {1..10}: bash specific, and would generate a huge line if the argument is large

*seq: GNU

*yes: GNU

And if you get tired of portability, consider GNU parallel:
sudo apt-get install parallel
seq 100 | parallel echo {}

which runs commands in parallel and has many cool options.
See also: https://stackoverflow.com/questions/169511/how-do-i-iterate-over-a-range-of-numbers-defined-by-variables-in-bash

A: ps aux | grep someprocess looks like you want to watch changes of a program for a fixed time. Eduardo gave an answer that answer your question exactly but there is an alternative: watch:
watch 'ps aux | grep someprocess'

Note that I've put the command in single quotes to avoid the shell from interpreting the command as "run watch ps aux" and pipe the result through grep someprocess. Another way to do the previous command would be:
watch ps aux \| grep someprocess

By default, watch refreshes every two seconds, that can be changed using the -n option. For instance, if want to have an interval of 1 second:
watch -n 1 'ps aux | grep someprocess'

A: I don't think a command or shell builtin for this exists, as it's a trivial subset of what the Bourne shell for loop is designed for and implementing a command like this yourself is therefore quite simple.
Per JimB's suggestion, use the Bash builtin for generating sequences:
for i in {1..10}; do command; done

For very old versions of bash, you can use the seq command:
for i in `seq 10`; do command; done

This iterates ten times executing command each time - it can be a pipe or a series of commands separated by ; or &&. You can use the $i variable to know which iteration you're in.
If you consider this one-liner a script and so for some unspecified (but perhaps valid) reason undesireable you can implement it as a command, perhaps something like this on your .bashrc (untested):
#function run
run() {
    number=$1
    shift
    for i in `seq $number`; do
      $@
    done
}

Usage:
run 10 command

Example:
run 5 echo 'Hello World!'

A: A fish shell implementation of @eduardo-ivanec's run function above
function run
  set number $argv[1]
  for i in (seq $number)
    eval $argv[2..-1]
  end
end

A: Just for fun
pgrep ssh
!!;!!;!!;!!;!!;!!

NOTE: You must run the command pgrep ssh first, separately, and then enter the !!;!!;!!;!!;!!;!! string. Otherwise, the !! are replaced with the command that was previously executed.
; is a command separator and !! replay last command in bash.
So this runs pgrep ssh and then replays it 6 times.

A: similar to previous replies, but does not require the for loop:
seq 10 | xargs -I -- echo "hello"

pipe output of seq to xargs with no arguments or options

A: To run ps aux multiple times searching for a different known string each time:
for str in {str1,str2,...}; do ps aux | grep $str | grep -v " grep "; done

The grep -v " grep " part will remove grep itself from the result, which is a bad idea if one of your search strings is grep.

A: Try this:
yes ls | head -n5 | bash

This requires the command to be executed in a sub-shell, a slight performance penalty. YMMV. Basically, you get the "yes" command to repeat the string "ls" N times; while "head -n5" terminated the loop at 5 repeats. The final pipe sends the command to the shell of your choice.
Incidentally csh-like shells have a built-in repeat command. You could use that to execute your command in a bash sub-shell!

A: On macOS you can use the repeat command.
repeat 10 ps aux | grep someprocess

A: That would be 'watch' - should be part of almost every unix system using procps
You can see fs changes or otherwise interesting movement in a system. For example,
watch "df -hP | grep /tmp"

Just put your commands as an argument (see man watch)


text:
Q: Charge 19.5V laptop with 19V battery pack I have a Dell Latitude E5450.
On the original power supply it says
output: 19.5V - 3.34A
Can I use a battery pack that provides 19V - 3A?
Hopefully somebody can explain this to me and what I need to be careful for.
Is it OK to be below the numbers? Is it OK to be over?
What is the range?

A: In relation to the voltage, you need to match the existing battery, like for like. In relation to the current (amps), then as long as the battery matches or exceeds the existing battery's rated current it will be OK.
As the power supply charges the battery through a regulation circuit, there is no direct relation between charger voltage and battery voltage.


text:
Q: Problem on web.xml when deploying GWT into JBoss I have developed a simple application in GWT. After that, I generate war file and deploy it into JBoss. However, when I do this, I get an error message like:

The content of element type "web-app"
  must match
  "(icon?,display-name?,description?,distributable?,context-param*,filter*,filter-
  mapping*,listener*,servlet*,servlet-mapping*,session-config?,mime-mapping*,welcome-file-list?,error-page*,taglib*,resource-env-ref*,resource-
  ref*,security-constraint*,login-config?,security-role*,env-entry*,ejb-ref*,ejb-local-ref*)".

On the other hand, my web.xml is the following:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/resources/spring.xml</param-value>
</context-param>

<!-- Servlets -->
<servlet>
  <servlet-name>greetServlet</servlet-name>
   <servlet-class>main.java.com.gwt.app.server.GreetingServiceImpl</servlet-class>
 </servlet>

<servlet-mapping>
    <servlet-name>greetServlet</servlet-name>
     <url-pattern>/zb_app/greet</url-pattern>
</servlet-mapping>

 <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-    class>
</listener>

 <!-- Default page to serve -->
 <welcome-file-list>
    <welcome-file>ZB_app.html</welcome-file>
 </welcome-file-list>

</web-app>

It is to say, the web-app tag contains some mandatory tags. I do not what is the problem, could someone help me with the problem?
Thank you in advance!
Regards!

A: Try to put the listener declaration before the servlets, the order of the elements shouldn't be a problem but I've seen this in some container (don't remeber if it was JBoss)

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Servlets -->
<servlet>
<servlet-name>greetServlet</servlet-name>
<servlet-class>main.java.com.gwt.app.server.GreetingServiceImpl</servlet-class> </servlet>

<servlet-mapping>
<servlet-name>greetServlet</servlet-name>
<url-pattern>/zb_app/greet</url-pattern>
</servlet-mapping>

A: The sequence should be context-param - listener - servlet and here it is
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/resources/spring.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>greetServlet</servlet-name>
        <servlet-class>main.java.com.gwt.app.server.GreetingServiceImpl</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>greetServlet</servlet-name>
        <url-pattern>/zb_app/greet</url-pattern>
    </servlet-mapping>
   <welcome-file-list>
        <welcome-file>ZB_app.html</welcome-file>
    </welcome-file-list>

</web-app>


text:
Q: BeanWrapperFieldSetMapper alternative, to avoid setTargetType/setPrototypeBeanName I need a way to get rid of fieldSetMapper.setTargetType because I do not want to add a POJO every time I have a new file to read. Is it possible?

A: Springbatch has a few FieldSetMapper implementations available out-of-the-box : Documentation (FieldSetMapper)
You can for example use a PassThroughFieldSetMapper to get a FieldSet object in your processor. You can do the same with an ArrayFieldSetMapper to get an array object.
But in your case, I think you need to implement your own FieldSetMapper. It could for example have a names property (with a setter) and a targetClass property (with a setter). Using Reflect, you could then cast the object to your desired class and call setters according to the names passed as arguments.
Here's what a FieldSetMapper looks like :
@Override
public Report mapFieldSet(FieldSet fieldSet) throws BindException {

    T object;
    object.setField(fieldSet.readString(0));
    return object;
}

Here's what Reflect looks like :
    Method method = object.getClass().getMethod(methodName);
    method.invoke(object);


text:
Q: Face-API: There is no persisted faces of person in group i'm using ms github project :Facial-Recognition-Door
Facial-Recognition-Door
private async Task<bool> TrainingWhitelistAsync()
    {
        bool isSuccess = true;

        // Train whitelist after add all person
        Debug.WriteLine("Start training whitelist: " + WhitelistId);
        await _faceApiClient.TrainPersonGroupAsync(WhitelistId);

        TrainingStatus status;

        while(true)
        {
            status = await _faceApiClient.GetPersonGroupTrainingStatusAsync(WhitelistId);

            // wait for training to complete
            if (status.Status != Status.Running)
            {
                Debug.WriteLine("GetPersonGroupTrainingStatusAsync stopped running:" + status.Message);
                if (status.Status == Status.Failed)
                {
                    isSuccess = false;
                }
                break;
            }

            await Task.Delay(1000);
            Debug.WriteLine("GetPersonGroupTrainingStatusAsync still running:" + status.Message);
        }

        Debug.WriteLine("GetPersonGroupTrainingStatusAsync end result: " + isSuccess);
        return isSuccess;
    }

every time when i run to
status = await _faceApiClient.GetPersonGroupTrainingStatusAsync(WhitelistId);
it retruns me failed, and say GetPersonGroupTrainingStatusAsync stopped running:There is no persisted faces of person in group f473519e-452b-4a65-8e11-85ccdb02063e.
Is anything wrong or just i'm using a free key?
my key screenshot
can any one help me?


text:
Q: How to refresh page without closing a socket? Is there a way to reload/refresh the contents of an HTML page without closing the open socket to the server? All the options mentioned here appear to be closing the socket.
I would like to do such a thing whenever a node server is sending a JSON message with the new values for a specific part of the page. So, the client has the new data, but apparently with jQuery I can not update the webpage. (No, the jQuery that I have already works because the first time the client is connected, the same jQuery is used to load the page. I can see the webpage fine; however, when I request to view the source code of the HTML page I can not see anywhere what I am actually seeing on the screen.)
Any ideas? Thanks in advance.

A: The only way to avoid closing an open connection on a page is to dynamically change the page's content. As you stated, you can just use jQuery, but do note that the rendered output is different from the page's source, which is why you can't see the DOM changes you've made with JavaScript. To view the rendered source, use inspect element (may vary by browser).


text:
Q: Upscaling Image on Hover I want to upscale image on hover, but the problem is I can make it overlapse its own container with overflow: hidden only by making img absolute positioned, wherefore all article content 'thinks' that there is no image in container.

article {
  background: #e8e8e8;
  color: #484848;
  overflow: hidden;
  padding: 0.5rem;
  margin: 2rem auto 0 auto;
  width: 60vw;
}

section {
  float: left;
  margin-right: 0.5rem;
}

p {
  margin: 0;
}

img {
  transition: 0.2s linear;
  object-fit: cover;
  width: 128px;
  height: 128px;
}

img:hover {
  position: absolute;
  transform: scale( 1.5 );
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

How to freeze all article content after img becomes absolute positioned?
Please, no JS solutions.

A: float:left on p done the work!.

article {
  background: #e8e8e8;
  color: #484848;
  overflow: hidden;
  padding: 0.5rem;
  margin: 2rem auto 0 auto;
  width: 60vw;
}

section {
  float: left;
  margin-right: 0.5rem;
}

p {
  margin: 0;
  float:left;
}

img {
  transition: 0.2s linear;
  object-fit: cover;
  width: 128px;
  height: 128px;
}

img:hover {
  position: absolute;
  transform: scale( 1.5 );
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

As you want p to don't interact with images then before hover text will also don't interact with image and don't change it's own position.

A: The trick is to put the element you want to animate into a container, and then trigger the animation when you hover the container.

article {
  background: #e8e8e8;
  color: #484848;
  padding: 0.5rem;
  margin: 2rem auto 0 auto;
  width: 60vw;
}

section {
  float: left;
  margin-right: 0.5rem;
}

p {
  margin: 0;
}

img {
  transition: 0.2s linear;
  object-fit: cover;
  width: 128px;
  height: 128px;
}

.image-container {
  display: inline-block;
}

.image-container:hover > img {
  transform: scale( 1.5 );
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


text:
Q: Why does this REG QUERY command work on Win7, but not WinXP Comamnd is: reg query \\cois316\hklm\Software\Microsoft\.NETFramework /v EnableIEHosting
and on Windows 7 this works flawlessly, but on XP I get an error that says either "The network path was not found". The hostname is valid on the network and I can ping from my machine to the hostname.
Script this is being used in:
@echo off
cls
:start
echo Main Menu
echo ---------
echo 1) Get Reg Key Status
echo 2) Set Reg Key
echo 3) Exit
echo.

set /p MenuChoice=Choose an option:

IF %MenuChoice% == 1 (
    set /p Hostname=Enter Hostname:
    REG QUERY \\%Hostname%\HKLM\SOFTWARE\Microsoft\.NETFramework /v EnableIEHosting
    goto start
)

IF %MenuChoice% == 2 (
    set /p Hostname=Enter Hostname:
    REG ADD \\%Hostname%\HKLM\SOFTWARE\Microsoft\.NETFramework /v EnableIEHosting /t REG_DWORD /d

0x00000001
    goto start
)

IF %MenuChoice% == 3 (
    goto end
)

IF %MenuChoice% == 4 (
    set /p Hostname=Enter Hostname:
    echo \\%Hostname%\HKLM\SOFTWARE\Microsoft\.NETFramework /v EnableIEHosting
    pause
)

cls

goto start

:END

A: Okay. the problem is within the following block:
IF %MenuChoice% == 1 (
    set /p Hostname=Enter Hostname:
    REG QUERY \\%Hostname%\HKLM\SOFTWARE\Microsoft\.NETFramework /v EnableIEHosting
    goto start
)

Why? As soon the commmand interpreter hits a () block, he automatically resolves all variables contained in this block. That means that the statement set /p Hostname=Enter Hostname: will work, but the Hostname variable was already resolved. To prove it, try to add an Echo. e.g. ECHO Hostname Entered is: %Hostname%
As soon you queried something and you get back to the :start label, and you query again another server, he's using the previously entered hostname.
To solve this issue, you have to enclose your variables with an exclamation mark. %Hostname% -> !Hostname! .
This is only working if you execute the following command initially in your batch file:
SETLOCAL ENABLEDELAYEDEXPANSION

It would work this way:
IF %MenuChoice% == 1 (
    set /p Hostname=Enter Hostname:
    REG QUERY \\!Hostname!\HKLM\SOFTWARE\Microsoft\.NETFramework /v EnableIEHosting
    goto start
)

You have to change this in all other blocks too of course.
I think this would fix your problem on XP.


text:
Q: Concat DataFrame under specific condition For the following dataframes which are stored in a list of lists, I want to concat them if there is something to:
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
                     'B': ['B0', 'B1', 'B2', 'B3'],
                     'C': ['C0', 'C1', 'C2', 'C3'],
                     'D': ['D0', 'D1', 'D2', 'D3']},
                    index=[0, 1, 2, 3])

fr_list = [[] for x in range(2)]
fr_list[0].append(df1)
fr_list[0].append(df1)
fr_list[1].append(df1)

for x in range(2):
   df = pd.concat(fr_list[x] if len(fr_list[x]) > 1)  # <-- here is the problem

A: The syntax you want is probably:
...
df = pd.concat((fr for fr in fr_list[x] if len(fr) > 1))


text:
Q: SilverStripe - limiting the number of many relations a dataobject can have If I have a $has_many relationship that I want to manage with a GridField in the cms, how would I go about putting a limit on the number of how many relations one object can have? Is this possible?
Can I do this in the model or would it have to be a check I add into the GridField I'm using to add and remove relations?
I'm looking at implementing GridField_SaveHandler to make a custom GridFieldComponent but not sure how I can use this to abort the save if i detect something is wrong.

A: the following 2 solutions are not the cleanest way to solve this, but the most pragmatic and easiest to implement.
basically, what I suggest to do, is just count the objects and remove the ability to add new records once the count is above a certain number.
if you want to limit the number of records on a single relation/grid (lets say max 5 players per team):
class Player extends Dataobject {
    private static $db = array('Title' => 'Varchar');
    private static $has_one = array('TeamPage' => 'TeamPage');
}
class TeamPage extends Page {
    private static $has_one = array('Players' => 'Player');
    public function getCMSFields() {
        $fields = parent::getCMSFields();
        $config = GridFieldConfig_RecordEditor::create();
        if ($this->Players()->count > 5) {
            // remove the buttons if we don't want to allow more records to be added/created
            $config->removeComponentsByType('GridFieldAddNewButton');
            $config->removeComponentsByType('GridFieldAddExistingAutocompleter');
        }
        $grid = GridField::create('Players', 'Players on this Team', $this->Players(), $config);
        $fields->addFieldToTab('Root.Main', $grid);
        return $fields;
    }
}

if you want to limit the total number of records globally (if we limit this way to 5, this means if 1 Team already has 3 Players, then the 2nd team can only have 2):
class Player extends Dataobject {
    private static $db = array('Title' => 'Varchar');
    private static $has_one = array('TeamPage' => 'TeamPage');
    public function canCreate($member = null) {
        if (Player::get()->count() > 5) {
           return false;
        }
        return parent::canCreate($member);
    }
}
class TeamPage extends Page {
    private static $has_one = array('Players' => 'Player');
    public function getCMSFields() {
        $fields = parent::getCMSFields();
        $config = GridFieldConfig_RecordEditor::create();
        $grid = GridField::create('Players', 'Players on this Team', $this->Players(), $config);
        $fields->addFieldToTab('Root.Main', $grid);
        return $fields;
    }
}

A: I have wrote a quick jQuery plugin to limit the number of items a GridField can have: -
Download the plugin here: - gridfieldlimit.js
https://letscrate.com/f/monkeyben/silverstripe/gridfieldlimit.js
Set up the plugin in the getCMSFields function: -
// Pass GridField configs, each one containing field name and item limit
$vars = array(
    "GridFieldLimits" => "[['GRIDFIELD_NAME_1', 3], ['GRIDFIELD_NAME_2', 6]]",
);

// Load the jquery gridfield plugin
Requirements::javascriptTemplate("themes/YOUR_THEME_NAME/javascript/gridfieldlimit.js", $vars);

A: works for me: make the canCreate method of the DataObject that's managed by your GridField check for existing objects.
of course, this doesn't allow you to implement a customg GridFieldComponent, as you need to modify the DataObject code.


text:
Q: Jquery Waypoints not detecting viewport I'm using jquery waypoints to add/remove classes. Right now, I'm loading documents into a wrapper div. Code goes like this:
$(function () {
         $('.content-section').load('about.html');
     });

However, when it loads the html document, all the classes are added to their corresponding elements, even if they're not in viewport. The only way to get it working properly is if I adjust the screen size and back, then it starts to detect elements on their viewport properly.
Anyone know why this is occurring?
EDIT: I should also mention that I tested my website without loading external html docs. For example, I dropped all the elements from the 'about.html' into the main wrapper div, which is in another html doc of course, and waypoints detected the viewport just fine.

A: Your code is set to run on dom ready with $(function(){.
If you only want this to run on window resize, then wrap your code with that event like so:
$(function(){

    $( window ).resize(function() {

        $('.content-section').load('about.html');

    });

});
You can read more about the jQuery resize event here: https://api.jquery.com/resize/


text:
Q: Integrability of a product of two integrable functions under the product measure Here is the question:
Let $(X, \mathcal{S}, \mu)$ and $(Y, \mathcal{T}, \lambda)$ be $\sigma$-finite measure spaces. Suppose that $g: X \rightarrow \mathbb{R}$ is a $\mu-$integrable function and that $h: Y \rightarrow \mathbb{R}$ is a $\lambda-$integrable function. Define $f: X \times Y \rightarrow \mathbb{R}$ by $f(x,y) = g(x)h(y).$ Prove that $f$ is $\mu \times \lambda$ integrable and that $$\int_{X\times Y} f d(\mu \times \lambda) = (\int_{X}g d\mu) (\int_{Y} hd\lambda)$$
I found this question here Proving a formula for the product of two measurable functions but I am wondering if someone can give me more details about the first and last step?

A: First of all, we may assume that $f$ and $g$ are non-negative.
This is due to the fact that we can write $f$ and $g$ as $f=f_+-f_-$ and $g=g_+-g_-$, where $f_\pm=\max\{\pm f,0\}$ and $g_\pm=\max\{\pm g,0\}$. So if $f$ and $g$ are integrable, so are $f_\pm$ and $g_\pm$ and vice versa.
Then $fg=f_+g_++f_-g_--f_+g_--f_-g_+$, where
$|fg|\ge |f_+g_+|, |f_-g_-|, |f_+g_-|, |f_-g_+|$.
If $f,g\ge 0$, then there exist increasing sequences of simple measurable functions $f_n\to f$ and $g_n\to g$, with Monotone Convergence Theorem (MCT) providing that $\int_X f_n\,d\mu\to \int_X f\,d\mu$ and $\int_Y g_n\,d\lambda\to \int_Y g\,d\lambda$.
It is now straight-forward that
$$
\Big(\int_X f_n\,d\mu\Big)\cdot\Big(\int_Y g_n\,d\lambda\Big)=\int_{X\times Y}f_ng_n\,d(\mu\times\lambda)
$$
and, again applying MCT we get that
$$
\Big(\int_X f_n\,d\mu\Big)\cdot\Big(\int_Y g_n\,d\lambda\Big)\to
\Big(\int_X f\,d\mu\Big)\cdot\Big(\int_Y g\,d\lambda\Big)
$$
while
$$
\int_{X\times Y}f_ng_n\,d(\mu\times\lambda)\to
\int_{X\times Y}fg\,d(\mu\times\lambda)
$$


text:
Q: System.Data.SqlServerCe.Entity.dll using nuget : add ef4.1 and sqlce4 but i got this when project uploded on my hosting space
Exception Details: System.Data.MetadataException: Schema specified is not valid. Errors:
NModel.ssdl(2,86) : error 0004: Could not load System.Data.SqlServerCe.Entity.dll. Reinstall SQL Server Compact.

A: Everything work fine if you add references with NuGet.
The required packages are:

*

*EntityFramework.SqlServerCompact
(https://nuget.org/packages/EntityFramework.SqlServerCompact/4.3.4)

*Microsoft.SqlServer.Compact
(https://nuget.org/packages/Microsoft.SqlServer.Compact)

A: This same thing is happening to me. It happening over time somehow. When I first deploy to production server it works ok. But then the SDF file becomes corrupt or something and stops working. As a temp fix I just replace the sdf file. I will post more when I figure out the real issue.


text:
Q: Can Dataframe joins in Spark preserve order? I'm currently trying to join two DataFrames together but retain the same order in one of the Dataframes.
From Which operations preserve RDD order?, it seems that (correct me if this is inaccurate because I'm new to Spark) joins do not preserve order because rows are joined / "arrive" at the final dataframe not in a specified order due to the data being in different partitions.
How could one perform a join of two DataFrames while preserving the order of one table?
E.g.,
+------------+---------+
 |    col1    |  col2   |
 +------------+---------+
 | 0          | a       |
 | 1          | b       |
 +------------+---------+
joined with
+------------+---------+
 |    col2    |  col3   |
 +------------+---------+
 | b          | x       |
 | a          | y       |
 +------------+---------+
on col2 should give
+------------+--------------------+
 |    col1    |  col2   |    col 3 |
 +------------+---------+----------+
 | 0          | a       |     y    |
 | 1          | b       |     x    |
 +------------+---------+----------+
I've heard some things about using coalesce or repartition, but I'm not sure. Any suggestions/methods/insights are appreciated.
Edit: would this be analogous to having one reducer in MapReduce? If so, how would that look like in Spark?

A: It can't. You can add monotonically_increasing_id and reorder data after join.


text:
Q: How to choose an option in some windows with keyboard? For example, when I close an app with some changes without saving ir before. A window asks me if I want to save or not.

In Windows I can choose between these options with Tab but in Mac does not work.
EDIT: To save the document It's obviously that I can press Enter but I want to know how can I choose the other options.
PS: sorry for my english, I'm from Argentina
EDIT2: I found the answer here but I don't know how to mark as 'Answered': How to set it up to switch between tabs using TAB key on Macbook?


text:
Q: Find common members that are in two lists of dictionaries This may be a duplicate but the closest I could find was Comparing 2 lists consisting of dictionaries with unique keys in python which did not work for me.
So I have two lists of dictionaries.
y = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
y = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]

How do I compare these two lists so my compare results in the intersection of the two lists. I can't convert it to set since it says unhashable type (dict)

A: Your question and it's title seem at odds with each other.
The intersection of the 2 lists would be the common elements of both list. The question title requests the elements that are not in both lists. Which is it that you want?
For the intersection, it is not very efficient (being O(n^2) in time), but this list comprehension will do it:
>>> a = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
>>> b = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]
>>> [d for d in a if d in b]
[{'a': 1, 'b': 2, 'c': 3}]

A: y1 = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
y2 = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]
print [x for x in y1 if x in y2] # prints [{'a': 1, 'c': 3, 'b': 2}]

A: A dict (or list) is not hashable, however, a tuple is. You can convert the list of dicts to a set of tuples. Perform the intersection and then convert back
the code to convert to a set-of-tuples
y_tupleset = set(tuple(sorted(d.items())) for d in y)

the code to convert back the intersected set-of-tuples to a list-of-dicts
y_dictlist = [dict(it) for it in list(y_tupleset)]

Thus, the full code would be:
y0 = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
y1 = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]

y0_tupleset = set(tuple(sorted(d.items())) for d in y0)
y1_tupleset = set(tuple(sorted(d.items())) for d in y1)
y_inter = y0_tupleset.intersection(y1_tupleset)
y_inter_dictlist = [dict(it) for it in list(y_inter)]

print(y_inter_dictlist)
# prints the following line
[{'a': 1, 'c': 3, 'b': 2}]

edit: d.items() is valid on python3, for python2, it should be replaced with d.iteritems()

A: Pick your poison:
y1 = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
y2 = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]
y3 = [{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 2, 'c': 6}]

# Returns a list of keys that are in both dictionaries
def intersect_keys(d1, d2):
    return [k for k in d1 if k in d2]

# Returns a list of values that are in both dictionaries
def intersect_vals(d1, d2):
    return [v for v in d1.itervalues() if v in d2.itervalues()]

# Returns a list of (key,value) pairs that are in both dictionaries
def intersect_pairs(d1, d2):
    return [(k,v) for (k,v) in d1.iteritems() if k in d2 and d2[k] == v]

print(intersect_keys(*y1))      # ['a', 'c', 'b']
print(intersect_vals(*y1))      # [3]
print(intersect_pairs(*y1))     # []

print(intersect_keys(*y2))      # ['a', 'c', 'b']
print(intersect_vals(*y2))      # []
print(intersect_pairs(*y2))     # []

print(intersect_keys(*y3))      # ['a', 'c', 'b']
print(intersect_vals(*y3))      # [2]
print(intersect_pairs(*y3))     # [('b', 2)]

Note: the examples compare the two elements of the y* list, which was how I interpreted your question.  You could of course use something like:
print(intersect_pairs(y1[0], y2[0]))

To compute the intersection the first dictionary in the y1 and y2 lists.


text:
Q: JSZip in a Loop? Is it possible to create real zip folders and files with JSZip in a loop, one per element?  If so, how?
Something like this:
var JSZip = require("jszip");
const saveAs = require('file-saver');
var fs = require("fs");

for(i = 0; i > 5; i++){
    var zip = new JSZip();
    zip.folder(i).file(i+".txt", i);

    zip
    .generateNodeStream({type:'nodebuffer',streamFiles:true})
    .pipe(fs.createWriteStream('Zipped Projects.zip'))
    .on('finish', function () {
        console.log("Zipped Projects.zip written.");
    })
}

Outside of the loop, an actual zip folder is created with the expected contents in the current directory.  Inside the loop, nothing happens, not even the log.

A: If I understand your question correctly, then this is issue is caused by new zip objects being created per loop iteration.
Perhaps you could consider making the following adjustments to resolve this problem:
var JSZip = require("jszip");
const saveAs = require('file-saver');
var fs = require("fs");

// Create the single zip object that will be populated
// during the for loop
var zip = new JSZip();

// Populate the zip object with text files per iteration.
// Make sure you update the loop logic to use "i < 5"
for(var i = 0; i < 5; i++){
    zip.folder(i).file(i+".txt", i);
}

// Now that the zip object has been populated, write it to
// disk
zip
.generateNodeStream({type:'nodebuffer',streamFiles:true})
.pipe(fs.createWriteStream('Zipped Projects.zip'))
.on('finish', function () {
    console.log("Zipped Projects.zip written.");
})

Hope this helps!

A: var JSZip = require("jszip");
const saveAs = require('file-saver');
var fs = require("fs");

var asanaProjects = require("C:/Users/GabrielRivera/Documents/asana/New Projects JSON.json");

async function createProjectZips() {

    var zip = new JSZip();

    asanaProjects.map((project, index, array) => {

        zip.file(project.name+' - '+index+'.json', JSON.stringify(project));
    })

    zip
        .generateNodeStream({type:'nodebuffer',streamFiles:true})
        .pipe(fs.createWriteStream('Zipped Projects.zip'))
        .on('finish', function () {
        //console.log("Zipped Projects.zip written.");
        })
}

createProjectZips()
.then(() => {
})
.catch(err=>console.log(err))


text:
Q: Attention Americans: Do you use the SILENT H in the beginning? English is my mother tongue and we often follow the British pronunciations.
However, something caught my attention recently. In my Oxford dictionary, I noticed that so many words that begin with 'wh' have a leading 'h' as part of the phonetics. Here are some of them:

what
when
wheeze
wheel
wheat
whatever
whip

and the list goes on...
I have heard many US accents but never encountered this. Perhaps I never noticed it.
Thus my question: Do Americans really use these words with a leading h or at least are they supposed to?
Thanks!
EDIT: I am not using the net as my source here. It's a printed book. So for those who are unsure, here it is:

BTW, the exact title of the dictionary is:
Oxford WordPower
English-Arabic dictionary
ISBN: 0-19-431485-5
NEWEST EDIT: Please do not consider this a duplicate of Hwat, hwere, and hwy?
That discusses the origins of words and various 'accents'. Yes, the examples are related, but my question is different and simple. I'm more keen on knowing if Americans (today) use the leading h pronunciation (at large)?
Ever since I started my study of languages (my mother tongue included), I've tried to stick to a standard pronunciation from the dictionary. Thus in a way I look at the dictionary's pronunciation as the right way to pronounce words, regardless of what people really do. So now after seeing the leading h pronunciation related to Americans, I'm curious to know if they really do so.
And after the kind of responses and links I've seen on this subject today, I don't even think that an average non-academic American really knows this exists. Perhaps I'm wrong.

A: Some do!  Some don't.  I said these words to myself just now to see what I do, and wouldn't you know it, I do put a teensy tiny "h" in front of these.  Kind of like "hWat?"  It's barely discernable, even to me.
Amazing to learn after all these years that I pronounce some words in a way I would never have imagined.  Wow!  Or is that hWow?
I'm originally from Southern California, and probably had an original "O.C" accent, but since age 15 I've been all over: Toronto, Canada; Cheltenham, England; Germany for 3 years and Yes I speak it fairly fluently; Washington state, USA, for the past 30 years.  My accent is probably so muddled up by now there's no way to tell what I sound like.

A: First of all, I wish to remind that the letter "H" is more acceptably pronounced "age" or "eij" not "heige"/"heij".
There, the pronunciation of "H" itself does not involve the sound of "H. I've been to parts of Asia and US where they pronounced it "heige" - somewhat coincident in places where they also pronounce "pronounciation" rather than "pronunciation".
The way I've been brought up, which may not agree with others

*

*Elision of h to before w to emphasize the presence of an "h". Therefore we pronounce "hwen", "hwat",etc.

*In the US, people pronounce "herb" as "erb", "homage" as "omage"/"ormarj". I think the Queen of England would not coincide with such pronunciation. Neither does the Oxford dict. I am more comfortable pronouncing them with the non-silent "H". I think US pronunciation standardization efforts are simply too zealous.

*Regardless of dialect, the "H" mostly becomes silent when paired with a prior word that ends with a consonant:
green herb = green'erb

*However, if the prior word ends with "T", I would encourage people to pronounce "herb" rather than "erb". e.g, "fragrant herb" rather than "fragrant 'erb". Could be misheard as "fragrant turd".

*Regardless of dialect, the elided "H" in "when", "where", etc, is not silent, even when paired with a prior word ending with a consonant. e.g.

*

*he says hwen

*tell him hwere