text:
Q: When should we use NodeJS and when should we use MongoDB? As a new developer, I am always confused about using NodeJS and MongoDB. So I hope I will get an actual answer. Thanks...

A: MongoDB and NodeJS are two different technologies. MonogDB is a database system which gives you a chance to efficiently store documents in a database and to perform operations like data updates, or to search documents by some criterias.
NodeJS's responsibilty is especially to execute your application.

A: Nodejs is a Javascript engine that you can write any application you want with (by programming in the Javascript language).  It runs your Javascript code.  Most commonly, it is used to build servers that can respond to web requests, though it can be used for lots of other types of code too.
MongoDB is a database engine.  Code within some application or server uses MongoDB to save, query or update data in a database.  There are many web servers built with nodejs that will then use MongoDB for storing data.
MongoDB offers an API library that runs within a Nodejs application to give you programmatic access to MongoDB so you can create databases and then add, query, update or delete data from the MongoDB database.  MongoDB also has API libraries for other programming environments such as Python, Java, etc...
These two technologies are for different parts of a typical web server system.  You don't substitute one for the other.  Instead, you can use them together.

When should we use Nodejs?

Any project needs a programming environment and a runtime library that offers you basic programming tools/support and can compile and/or interpret your code.  Nodejs is such as tool for the Javascript programming language.  There are other similar tools for other languages such as Python, Java, PHP, C#, C++, Go, etc...
So, if you want to write some kind of stand-alone program or server in Javascript, then you can use nodejs for it.

When should we use MongoDB?

If your application needs the ability to persistently store data in a way that you can efficiently query or update it later, then you would typically use some form of database.  There are dozens of popular databases.  MongoDB is one such database.  MariaDB, MySql, CouchDB, DynamoDB (on AWS), Postgres are examples of other databases.  Different databases have different strengths (things they are best at) and different ways of using them so it's a whole different question to choose the right/best database for what you're doing.

A: Here is a Blog link that will tell you when you should use NodeJS.
Here is another link to understand when you should use mongoDB.

A: Well, NodeJS and MongoDB are two different process. Here I tried to explain as simpler as possible:

NodeJS

Shortly we can say, NodeJS is a JavaScript runtime environment. It's actually helps JavaScript to run outside of server. It's used in server side development.

MongoDB

But, MongoDB is NoSQL database which is document oriented. It represents data as of JSON documents. It's used for store data.

Summary

The summary is MongoDB is a database where we can store data and NodeJS helps us to to connect our client site to database by it's server site.

Example:

Suppose you are building a website and you need a database to store the data or information so here you can use MongoDB but to be connected with MongoDB you need a connector, so here you can use NodeJS which will help your website to run outside of server.

A: Nodejs: Node.js is an interpreter or runtime/ running environment for JavaScript. built on Chrome's V8 JavaScript engine. responsibility is especially to execute your application.
MongoDB: is a No-SQL database for storing data. when you need high availability of data with automatic, fast, and instant data recovery.


text:
Q: how should we I use a modelEvaluator of JPMML evaluator in java multithreaded code? I am using JPMML Evaluator library and PMML instance is common for all evaluator will it block the evaluator and create locking. while processing in multithreaded fashion.
//single threaded

PMML pmml = <new pmml>

//multithreaded
ModelEvaluator<MiningModel> someModelEvaluatorThread = new MiningModelEvaluator(genderPmml);

will it work or hit on performance. I am not creating pmml thread specific because I don't want to parse the same file again and again.

A: The README.md file of the JPMML-Evaluator library says:

Model evaluator classes follow functional programming principles and are completely thread safe.

Doesn't matter if you share the same model evaluator instance between all threads, or create a separate model evaluator instance for each thread - they will all get along very nicely. The mutable state is encapsulated in org.jpmml.evaluator.EvaluationContext object instance, which is "private" to each evaluation request.
Also, the JPMML-Evaluator library doesn't contain any synchronized code blocks, and doesn't use any locking mechanisms. The throughput of your application should increase linearly as you start more threads.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make Android Studio Faster ? Critical Case My Android studio is taking 1hour+ to build the gradle.
Can anyone suggest me how to make it faster? I can't deploy any app. Its working perfectly fine after build. I have a HP 2000-329WM Laptop with 3GB RAM. Can anyone suggest the best method to make the Android Studio to work perfectly fine like in Macbook. I am using a physical device and hence emulator and other optional features can be removed.
Suggest me the best way to OPTIMIZE Android Studio Performance without adding new Hardware resources(RAM.etc)
Android Studio Version : 2.1.2
OS : Windows 10
RAM : 3GB

A: A bit of a hack but I think the best way is to switch to Linux. Windows 10 consumes more RAM than any other operating system.
Also if possible add some RAM to your Laptop it helps a lot.

A: When you have created the project, to go Files>Settings>Build, Execution, Deployment and then check the Offline Gradle.
Once you are done making the project uncheck offline Gradle and then run.
This will speed up your project.


text:
Q: My ssh server stopped working after I did something I'm very new to Linux, BTW. The ultimate goal for me is to run applications and their GUIs on a (Mac) computer from another computer. The first step is to just use SSH to access and control the computer using another computer and the terminal. This was working fine.
The next step was to install XQuartz on the server and terminal to be able to see and use GUI on the other computer. Regular SSH control worked but not the GUI. Apparently, the DISPLAY variable was not set correctly and this was probably due to the fact that X11Forwarding was set to no in the sshd.config file. I changed it to yes; regular SSH still worked but the DISPLAY was still wrong and GUI did not appear. So, I read that I had to restart the SSH service and I found a way to do it:
sudo launchctl unload -w /System/Library/LaunchDaemons/ssh.plist

This screwed something up, because now I can't even do regualr ssh control. I tried to both unload and load, this gives different error messages in the terminal:
When I run (on the other computer):
sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist

I instantly get:
ssh_exchange_identification: Connection closed by remote host

Then I tried to undo the damage:
sudo launchctl unload -w /System/Library/LaunchDaemons/ssh.plist

Then I, after some time (about 3 seconds), get:
ssh: connect to host macpro-c10c8b.imt.liu.se port 22: Connection refused

What have I done, and how can I fix it?

A: You should try looking in the logs of sshd, somehow you've come with invalid SSHD configuration, here is some guide on it: http://linux.die.net/man/5/sshd_config
look where sshd is logging stuff and look there for potential issue why it is not running for you.
This "ssh: connect to host macpro-c10c8b.imt.liu.se port 22: Connection refused"
should guide you there is no sshd running on macpro-c10c8b.imt.liu.se (probably your Linux box) which is why the command fails.

A: The problem is solved, we had changed the extension of sshd.config to sshd.config.txt. This did not have an effect until I did the unload/load command. This is why I blamed the unload/uload function. Changed the name back to normal, restarted the ssh service and now it works.


text:
Q: Reading multiple lines of doubles with fscanf I have an input file which contains six doubles on every line, which I would like to be read by fscanf. However, after reading the numbers from the input file, all stored values are zero. For example:
Input:
8.260358155 0.217414463 0.079918794 -0.068255156 -0.124913458 0.821136998
0.095921056 0.878265878 1.099486349  0.766342809  1.918243674 0.476907831
1.050441605 8.451442631 0.945819695 -0.440024089 -1.149013541 0.374284191

Code:
    double r[NMAX][3];
    double rv[NMAX][3];
    int nAtom = 3;
    int n;
    FILE *loadFile = fopen(LoadName,"r");
    if (loadFile == NULL){
        printf("ERROR: can't open loadFile\n");
        exit(1);
    }

    fscanf(loadFile,"%d",&nAtom);
    for (n=0; n<nAtom; ++n){
        fscanf(loadFile, "%f %f %f %f %f %f",
               &r[n][0],&r[n][1],&r[n][2],&rv[n][0],&rv[n][1],&rv[n][2]);
    }

    fclose(loadFile);

    for (n=0; n<nAtom; ++n){
        printf("%12.9f %12.9f %12.9f %12.9f %12.9f %12.9f\n",
                r[n][0],r[n][1],r[n][2],rv[n][0],rv[n][1],rv[n][2]);
    }

Output:
0.000000000  0.000000000  0.000000000  0.000000000  0.000000000  0.000000000
0.000000000  0.000000000  0.000000000  0.000000000  0.000000000  0.000000000
0.000000000  0.000000000  0.000000000  0.000000000  0.000000000  0.000000000

Could anyone say what I'm doing wrong here?

A: As @BLUEPIXY says in the comments, you're telling fscanf to parse your input values as floats, but having it put them into doubles.  You could fix this by either (as suggested) use %lf to tell fscanf you're filling doubles, or declare r and rv to be arrays of floats.
Compilers are pretty good about warning of such things, if you ask them nicely.

A: Your fscanf should look like :
fscanf(loadFile, "%lf %lf %f %lf %lf %lf",&r[n][0],&r[n][1],&r[n][2],&rv[n][0],&rv[n][1],&rv[n][2]);

Then delete the line
 fscanf(loadFile,"%d",&nAtom);


text:
Q: question on haml rendering I seem to be having a problem with haml. Rails is rendering:
%span
  stuff
  #div_name
  moar stuff

as
stuff

moar stuff

any ideas? why isn't 'moar stuff' inside the span?

A: Works fine for me:
$ echo '%span\n  stuff\n  #div_name\n  moar stuff' | haml

  stuff

  moar stuff

A: Try this:
%span
  stuff
#div_name
moar stuff

The span only contains stuff, so you have to undent after stuff, so that other elements are not contained in the span.
You can also write it like this:
%span stuff
#div_name
moar stuff

Which gives exactly this:
stuff

moar stuff


text:
Q: to change to https by http - safari shows our website not feel right We got our SSL certificate yesterday . This I have now embedded and redirected the old address on the https page . Now our site is no longer displayed in Safari correctly. In Chrome and Firefox, however, everything is working properly. I'm at a loss on what to do.
Our page is: https://www.zweistein.design

A: As I do not have Safari running on my PC I cannot double check this, however opening the source code on Firefox revealed a HTML semantic error. You appear to have a DIV tag in your HEAD tag.
DIV is a "flow content" tag and should not appear inside your HEAD tag.
https://developer.mozilla.org/en/docs/Web/HTML/Element/head
https://developer.mozilla.org/en/docs/Web/HTML/Element/div
Again I cannot test this so I am not sure if this is what is causing your issue, but definitely worth correcting.


text:
Q: How to apply function over a list by taking list of list elements as function argument? Reproduce-able data set-
set.seed(55)
data <- rnorm(8)

dates <- as.POSIXct("2019-03-18 10:30:00", tz = "CET") + 0:7*60
dataset <- xts(x = data, order.by = dates)

colnames(dataset) <- "R"
dataset$Timestep <- 1:8
dataset$Label <- 1
dataset$Label[4:8,] <- 2

I am trying to fit linear regression model separately for each label by taking "R" as dependent variable and "timestamp" as predictor and return all the slopes ( in this case- 2).
Initially my thought was to use split and lapply function but could not manage to execute it as I don't know how to access list of list with lapply.
As the dataset is really large, I want to avoid for loop. Can you guys help? Really appreciate it.

A: 1) formula Use the formula shown to nest within Label:
co <- coef(lm(R ~ factor(Label) / (Timestep + 1) + 0, dataset))
co[grep("Timestep", names(co))]
## factor(Label)1:Timestep factor(Label)2:Timestep
##              0.01572195              0.15327212

2) split/lapply  Alternately use split/lapply as shown:
slope <- function(x) coef(lm(R ~ Timestep, x))[2]
sapply(split(dataset, dataset$Label), slope)
## 1.Timestep 2.Timestep
## 0.01572195 0.15327212

2a) Alternately we can use the same last line of code but replace the slope function with a calculation that directly computes the slope without lm:
slope <- function(x) with(x, cov(R, Timestep)  / var(Timestep))
sapply(split(dataset, dataset$Label), slope)  # same as sapply line in (2)
##          1          2
## 0.01572195 0.15327212

3) nlme  This package comes with R so does not have to be installed.
library(nlme)
coef(lmList(R ~ Timestep | Label, dataset))[, "Timestep"]
## [1] 0.01572195 0.15327212


text:
Q: How to put something in header Details at the end the page? I have a crystal report document.
In the header Details, there is a subreport (format : vertical alignment : Bottom).
The report footer and page footer are suppressed.
Nonetheless in Preview, my subreport don't touch the bottom of the page.
Why?


text:
Q: FS mounted as RO on boot after upgrade to 15.04 Just upgraded from 14.10 to 15.04.
Couldn't get the system to boot ok.
I could boot using (upstart) option - not using default systemd.
When in default mode the lightdm terminal was stuck before login screen.
I could switch to TTY though.
I found out finally that in TTY i can run:
$ mount -rw -o remount /
This causes the lightdm service to continue to login screen and I can work normally.
However I now have to do that manually each reboot...
Also I tryed checing the FS using fsck and everything is OK.
Any thoughts?
EDIT - This is the content of my /etc/fstab:
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/sda1 during installation

/dev/disk/by-label/data /mnt/data ext4 nosuid,nodev,nofail 0 0
/dev/disk/by-label/backup /mnt/backup ext4 nosuid,nodev,nofail 0 0

A: Once you're sucessfully logged on to Ubuntu. Open a Terminal (Ctrl+Alt+T)  followed by:-
sudo nano /boot/grub/grub.cfg

Edit the line that looks like
linux /boot/vmlinuz-x.x.x-xx-generic root=xxx\xyz ro xxx-options

to
linux /boot/vmlinuz-x.x.x-xx-generic root=xxx\xyz rw xxx-options
This file is generated from the files present in /etc/grub.d and therefore you'll need to edit this each time you update or make changes to grub.


text:
Q: Pure-FTPD error: Unable to start a standalone server: Address already in use I just installed Pure-FTPD to give it a test run, I added a group and a user

groupadd test1
useradd -g test1 -d /var/www/html -s /etc testuser

then tried to run the server using

/usr/sbin/pure-ftpd -S <ip>,21 -c 30 -C 1 -l puredb:/etc/pureftpd.pdb -x -E -j -R

and receive this error

Unable to start a standalone server: Address already in use

I took a look at what was running that may already be using port 21

grep ftp /etc/services

and see this

21 is registered to ftp, but also used by fsp
ftp             21/tcp
ftp             21/udp          fsp fspd

then i took a closer look at port 21

lsof -i :21

and got this

COMMAND    PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
pure-ftpd 3709 root    4u  IPv4  12920      0t0  TCP *:ftp (LISTEN)
pure-ftpd 3709 root    5u  IPv6  12922      0t0  TCP *:ftp (LISTEN)

any clues?

A: it's already running, kill the pid and try again...

A: I too have same issue like this.
Failed to start Pure-FTPd FTP server.
PID file /var/run/pure-ftpd.pid not readable (yet?) after start.

I do the following steps:
# ps -A | grep ftp
 3080 ?        00:00:00 vsftpd
# kill 3080

Again I restarted my pure-ftpd.service and its  active (running).
Its works for me


text:
Q: How do you populate a google sheets/excel column with cells from a column in another sheet in the same document? I have a google sheets document that has a main sheet which will have columns x y and z and subsequent sheets 1, 2, and 3 that will each also have columns x y and z. Sheets 1, 2, and 3 represent different people who are putting information into the columns.
The purpose of the main sheet is to display all of the information that has been put into columns x y and zin the three other sheets so the information can be viewed all at once. The purpose of sheets 1, 2, and 3 is so each individual can track their own individual information without also seeing all the info from other people/sheets.
I would like to be able to automatically pull new information from sheets 1, 2, and 3 and have it placed in the respective column on the main sheet in chronological order. I know it is possible to have specific cells display information on another sheet, but if possible, I would like the cells to automatically populate the next available cell in whichever column they are under. Basically, the columns in the main sheet and the other three sheets are the same name, and I would like the columns in the main sheet to populate whenever new info is input to the respective columns in sheets 1, 2, and 3. I hope this makes sense.
For instance, if column x in sheet 2 was filled in with the name Jane Doe, the main sheet should automatically populate Jane Doe into the next available cell in column x. Then someone types in John Smith into column x on sheet 1 and it automatically populates the cell after Jane Doe with John Smith in the main sheet.
Here is a demo sheet with how I would like it to be, with the columns in the main sheet populated with the items in all the columns from sheets 1, 2, and 3: https://docs.google.com/spreadsheets/d/1y0dldFtq6NtLPjU21HVedtUzYKi-MjLTz62tupYbZGY/edit?usp=sharing
Is it possible to connect sheets within a document like this? Thank you so much in advance! :) Let me know if you need any more information.

A: with formulae, you have two options on chronology:
sheet-by-sheet
=QUERY({Sheet1!X:Z; Sheet2!X:Z; Sheet3!X:Z},
 "where Col1 is not null
     or Col2 is not null
     or Col3 is not null", )

row-by-row
=QUERY(SORT({
 Sheet1!X:Z, ROW(Sheet1!X:Z);
 Sheet2!X:Z, ROW(Sheet2!X:Z);
 Sheet3!X:Z, ROW(Sheet3!X:Z)}, 4, 1),
 "select Col1,Col2,Col3
  where Col1 is not null
     or Col2 is not null
     or Col3 is not null"; )

the next best thing is to have a timestamp script with onEdit trigger so every time your ppl make a change a timestamp is added on their sheet in some column and then you in your master sheet will only collect it and sort by timestamp.
https://stackoverflow.com/questions/tagged/google-apps-script+timestamp


text:
Q: How to use underscorejs to manipulate a DOM element's attribute? I know underscorejs template is way more useful to replace some sort of string. But can I use the same template mechanism to manipulate a DOM's attribute values based on an action?
Let's say I've a table (kendogrid) and I want to change a row's background color dynamically (a dropdown menu will be shown to the end user). I used jQuery to change the background. But my boss is insisting me to use underscorejs's template. I'm kinda stuck.
Help?? Anyone??

A: My guess is that they want you to update the data and render the template everytime there is an event that changes the DOM state.
HTML:

<select id="highlight-choice">
    <option value="0">first</option>
    <option value="1" selected>second</option>
</select>

Javascript: (certain parts must be run after DOM is ready)
var compile = _.template(document.getElementById('gridtemplate').innerHTML);

var data = {
    rows: [
        {
            columns: [1,2],
            background: '#fff'
        },
        {
            columns: [3,4],
            background: '#ff0'
        }
    ]
};

function render() {
    document.getElementById('container').innerHTML = compile(data);
}

render();

document.getElementById('highlight-choice').addEventListener('change', function() {
    _.each(data.rows, function(row) {
        row.background = '#fff';
    });
    data.rows[this.value].background = '#ff0';
    render();
});

jsFiddle


text:
Q: Adding cv-qualifers to a typedef-ed function type In the following code, the last two static_asserts fail.
But why? Where should I put the const to make the assertations pass?
#include <type_traits>

// these are ok
static_assert(!std::is_same_v<void(), const void()>);
static_assert(!std::is_same_v<void(), void() const>);
static_assert(!std::is_same_v<const void(), void() const>);
// so 'void()', 'const void()', 'void() const' are all distinct types

using F = void(); // or 'typedef void F()';

static_assert(std::is_same_v<const F, const void()>); // error!
static_assert(std::is_same_v<const F, void() const>); // error!

The above code may seem too abstract and like a pure language-lawyer code, so I'll explain in detail what led me to the question.
Real-life example
I had the following code:
#include <type_traits>

template <class>
struct X;

template <class T, class U>
struct X<T U::*> {
    using t = T;
};

struct A {
    void member() {}
};

static_assert(std::is_same_v<
    X<decltype(&A::member)::t, void()
>); // this is ok

My intention was that the X<pointer-to-member-function>::t would be the type of the written-outside-the-class version of the member-function (You probably know what I mean). And the code above runs fine, that is, the static_assert passes.
Next, I changed the definition of A to the following:
struct A {
    void const_member() const {}
};

and the static_assert to:
static_assert(std::is_same_v<
    X<decltype(&A::const_member)::t, void()
>);

Now the static_assert fails.
But then I noticed that if I changed the void() in the static_assert to void() const it compiles. So I changed the partial speciailization of X to the following (so that X::t would be void())
template <class T, class U>
struct X<const T U::*> {
    using t = T;
};

but then, the compiler complains:
 error: incomplete type 'X<void (A::*)() const>' used in nested name specifier
   17 |             X<decltype(&A::const_member)>::t, void()

Apparently, the specialization is not selected.


text: Q: Add/del root user Linux mint 19 Достался ящик от предыдущего сотрудника, стоит Линукс минт 19. Могу я как-то создать нового рут пользователя и потом удалить старого? Лень сносить минту. Действующий пароль естественно уехал вместе с хозяином.


text:
Q: any help or idea on how to implement the timer functionality i have the following code in react native ,
    let pub='';
  let x= '';
    // global variables

    setInterval(() = {
     const value = await AsyncStorage.getItem('users');//read data from async storage
     pub = JSON.parse(value);
     for (let i = 0; i < pub.length; i++) {
         x = pub[i].id;
         console.log('value of id >>', x);  // the value of x is printed every 30 secs, //if there are 3 values of x as 1,2,3
//I want 1 to be printed first 30 secs ,2 next 30 sec, 3 to be priint next
 30sec and again goback to 1 and so on..how to do ?

     },30000)

i want value of id to be printed every 30 seconds incrementing
for example,
if x has 1,2,3
i want 1st 30 sec 1 to be printed,
i want 2nd 30 sec 2 to be printed ,
3rd 30 sec 3 to be printed and repeat the same ...

A: You can do something like below
const value = await AsyncStorage.getItem('users');//read data from async storage
pub = JSON.parse(value);

if(!Array.isArray(pub))
  return;

let i =0;
setInterval(() => {
                   console.log('value of id >>', pub[i].id);
                   i++;
                 },30000)

A: No need for the for loop. The interval with an incrementing index takes care of that. Here's an example that will repeat or stop the interval once it's reached it's length - it's set for 3 seconds here in the example. Also note the fix in your arrow function () = { should be () => {.

//const value = await AsyncStorage.getItem('users');
//pub = JSON.parse(value);
let pub = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 7}, {'id': "F"}];
let id_index = 0,
  repeat = true
const interval = setInterval(() => {
  x = pub[id_index].id;
  console.log('value of id >>', x);
  if (id_index++ >= pub.length-1) {
    if (repeat) id_index = 0; //reset
    else clearInterval(interval)
  }

}, 500)

// just in case you have to stop
// clearInterval(interval)


text:
Q: Single word for "a chieftain of thieves" I am in need of a single word for "a chieftain of thieves", if there is any. If there is none, can I use "thieves'-chieftain" instead?

A: might I suggest ringleader?
ring·lead·er
ˈriNGˌlēdər/
noun
a person who initiates or leads an illicit or illegal activity.

A: Capo sense #2
The head of a crime syndicate, especially the Mafia, or a branch of one.

A: To me, the best alternative would be "king thief".
Sorry! I had accidentally written "king thieve" in place of "king thief". I am sorry for the mistake. I did not mean plural, else I would have written "thieves".

A: One possible alternative is kingpin. Wikipedia gives some other suggestions.

A crime boss, crime lord, mob boss, kingpin, or Don is a person in charge of a criminal organization.

A: Guildmaster would be a good term for fantasy or science fiction or medieval historical fiction. This comes from the archetypal "thieves' guild" that's prevalent in Dungeons and Dragons and all of it's roll-playing variations over the last 40 years. Many best-selling fantasy authors (R.A. Salvatore, for instance) have used the expression in their works.

A: Perhaps head thief
Example: "You see," the head thief began, "we are professional pickpockets. As soon as the guards would enter the barracks, we would slip the cards into their pockets.


text:
Q: from movieclip (check if main timeline is playing) in as3 i have this function, but ......
i want
 if the main time is playing so it go to the frame  and play
and
 if the main time is (not playing)  so it go to the frame  and pause
this function for a custom slider control in the main time.
thanks;
sliderLine_mc.addEventListener(MouseEvent.CLICK,snapTO);

function snapTO(event:MouseEvent)

{
    if (sliderTrack.mouseX > 0 && sliderTrack.mouseX < 320)
    {
        sliderKnob.x = mouseX;
        sliderKnob.x = MovieClip(root).currentFrame * (300 / MovieClip(root).totalFrames);

        if (MovieClip(root).isPlaying == true)
        {
            MovieClip(root).gotoAndPlay(Math.floor(mouseX / (300/MovieClip(root).totalFrames))-60);

        }
        else if (MovieClip(root).isPlaying == false)
        {
            MovieClip(root).gotoAndStop(Math.floor(mouseX / (300/MovieClip(root).totalFrames))-60);

        }

    }
}

A: You can create a watcher movie clip that will do what you want:
public class WatcherMC extends MovieClip
{

private var last_enter_frame:int= 0;
private var root_animation_steps:int= 0;
private var root_stoped_steps:int= 0;
public RootIsPlaying:boolean= false;
public function WatcherMC():void
{
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}

private function onEnterFrame(event:Event):void
{
    if (MovieClip(root).currentFrame!= last_enter_frame)
    {

        root_animation_steps++;
        if (root_animation_steps> 3)
        {
                    root_stoped_steps= 0;

                    root_is_playing();
        }
    }
    else
    {
             root_stoped_steps++;

             if (root_stoped_steps> 3)
             {
            root_animation_steps= 0;
            root_is_still_not_playing();
             }
    }
        last_enter_frame= MovieClip(root).currentFrame;
}

private function root_is_playing():void
{
// root is playing, do what ever I want
RootIsPlaying= true;
}
private function root_is_still_not_playing():void
{
// root is not playing, do what ever I want
RootIsPlaying= false;
}

}
put your code in the functions root_is_playing and root_is_still_not_playing
you can then check WatcherMC_instance.RootIsPlaying or not if you instantiate an instance of WatcherMC movie clip ..
like this:
var WatcherMC_instance:WatcherMC= new WatcherMC();
// use WatcherMC_instance.RootIsPlaying ..

I hope this will help!


text:
Q: MIC ON, Problems with audio on IOS 15 I ask for help with this problem, example: In a game or any app, I turn on the microphone and automatically the audio/sound of background apps slide the volume or mute or switch to MONO. Example: In games, we need STEREO audio to hear directions and we also need the microphone to talk to the team (Squad). It is not possible, with the microphone connected, the game audio will switch to MONO! MY QUESTION: Is there any app to manage and control audio output for iPhone?
I came across the same problem on the following devices: IPhone 8Plus IOS 14.8, IPhone XR IOS 15.1. and iPhone 12 IOS 15.1
[From Google Translate. original below]

Oi, peço ajuda com esse problema, exemplo: Em um jogo ou em qualquer aplicativo, ligo o microfone e automaticamente o áudio/som dos aplicativos em segundo plano deslizo o volume ou mudo ou mude para MONO. Exemplo: Nos jogos, precisamos de áudio ESTÉREO para ouvir direções e também precisamos do microfone para conversar com a equipe (Esquadrão). Não é possível, com o microfone conectado, o áudio do jogo mudará para MONO! MINHA PERGUNTA: Existe algum aplicativo para gerenciar e controlar a saída de áudio para iPhone?
Me deparei com o mesmo problema nos seguintes dispositivos: IPhone 8Plus IOS 14.8, IPhone XR IOS 15.1. e iPhone 12 IOS 15.1

A: From what I can find out, the iPhone's mics are not set to be stereo by default. Usually, the connection from a wired or bluetooth mic to an iPhone is for telephony, which does not require a stereo audio signal.
This page at Apple Developer shows how to enable stereo microphone input, but only, it seems, from within an iOS app coded to do so. I've seen no Setting in iOS to change to Stereo.
An iPhone feedback submission to Apple may be a first step making Apple aware of the necessity of providing user control of the built-in mics.


text:
Q: Is MonoTouch can change UISwitch's label text? As the title said, I was wonder if MonoTouch can change UISwitch's label text. Many topic talk about Object C's implements, and something about "catagory", who can help me?

A: Here is a forum discussing this topic.
From what it looks like to me, you can look at the SubViews of the UISwitch and cast them to UILabel and modify the text.  You can probably get more information in the MonoDevelop debugger to see which index to use.
Although, since these are private details about UISwitch, which Apple could change at any time and break your app--I don't know if I'd use it.  Would you be better off putting a UILabel next to your UISwitch describing its functionality more clearly?


text:
Q: How to call memcmp() on two parts of byte[] (with offset)? I want to compare parts of byte[] efficiently - so I understand memcmp() should be used.
I know I can using PInvoke to call memcmp() - Comparing two byte arrays in .NET
But, I want to compare only parts of the byte[] - using offset, and there is no memcmp() with offset since it uses pointers.
int CompareBuffers(byte[] buffer1, int offset1, byte[] buffer2, int offset2, int count)
{
  // Somehow call memcmp(&buffer1+offset1, &buffer2+offset2, count)
}

Should I use C++/CLI to do that?
Should I use PInvoke with IntPtr? How?
Thank you.

A: C++/CLI will definitely be the cleanest, but this hardly justifies adding C++/CLI to your project if you aren't already using it.
How about Marshal.UnsafeAddrOfPinnedArrayElement(array, offset)?

A: No matter what you do, you should check that the offset/count values are valid for the given byte arrays. After you do that, I don't see how just doing a for loop in C# is going to be any slower than P/Invoking a Win32 method.  Seems like there would be a lot of overhead in the P/Invoke that it would not be worthwhile.
Also, there is always unsafe C#.
As with all performance questions, you should do your own performance testing.  But it sounds to me like you are trying to optimize for performance prematurely.

A: No need to P/Invoke in C++/CLI.  Use pin_ptr<> to pin the array.  That gets you a byte*, just add the offset.

A: [DllImport("msvcrt.dll")]
private static extern unsafe int memcmp(byte* b1, byte* b2, int count);

public static unsafe int CompareBuffers(byte[] buffer1, int offset1, byte[] buffer2, int offset2, int count)
{
    fixed (byte* b1 = buffer1, b2 = buffer2)
    {
        return memcmp(b1 + offset1, b2 + offset2, count);
    }
}

You might also want to add some parameter validation.

A: There is one more way
SequenceEqual from System.Linq
 byte[] ByteArray1 = null;
 byte[] ByteArray2 = null;

 ByteArray1 = MyFunct1();
 ByteArray2 = MyFunct2();

 if (ByteArray1.SequenceEqual<byte>(ByteArray2))
 {
    MessageBox.Show("Same");
 }
 else
 {
   MessageBox.Show("Not Equal");
 }


text:
Q: extract headers from a list of files along with the file name I was trying to write a shell script wherein I can extract the headers and also the filename from a list of files in a given directory.
For example: ABC_TESTFILE1.csv contains headers like
C1,C2,C3

ABC_TESTFILE2.csv contains headers like
C1,C4,C5

I want output text file as:
ABC_TESTFILE1,C1,C2,C3
ABC_TESTFILE2,C1,C4,C5

I was trying my luck as:
#!/bin/bash

# Go to where the files are located
filedir=/home/vikrant_singh_rana/AAA_USP/Combined-Files/*

for filepath in $filedir
do
 #echo "Processing $filename"
 # do something on $f
 var_head=$(head -n 1 basename "$filepath" )
 echo "$var_head"
done; > test.txt

A: Using AWK:
awk 'NR==1 {print FILENAME "," $0}' *.csv

will list all the files with a .csv extension containing at least one line, with the first line.

A: You could use printf to format the output of basename and head:
for file in /home/vikrant_singh_rana/AAA_USP/Combined-Files/*.csv; do
  printf '%s,%s\n' "$(basename "$file" ".csv")" "$(head -n1 "$file")"
done >test.txt

A: path=(`ls -d /tmp/*.csv`)
        for file in "${path[@]}"; do
            head_line=`head -n1 $file`
            file_no_extension=`basename $file | sed 's/\..*//'`
            echo "$file_no_extension""$head_line"
        done

Make sure that path its an array:
[root@mole tmp]# set | grep ^path=
path=([0]="/tmp/ABC_TESTFILE1.csv" [1]="/tmp/ABC_TESTFILE2.csv")


text:
Q: Code First database generation external dll I am attempting to use code first to generate a database and seed it every time my application is run, however I get the following error:

Cannot attach the file
  'C:{filepath}\Application\App_Data\mydatabase.mdf' as database
  'mydatabase'.

I've tried to do an 'update-database' (as recommended from other questions) however no .mdf files get generated.
This is the connection string used:

Data
  Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\mydatabase.mdf;Initial
  Catalog=mydatabase;Integrated Security=True

As some background information, I have two different projects which sit in different solutions:

*

*Application

*Domain

The 'application' project has a reference to the 'domain' project
In the domain project I have created my code first models and dbContext:
public class ApplicationContext : IdentityDbContext<User, IntRole, int, IntUserLogin, IntUserRole, IntUserClaim>
{
    public ApplicationContext()
        : base(nameOrConnectionString: "constr") { }

    public ApplicationContext(string connectionString)
        : base(nameOrConnectionString: connectionString) { }

    static ApplicationContext()
    {
        Database.SetInitializer<ApplicationContext>(null);
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Use singular table names
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly());

        Configuration.ProxyCreationEnabled = false;
        Configuration.LazyLoadingEnabled = false;
        Configuration.ValidateOnSaveEnabled = false;
    }

    public DbSet<Item> Items { get; set; }
}

public class ApplicationContextInitializer : DropCreateDatabaseAlways<ApplicationContext>
{
    protected override void Seed(ApplicationContext context)
    {

        new List<Item>
        {
          new Item("test")
            {
            },
          new Item("test2")
            {
            },
          new Item("test3")
            {
            }
        }.ForEach(t => context.Items.Add(t));

        base.Seed(context);
    }
}

Inside my application project in the global.asax I have the following :
            Database.SetInitializer(new ApplicationContextInitializer());

I then attempt to add data to the database:
        mUnitOfWork = new UnitOfWork(new RepositoryProvider(new RepositoryFactories()));

        mUnitOfWork.ItemRepository.Add(new Item("my item"));
        mUnitOfWork.Save();

A: Turns out you need to add a context to the web.config as follows :
<configuration>
  <entityFramework>
    <contexts>
      <context type="Application.Data.ApplicationContext, Application.Data">
        <databaseInitializer type="Application.Data.ApplicationContextInitializer, Application.Data" />
      </context>
    </contexts>
  </entityFramework>
</configuration>

Useful link if anyone else has a similar problem: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

A: To extend the correct answer, you could also add this by Code:
public class DBConfig
{
    public static readonly DBInitializer Initalizer = new DBInitializer();

    public static void InitalizeDB()
    {
        System.Data.Entity.Database.SetInitializer<DMPDataContext>(Initalizer);
    }
}
protected void Application_Start()
    {
        //common application startups
        DBConfig.InitalizeDB();
        //...
    }


text:
Q: Disabling secure boot no longer loads ubuntu gnome (UEFI) I have installed ubuntu gnome next to windows 10 on an acer a7 with UEFI.
 I'm trying to install a nvidia driver and for that I need to disable secure boot.
When I turn off secure boot, I reach a terminal instead of the ubuntu login screen. Why is that?


text:
Q: Passing a value between view Controllers Objective C - iPhone Application
I have 2 programatically instantiated UINavigationControllers
In controller 1 I push this View
-(IBAction) showStartDateCalendar
{
 ModalSetDateController *setStartDate = [[ModalSetDateController alloc] init];
 [self.navigationController pushViewController: setStartDate animated:YES];
 [setStartDate release];

};

To push it back I was planning on doing something like this:
-(IBAction) PopMyViewControllerBack;

{
 [self.navigationController popViewControllerAnimated: YES];
}

But how would I be able to get the value of the datepicker on ModalSetDateController
Is this the best way to handle adding a UIPickerview. I would prefer to not even have a UINavigationController do it.
Thanks for your help!

A: Use:
-(IBAction)popMyViewControllerBack:(id)sender

and sender will be an instance of ModalSetDateController.


text:
Q: Vacuous truth and empty set properties I have a flaw in my reasoning, could you help me figure out what I am doing wrong?
To proof that $\emptyset$ is closed under addition we need to evaluate the following logical statement:
$$
\forall x,y \in \emptyset: Q(x,y)
$$
where $Q(x,y)$ is "$x+y \in \emptyset $"
We can transform this into a conditional statement like so:
$$
\forall x,y \in A:P(x,y)\implies Q(x,y)
$$
where $A$ is a non-empty set with at least two elements and $P(x,y)$ is "$x,y \in \emptyset$".
Here we can see that the first statement will always be false since $\emptyset$ has no elements and then by conditional logic this whole statement evaluates to true and so we conclude that $\emptyset$ is closed under addition. This is a vacuous truth.
But can we not use the same conditional logic to proof that $\emptyset$ is not closed under addition by using $R(x,y)$ to be "$x+y \notin \emptyset$"?
$$
\forall x,y \in A:P(x,y)\implies R(x,y)
$$
Since the antecedent $P(x,y)$ will always be false the whole statement will always evaluate to true and then we can conclude that $\emptyset$ is not closed under addition.

A: For addition not to be closed on the empty set, you would need to show $\exists \,x,y \in \emptyset: x+y \notin \emptyset$.
This is not a consequence of the vacuous truth $\forall x,y \in \emptyset: x+y \notin \emptyset$, so there is no contradiction with the other vacuous truth $\forall x,y \in \emptyset: x+y \in \emptyset$. Assuming you have a suitable definition of addition, it remains the case that addition is closed on the empty set.

A: You have almost "reinvented" Proof By Contradiction !
We want to know whether $P$ is true or not.
You have :
$ P \rightarrow Q $
$ P \rightarrow R $
You know that :
$Q = \lnot R$ [ Equivalently $R = \lnot Q$ ]
Putting these together , we have a Contradiction.
Hence , we know that $P$ can not be true !
Example :
$M$ is the Empty Set of Martians.
$P$ : "Martians Exist" : $\exists m \in M$
$Q$ : "All Martians are born on Mars" : $\forall m \in M : BornOnMars(m)$
$R$ : "All Martians are not born on Mars" : $\forall m \in M : \lnot BornOnMars(m)$
$Q = \lnot R$ [ Equivalently $R = \lnot Q$ ]
$P \rightarrow Q$
$P \rightarrow R$
We can conclude ( Proof By Contradiction ) that "Martians Exist" is not true : $P$ is not true.


text:
Q: Dynamic Array Fibonacci I need to turn a code that prints out the Fibonacci series that also uses dynamic arrays, here is what I have so far, I just don't know how to turn it into a dynamic array.
public class Fibonacci {
    public static void main(String[] args) {
        int[] numbers;
        numbers = new int[20];
        numbers[0] = 1;
        numbers[1] = 1;
        System.out.println("\nFibonacci series:\n");
        System.out.println(numbers[0]);
        System.out.println(numbers[1]);
        for (int i = 2; i < 20; i++) {
            numbers[i] = numbers[i-2]+numbers[i-1];
            System.out.println(numbers[i]);
        }
    }
}

A: The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.
Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.
Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.
It has three constructors:
ArrayList( )
ArrayList(Collection c)
ArrayList(int capacity)

Apart from that there are so many methods inherited from its parent class.

An example Program and Output:
import java.util.*;

public class ArrayListDemo {
   public static void main(String args[]) {
      // create an array list
      ArrayList al = new ArrayList();
      System.out.println("Initial size of al: " + al.size());

      // add elements to the array list
      al.add("C");
      al.add("A");
      al.add("E");
      al.add("B");
      al.add("D");
      al.add("F");
      al.add(1, "A2");
      System.out.println("Size of al after additions: " + al.size());

      // display the array list
      System.out.println("Contents of al: " + al);
      // Remove elements from the array list
      al.remove("F");
      al.remove(2);
      System.out.println("Size of al after deletions: " + al.size());
      System.out.println("Contents of al: " + al);
   }
}

Output:
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]

Also read this:
Java Dynamic arrays

A: One thing you can do is ask user to input the value for number of Fibonacci numbers he/she wants, store it in a variable and give
    numbers = new int[n];
this way you can implement dynamic arrays in this way also.

A: Dynamic arrays are arrays which can grow in size such as ArrayList or vectors. ArrayList is used often.
here is a solution for your problem
import java.util.*;
public class fibo{
public static void main()
{
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(0);
a.add(1);
insertoneelement(a);
System.out.println(a.toString());
}
public static void insertoneelement(ArrayList<Integer> x)
{x.add((x.get(x.size()-2)+x.get(x.size()-1)));}
}

make your loop pass over insertoneelement(a) in main() as many times as many extra elements you want apart form initial 0 and 1.
Indexing of ArrayList is similar to that of arrays, index first element is 0 and of the last is length of array - 1. The size() method returns the number of elements in the ArrayList.

A: Here's an example of a manual dynamic array:
public static void main(String[] args) {
    // Fibnocci begins with 0, 1
    int[] fibNumbers = new int[] {0, 1};

    // Set your condition of how many numbers you want to create, 20 in my case.
    // This is also limited to the max value of an integer
    while (fibNumbers.length < 20) {
        // Create a new array for the next number in the sequence
        int[] newFibNumbers = new int[fibNumbers.length + 1];
        // Copy the cotents from your original array to this new array
        System.arraycopy(fibNumbers, 0, newFibNumbers, 0, fibNumbers.length);
        // Calculate the last element which is equal to the sum of the previous two elements
        newFibNumbers[newFibNumbers.length - 1] = newFibNumbers[newFibNumbers.length - 2] + newFibNumbers[newFibNumbers.length - 3];
        // Set the new array to the original array
        fibNumbers = newFibNumbers;
    }

    // Print your fibonacci series
    for (int i = 0; i < fibNumbers.length; i++) {
        System.out.println(fibNumbers[i]);
    }
}

Results:


text:
Q: MySQL: Relacionar 5 tablas LEFT JOIN y COUNT Tengo 5 tablas:

*

*Tabla usuarios:
| id_usuario | nombre_usuario  |
| ---------- | --------------- |
| 1          | jose perez      |
| 2          | manolo garcia   |
| 3          | antonio sanchez |

*Tabla productos:
| id_producto | nombre_producto   |
| ----------- | ----------------- |
| 1           | camiseta espinete |
| 2           | camiseta batman   |
| 3           | camiseta simpson  |

*Tabla favoritos:
| id_favoritos | id_producto | id_usuario |
| ------------ | ----------- | ---------- |
| 1            | 3           | 2          |
| 2            | 1           | 3          |
| 3            | 2           | 1          |

*Tabla chistes:
| id_chiste | titulo_chiste    |
| --------- | ---------------- |
| 1         | chiste arevalo   |
| 2         | chiste jose mota |
| 3         | chiste gatos     |

*Tabla likes:
| id_like | id_chiste | id_usuario |
| ------- | --------- | ----  ---- |
| 1       | 3         | 2          |
| 2       | 1         | 3          |
| 3       | 2         | 1          |

Donde un usuario puede añadir productos como favoritos y darle like a los chistes. Me interesa conocer la cantidad total de favoritos y likes de cada usuario en una misma consulta y ordenar la lista de usuarios por una u otra cantidad (cantidad de favoritos o cantidad de likes, según lo que se seleccione). Se como hacerlo por separado, es decir, en dos consultas diferentes:

*

*Para listar los usuarios con el número total de favoritos uso:

SELECT usuarios.*,
count(favoritos.id_usuario) AS numFavoritos
FROM usuarios
LEFT JOIN favoritos
ON usuarios.id_usuario = favoritos.id_usuario
GROUP BY usuarios.id_usuario
ORDER BY numFavoritos DESC

*

*Y para listar los usuarios con el número total de likes uso:

SELECT usuarios.*,
count(likes.id_usuario) AS numLikes
FROM usuarios
LEFT JOIN likes
ON usuarios.id_usuario = likes.id_usuario
GROUP BY usuarios.id_usuario
ORDER BY numLikes DESC

He estado probando para hacerlo en una única consulta a la base de datos, pero no lo consigo.
Si alguien pudiera ayudar, se lo agradecería muchísimo, un saludo a todos!

A: Para obtener la cantidad de favoritos y de likes puedes unir las tres tablas de este modo:
SELECT
    usuarios.*,
    count(favoritos.id_usuario) AS numFavoritos,
    count(likes.id_usuario) AS numLikes
FROM usuarios
    LEFT JOIN favoritos ON usuarios.id_usuario = favoritos.id_usuario
    LEFT JOIN likes ON usuarios.id_usuario = likes.id_usuario
GROUP BY usuarios.id_usuario
ORDER BY numFavoritos DESC, numLikes DESC

Si te interesa ordenar primero por likes sólo tienes que cambiar la parte del orden así:
ORDER BY numLikes DESC, numFavoritos DESC


text:
Q: What is a reasonable size / order of magnitude for code splitting We are working no a large React code base and want to split up the application into smaller chunks using react-loadable.
My team mates are currently trying to make each and every component lazy-loadable. I do not think this is the right approach, as lazy loading also comes with some overhead, so I would prefer lazy loading larger building blocks like whole pages.
I have found lots of content on how to use lazy loading, however I have not found much information when comes to whether it makes sense to use lazy loading.
How should one approach lazy loading in React (in general / as a start)? What is good measure to determine whether lazy loading makes sense for a component?

A: That's a interesting question and as tdelaney said, this is very opinion based and it depends on the kind of application your team is working on.
Why not load everything in a lazy manner?
I wondered why not to lazy load everything.
Imho, loading every component in a lazy way is not so advantageous.
Your application may result boring to user by showing too many spinners/loader animations.
Furthemore:

*

*the complexity of writing and maintaining the code increases significantly. That's because for each component you have to manage both the "loading" (see Suspense in the below snippet) and the "loaded" status and appearance.

*your performance may be affected by many browser re-paintings of big areas.

How I'd approach to this
In my case, I started examining the scenarios from an user point of view in order to improve the user experience and reduce the "freezing" times.
For instance, I wanted the users of my web application (which is embedded in retail kiosks but also available for mobile devices), to quickly show a SplashScreen and then load each chunk separately.
After showing a SplashScreen, my intent was to show the App component with just "ui skeletons" of the child components while these (children of App component) were loading their nested child.
That made my application looking modern and very fast.
Then, many components for not visible/nested pages could be shown after user interactions, when clicking buttons, opening modals etc., etc... In this way it gained several seconds.
To sum up:

*

*render SplashScreen

*lazy load and render Application

*

*render skeletons of visible components

*lazy load and render visible components

*

*render children

The following is an index file I am currently using to implement it in a quite large project:
import React,{ lazy, Suspense, FC } from 'react';
import { createRoot } from 'react-dom/client';

import SplashScreen from "./SplashScreen";
const App = lazy(() => import('./App'));

const Application: FC = () => {
  console.log("Rendering <Application/>");

  return (<Suspense fallback={<SplashScreen/>}><App /></Suspense>);
}

const appRoot = createRoot(document.getElementById('app-container'));
appRoot.render(<Application />);

See the Code-Splitting section React.lazy and Critical rendering path for details.
I hope this has been helpful to you.


text:
Q: HTML-CSS overlay covering whole page with centered elements I want to create a simple full-screen overlay with loader and text in the center. I have some problems with the text. I want the image to be over ABOVE the text. Can you help me with this?

Loading, please wait...

http://jsfiddle.net/bLz7wgvs/2/
[edit]
Sorry for my English. I meant "above", not "under"...
It should look like:
                               [-------------loader here-------------]
           Loader text (plz wait, etc.) in one line, both centered horizontally and vertically

A: Edit
I didn't know you wanted to let the image appear above the text. I've changed your code a little bit: http://jsfiddle.net/bLz7wgvs/7/
CSS:
.loader-overlay {
    -ms-opacity: 0.9;
    background: #444;
    display: block;
    height: 100%;
    left: 0;
    opacity: 0.9;
    position: fixed;
    top: 0;
    vertical-align: middle;
    width: 100%;
    z-index: 100000;
}

.loader-content {
    margin-left: auto;
    margin-top: auto;
    width: 50%;
}

.loader-center {
    -moz-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
    left: 50%;
    display: block;
    position: fixed;
    top: 50%;
    transform: translate(-50%, -55%);
}

.loader-text {
    color: #FFF;
    font-size: 18px;
    height: 50%;
}

A: You just need to add a z-index to the image (and the associated class required to the HTML element):
.loader-img {
    z-index: 10;
}

http://jsfiddle.net/bLz7wgvs/4/
Otherwise, you can just replace the order of the elements in the DOM if you have control over this. Siblings will appear above other siblings if they appear after them in the DOM tree  As stated in the spec:

Within each stacking context, the following layers are painted in
  back-to-front order:

*

*the background and borders of the element forming the stackingcontext.

*the child stacking contexts with negative stack levels (most negative first).

*the in-flow, non-inline-level, non-positioned descendants.

*the non-positioned floats.

*the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.

*the child stacking contexts with stack level 0 and the positioned
  descendants with stack level 0.

*the child stacking contexts with positive stack levels (least positive first).

So you can just change the markup to:

Loading, please wait...

http://jsfiddle.net/bLz7wgvs/6/

A: Try this,
 .loader-overlay {
        -ms-opacity: 0.9;
        background: #444;
        display: block;
        height: 100%;
        left: 0;
        opacity: 0.9;
        position: fixed;
        top: 0;
        vertical-align: middle;
        width: 100%;
        z-index: 100000;
    }

    .loader-content {
        height: auto;
        margin-left: auto;
        margin-top: auto;
        width: auto;
    }

    .loader-center {
        -moz-transform: translate(-50%, -50%);
        -ms-transform: translate(-50%, -50%);
        -o-transform: translate(-50%, -50%);
        -webkit-transform: translate(-50%, -50%);
        left: 50%;
        position: fixed;
        top: 50%;
        transform: translate(-50%, -50%);
    z-index:1;
    }

    .loader-text {
        color: #FFF;
        font-size: 18px;
    z-index: 1;
    }

Ive added z-index to the image and loader text :)


text:
Q: Memory mapping, virtual and physical memory in C++ I am trying to solve the following issue: having a custom data container that manages a generic type, I need to allow for other application components to retrieve the container's internal pointer and use it as if it were a simple T* array region (without treating it as a more intelligent array holder). The problem is that this memory is, in a very special case, moved somewhere else and erased. So there are a plethora of components that are aware of the old data pointer and will use that one to access their required information.
The setup looks, pseudo-codeish, something like this:
container<T>
{
  T* ptr;
  public:
  ContainerInterfaceCode..
}

Hypothesis:
T* ptr is a pseudo-address (may I call it "virtual"?) which is mapped in a physical space A.
When an event is risen, T* ptr's mapping will be set for another physical space, B.
Any component that uses T* ptr is then oblivious of the change of physical location, "thinking" its data is stored at that virtual address.
Conclusion:
I would therefore like to know whether there is a mechanism involving memory mapping (virtual to physical) that will allow to juggle with the mapping of the T* ptr, thus leaving other application components untouched. Simply put, T* ptr should point to a memory region that gets mapped in a certain part, and, upon request, that same pointer will be mapped in another place (where the underlying data is to be copied for consistency). This must allow seamless transitions.
Note: I can't use wrappers, smart pointers, handles, etc. for the simple fact that it means modifying a huge codebase just for one, rather minor, modification.
As I haven't found enough resources dealing with this scenario, can anyone, perhaps, present a short webography with some relevant reading material on the subject?

A: In linux you can used the shared memory.The shared memory is a mechanism which allow two process  access a same area of memory, it is a kind of IPC method. You can find some more
details here http://en.wikipedia.org/wiki/Shared_memory.


text:
Q: How can I make sudo never ask for a password with a certain argument, but always ask for a password with another argument? For example, I want to allow sudo shutdown -c to always be run without entering a password, but sudo shutdown without -c to always require a password (even if I've authenticated to sudo previously).

A: To change your sudo configuration you need to edit you /etc/sudoers file by using visudo (Only use this because it has validation included. If you don't know how to use vi here are the quick basics you need to edit the file). To allow certain parameters there is an answer here. So you would basically add something like
user ALL=(root) NOPASSWD: /usr/bin/shutdown -c

to the file to allow all users to excecute shutdown -c without entering a password. To make sudo allways ask for a password you can set the timeout to 0 by adding
Defaults timestamp_timeout = 0

this is not command specific (sorry couldn't find anything better) but will ask for a password for all commands that need one to execute (ie there is no NOPASSWD option specified).
For more details on what you can do with your sudoers file see the official page.


text:
Q: Changes in dll on converting web application from vs 2008 to 2012 I want to use an ASP.NET web application which was built using visual studio 2008 to 2013. will keep the .net framework to 3.5.
My concern is: There will be changes to .csproj and .sln after opening the project in 2013 but what about the dll to be deployed. would i need to update the hosting environment to 4.0 or any dependency upgrade?

A: The csproj and sln files will indeed be upgraded, but that has no bearing on the output of compilation.
As long as you continue to build for .NET 3.5, there shouldn't be any additional requirements to deploy your application. One thing to keep in mind is that VS2008 web deploy projects and database projects have been deprecated, and no upgrade path for those exists. So be careful if you're using either of those.
The safest approach for you will be to test the upgrade. Install VS2013, which runs side-by-side with VS2008. Open up the old solution, let VS update it, then do a test deployment. If there's a problem, just revert the change to whatever your last source controlled version is.


text:
Q: iPhone PayPal init failed I try to init PayPal in my app. Sometimes I get "Network Timeout" error and if I retry to init PayPal this alerts appear again and again. How to avoid this? How to reinit PayPal correctly?  My code is:

- (void)initializePayPal {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    [PayPal initializeWithAppID:PP_APP_ID forEnvironment:ENV_SANDBOX];

    while ([PayPal initializationStatus] == STATUS_INPROGRESS) {
        [NSThread sleepForTimeInterval:1];
    }

    switch ([PayPal initializationStatus] ) {
        case STATUS_COMPLETED_SUCCESS:
            NSLog(@"STATUS_COMPLETED_SUCCESS");
            break;
        case STATUS_COMPLETED_ERROR: {
            NSDictionary *responseMessage = [PayPal getInstance].responseMessage;
            NSLog(@"STATUS_COMPLETED_ERROR:%@", responseMessage);

            if ([[responseMessage objectForKey:@"errorId"] integerValue] == 10818) {
                [self initializePayPal];
            }
        }
            break;
        default:
            break;
    }

    [pool release];
}

A: PayPal init failed sometimes when i use ENV_SANDBOX The problem was solved when i start use ENV_LIVE instead ENV_SANDBOX

A: In fact, your program will never work.
PayPal.initializePayPal

is an async method and the do-initialize part of it has to be run in a message loop. So in your code you while statement are holding the main thread from return to the event loop. what you need to do, is to left this method go and try to test the status when you want to use any of the PayPal feature in your UI. Give the real initialize a chance to run.


text:
Q: Has anyone ever used a pencil while at Hogwarts? From the Slytherin Welcome Message:

We also get respect from our fellow students. Yes, some of that respect might be tinged with fear, because of our Dark reputation, but you know what? It can be fun, having a reputation for walking on the wild side. Chuck out a few hints that you've got access to a whole library of curses, and see whether anyone feels like nicking your pencil case.

I was always under the impression that everyone at Hogwarts wrote with ink and quills, so why would they need something to hold pencils?
Does anyone at Hogwarts ever use pencils or pens to write with?

A: Yes, people do use pens, which they attach to quills. If they have pens, they could store them in a pencil case. Why they are still called pencil cases instead of pen cases, or quill-tip cases, might be mere tradition.
Dolores Umbridge has a set of pens on her desk in this scene where she uses her "special" quill to punish Harry Potter.

I can't remember any student using pencils specifically, or anybody else for that matter.
Side note: I think this would come under the purview of the Ministry Department called Misuse of Muggle Artefacts. Perhaps somebody should notify an employee of that department, such as Arthur Weasley, that Ms. Umbridge is misusing pens.

A: No, or if they have it's never mentioned.
No one is ever mentioned as actually using or having a pencil at Hogwarts in the seven books. However, there are two mentions of students having pencil cases.

"...and Parvati and Lavender, who were practising basic Locomotion Charms, were making their pencil-cases race each other around the edge of the table." - Harry Potter and the Order of the Phoenix, Chapter 31 (O.W.L.s)

Hermione, Lavender and Parvati all have a pencil case.

"Oh, yes,' said Hermione in a choked voice, taking her things and turning away quickly to hide the fact that she was wiping her eyes on her pencil case." - Harry Potter and the Half-Blood Prince, Chapter 15 (The Unbreakable Vow)

It's never said, though, what's actually in the pencil case. It's possible that it is indeed used to hold pencils, but it's also possible that it's used to hold other small items, perhaps even the quills Hogwarts students usually write with.

A: Pencils are used in at least one scene of at least one film, where they appear alongside quills as an alternative.

I believe this scene was in The Goblet of Fire.
This makes sense to me as a simple wooden pencil as seen appears to fit the setting and as in most schools you'd have ink or pencil to choose from, the filmmakers decided so can Hogwarts.
It is never mentioned in the books though, and even Harry's drawing of a Bowtruckle for Professor Grubbly-Plank is made with his quill. (Page 241 OotP)


text:
Q: Convert Infix expression to list I want to convert infix expression to list such that double digits or character are considered a single operand i.e 28*35/(21-13) should result in ['28', '*', '35', '/', '(', '21', '-', '13', ')']
This is the code I've written and it works fine but I was wondering if there was a smarter way to do it like with list comprehension or something
expression = "28*35/(21-13)"
expression.replace(' ', '') # replace spaces if any
expressionList = []
operand = ""
for char in expression:
    if char in "+-*/()":
        if operand != '':
            expressionList.append(operand)
            operand = ''
        expressionList.append(char)
    else:
        operand += char

A: You canno't use a list-comprehension as need to know previous element to split the content. The easier solution I see, is to use a regex
Here (\d+|[-+()/*]) means

*

*\d+ any suite of digits, or (the pipe is OR |)

*any char in -+()/*
import re

expression = "28*35/(21-13)"
values = re.findall(r"(\d+|[-+()/*])", expression)
print(values) # ['28', '*', '35', '/', '(', '21', '-', '13', ')']

Add letters : "([A-Z]+|\d+|[-+()/*])"


text:
Q: Como carregar valores na combobox pelo evento load do form C# Estou tentando através deste código:
private void frmAdicionarProdutos_Load(object sender, EventArgs e)
        {
             string serverName = "localhost";
             string port = "5432";
             string userName = "postgres";
             string password = "adm";
             string databaseName = "GE";
             NpgsqlConnection conn = null;
             string ConnString = null;

             ConnString = String.Format("Server={0};Port={1};User Id={2};Password={3};Database={4};",
                                           serverName, port, userName, password, databaseName);

            using (conn = new NpgsqlConnection(ConnString))
            {
                conn.Open();

                string cmdCarregar = String.Format("SELECT PRODUTOS.ID_PRODUTO, PRODUTOS.NOME, PRODUTOS.PRECO FROM PRODUTOS;");
                using (NpgsqlCommand cmd = new NpgsqlCommand(cmdCarregar, conn))
                {
                    NpgsqlDataReader dr = cmd.ExecuteReader();
                    DataTable dt = new DataTable();
                    dt.Load(dr);

                    cbProdutos.DisplayMember = "nome";
                    cbProdutos.ValueMember = "id_produto";
                    cbProdutos.DataSource = dt;
                    conn.Close();
                }
            }
        }

A principio quero só testar desta forma mesmo, depois implemento chamando a classe do banco.
Este código não mostra nada na ComboBox, creio que esqueci de algo.. Pois gostaria de mostrar: Nome do produto + valor dele (concatenado).

A: Acredito que irá funcionar ao acrescentar o DataBind()
cbProdutos.DataBind();

Verifique se funciona.
private void frmAdicionarProdutos_Load(object sender, EventArgs e)
    {
         string serverName = "localhost";
         string port = "5432";
         string userName = "postgres";
         string password = "adm";
         string databaseName = "GE";
         NpgsqlConnection conn = null;
         string ConnString = null;

         ConnString = String.Format("Server={0};Port={1};User Id={2};Password={3};Database={4};",
                                       serverName, port, userName, password, databaseName);

        using (conn = new NpgsqlConnection(ConnString))
        {
            conn.Open();

            string cmdCarregar = String.Format("SELECT PRODUTOS.ID_PRODUTO, PRODUTOS.NOME, PRODUTOS.PRECO FROM PRODUTOS;");
            using (NpgsqlCommand cmd = new NpgsqlCommand(cmdCarregar, conn))
            {
                NpgsqlDataReader dr = cmd.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(dr);

                cbProdutos.DisplayMember = "nome";
                cbProdutos.ValueMember = "id_produto";
                cbProdutos.DataSource = dt;
                cbProdutos.DataBind();
                conn.Close();
            }
        }
    }

A: Eu só consigo ver uma causa para o problema: você não associou o método frmAdicionarProdutos_Load ao evento Form.Load
this.Load += new System.EventHandler(this.frmAdicionarProdutos_Load);

Testei o seu código aqui e o combo carregou certinho.


text:
Q: Confused in Calling function in angularjs using anchortag i am working on one angularjs project.i have one dropdown in which new email,new contact,new calendar function is there.but these function is working on perticular page only like newmessage function works only on Email page.
i want to call the newMessage function, newAddressbook and new calendar functon from anywhere...
can you help me.
this is my code for that functions.:-
Email
             Contact
            Calendar

A: There may be few details which you might have missed , try embedding controller to the respective div which you are using .
Or you can declare the scope as "root" ('$rootScope') into your model .
Hope this will help .

A: This should work for you.
In your app.js write following code
app.run(['$rootScope', function($rootScope) {
    $rootScope.newMessage = function($event) {
        // do something
    }
    $rootScope.newAddressbook = function($event) {
        // do something
    }
    $rootScope.newCalendar = function($event) {
        // do something
    }
}]);

In Safari and IE "javascript:void(0)" is treated as unsafe so include following code into your app config
app.config(['$compileProvider',function($compileProvider) {
    $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|javascript|chrome-extension):/);
}])

// html code
Email
Contact
Calendar

A:

var app = angular.module('SOGo.Common')
   app.controller('navController', navController);
 app.run(['$rootScope', function($rootScope) {
    $rootScope.newMessage = function($event) {
        // do something
    }
    $rootScope.newAddressbook = function($event) {
        // do something
    }
    $rootScope.newCalendar = function($event) {
        // do something
    }
}]);

});


text:
Q: ValueError: Found input variables with inconsistent numbers of samples: [12600, 4200] In this code I am doing a time series split then using scikit learn I am creating a SVR model for prediction. My code is:
from sklearn import preprocessing as pre
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import TimeSeriesSplit
from sklearn import svm
from sklearn.preprocessing import MinMaxScaler

X_feature = wind_speed

X_feature = X_feature.reshape(-1, 1)## Reshaping array to be 1D from 2D

y_label = Power
y_label = y_label.reshape(-1,1)

timeseries_split = TimeSeriesSplit(n_splits=3)
for train1, test1 in timeseries_split.split(X_feature):

    print("Training data:",train1, "Testing data test:", test1)
train1 = train1.reshape(-1,1)## Reshaping array to be 1D fron 2D
test1 = test1.reshape(-1,1)

timeseries_split = TimeSeriesSplit(n_splits=3)
for train, test in timeseries_split.split(y_label):
    print("Training data_1:",train, "Testing data test_1:", test)

scaler =pre.MinMaxScaler(feature_range=(0,1)).fit(train1)

scaled_wind_speed_train = scaler.transform(train1)
print("scaler", scaled_wind_speed_train)
scaled_wind_speed_test = scaler.transform(test1)

SVR_model = svm.SVR(kernel='rbf',C=100,gamma=.001).fit(scaled_wind_speed_train,train)

y_prediction = SVR_model.predict(y_label)

    print (y_prediction)
    SVR_model.score(scaled_wind_speed_test,train)

The error that I am receiving is:
Training data: [   0    1    2 ... 4197 4198 4199] Testing data test: [4200 4201 4202 ... 8397 8398 8399]
Training data: [   0    1    2 ... 8397 8398 8399] Testing data test: [ 8400  8401  8402 ... 12597 12598 12599]
Training data: [    0     1     2 ... 12597 12598 12599] Testing data test: [12600 12601 12602 ... 16797 16798 16799]
Training data_1: [   0    1    2 ... 4197 4198 4199] Testing data test_1: [4200 4201 4202 ... 8397 8398 8399]
Training data_1: [   0    1    2 ... 8397 8398 8399] Testing data test_1: [ 8400  8401  8402 ... 12597 12598 12599]
Training data_1: [    0     1     2 ... 12597 12598 12599] Testing data test_1: [12600 12601 12602 ... 16797 16798 16799]
scaler [[0.00000000e+00]
 [7.93713787e-05]
 [1.58742757e-04]
 ...
 [9.99841257e-01]
 [9.99920629e-01]
 [1.00000000e+00]]
/home/nbuser/anaconda3_501/lib/python3.6/site-packages/sklearn/utils/validation.py:475: DataConversionWarning: Data with input dtype int64 was converted to float64 by MinMaxScaler.
  warnings.warn(msg, DataConversionWarning)
[6153.41834275 6006.33852041 5997.57462806 ... 6569.44075144 6393.55696288
 6112.57831243]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-53-925646f8c16a> in <module>()
     43
     44 print (y_prediction)
---> 45 SVR_model.score(scaled_wind_speed_test,train)
     46
     47

~/anaconda3_501/lib/python3.6/site-packages/sklearn/base.py in score(self, X, y, sample_weight)
    385         from .metrics import r2_score
    386         return r2_score(y, self.predict(X), sample_weight=sample_weight,
--> 387                         multioutput='variance_weighted')
    388
    389

~/anaconda3_501/lib/python3.6/site-packages/sklearn/metrics/regression.py in r2_score(y_true, y_pred, sample_weight, multioutput)
    528     """
    529     y_type, y_true, y_pred, multioutput = _check_reg_targets(
--> 530         y_true, y_pred, multioutput)
    531
    532     if sample_weight is not None:

~/anaconda3_501/lib/python3.6/site-packages/sklearn/metrics/regression.py in _check_reg_targets(y_true, y_pred, multioutput)
     73
     74     """
---> 75     check_consistent_length(y_true, y_pred)
     76     y_true = check_array(y_true, ensure_2d=False)
     77     y_pred = check_array(y_pred, ensure_2d=False)

~/anaconda3_501/lib/python3.6/site-packages/sklearn/utils/validation.py in check_consistent_length(*arrays)
    202     if len(uniques) > 1:
    203         raise ValueError("Found input variables with inconsistent numbers of"
--> 204                          " samples: %r" % [int(l) for l in lengths])
    205
    206

ValueError: Found input variables with inconsistent numbers of samples: [12600, 4200]

I believe the error my be at : SVR_model.score(scaled_wind_speed_test,train) but I do not know how to resolve this. I have edited the indentations to the exact original but am not sure if any unintentional indentations may be causing an error.

A: The following line should fix the error, assuming I have understood your code correctly
SVR_model.score(scaled_wind_speed_test,test)


text:
Q: Sitecore: hiding fields in content editor? I'm part of a team building a website in Sitecore. We've added a template field whose value we want to hide from content editors.
(the field contains extra CSS classes for a page so we can target styles at specific pages. Not best-practice - we should put it in code - but it has its advantages when the site is in production.)
Any way to do hide specific fields in the Sitecore content editor?
Cheers

A: Ruud's got the ticket, I think. Just to tack a little bit on to his answer, and because I wasn't sure how to do this myself the first time I worked w/ field-level security, select the Columns button in the toolbar to show the Field Read & Field Write options in the Security Editor.

A: You should restrict Field Read access to the field (so not Read access)

A: You could restrict read-access to the field, for the usergroup.

A: To add to the answers already given, you should probably add your settings as a rendering parameter, which will allow you to target renderings/controls more specifically rather than entire "pages", and allow you to set different classes on different components of the page.
Introduction to Sitecore Parameter Templates: Sitecore client configuration deep dive
Introduction to Sitecore Parameter Templates: Making sublayout configuration more intuitive
Use the Sublayout Parameter Helper to get the values in your code behind.


text:
Q: HAML link_to in rails does not apply a class on page load The problem with the below script is that the below code makes releases.content active only after the page refresh not during the first page load . I am new to writing a haml template . Anything evidently wrong that I might be doing here ?
%li.accordion-navigation
      = link_to "Last 10 Releases", "#releases"
      #releases.content.active
        %table.grid
          %thead
            %tr
              %th Build
              %th Deployed at
              %th Report
          %tbody
            - @last_deployments.each do |deployment|
              %tr
                %td= deployment.build
                %td= deployment.deployed_date
                %td
                  = link_to "detail", certification_path(deployment.certification)
    %li.accordion-navigation
      = link_to "Current Bug Status", "#bug_status"
      #bug_status.content.active \w

A: Try below code instead even its same -
%div.content.active{ id: 'releases' }


text:
Q: XCode upgraded to 4.4.1 and now I get errors compiling in stl  Upgraded to XCode 4.4.1 and restarted my machine, recompiled and now get the error below when I try to compile - any suggestions? (It used to compile fine)
(Running on Lion 10.7.4, XCode Version 4.4.1)
#ifndef MYFILE_H
#define MYFILE_H

#include <vector> <-- this line
#include <typeinfo>
#include <string>
#include "assert.h"

using namespace std;

Error message
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.1.sdk/usr/include/c++/4.2.1/vector:69:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.1.sdk/usr/include/c++/4.2.1/bits/stl_vector.h:69:1: error: expected member name or ';' after declaration specifiers
_GLIBCXX_BEGIN_NESTED_NAMESPACE(std, _GLIBCXX_STD)

A: If this problem is still actual, I suggest you should check the following project setup lines:

*

*C++ Language Dialect (mine: Compiler Default)

*C++ Standard Library (mine: Compiler Default)

*Compiler for C/C++/Objective-C (mine: Apple LLVM compiler 4.1)

Not all combinations work and not always the "Compiler Default" is the default. I had some problems, too.
(From the error message it looks for me like you are using libstdc++ instead of libc++ but not the gcc compiler or so. I had similar problem after the update.)


text:
Q: Symbol SDK: Waiting for transaction to complete throws UnhandledPromiseRejectionWarning I am trying to work with SymbolSdk.
I try to get the balance of a list of accounts for a given "mosaic".
I want the code to query the blockchain and resolve promises when the balance has been properly read for every user.
Then I want to join all the promises and display the output of every query at the end.
I got a code sample from symbol documentation showing how to trigger code when the information is received from the blockchain.
However it keeps throwing UnhandledPromiseRejectionWarning and I cannot find a way to catch these errors.
I guess they come from somewhere in accountHttp.getAccountInfo(userAddress) function, but I could not dive any further.
import * as SymbolSdk from 'symbol-sdk';
import { merge, of, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

const nodeUrl = 'http://localhost:3000';

export async function userBalance(userAddress: SymbolSdk.Address, mosaicId: SymbolSdk.MosaicId): Promise<SymbolSdk.UInt64> {
    const repositoryFactory = new SymbolSdk.RepositoryFactoryHttp(nodeUrl);
    const accountHttp = repositoryFactory.createAccountRepository();
    return new Promise<SymbolSdk.UInt64>(async (resolve, reject) => {
        accountHttp.getAccountInfo(userAddress)
            .pipe(catchError((err) => {
                const next = of(err)
                reject(err);
                return next;
            }))
            .subscribe((transactions) => {
                for (const mosaic of transactions.mosaics) {
                    // console.log(userAddress.plain(), mosaic.id.toHex(), mosaic.amount.toString());
                    if (mosaicId.equals(mosaic.id)) {
                        resolve(mosaic.amount);
                    }
                }
                resolve(new SymbolSdk.UInt64([0, 0]));
            },
            (err) => reject(err))
        });
}

if (require.main === module) {
    const promiseList = [];
    const users = ["TCC4A2H6VX4MVBYHBG33JRCL7SI4Z7OKSKUQRNXS", "TBHE2SZCMVGQTDDVSMM6G7KE33IWCXA726WXEV3H", "TBKFTBO4X5EIEHE4LDWVFALJGQU3HCVTAHN2NXCH",
    "TCWUJ4ENXWC4QYJ4N7ESVUHTBXL6IJ4TTPNFME3F", "TC2X5PCGSOEGX6TPZYTZQZYJBOP2QOPDC4VQ5GCK"];
    const rawMosaicId = "0874BB5FEAAA53C4";
    users.forEach(async (user) => {
        const promise = new Promise<[string, SymbolSdk.UInt64, SymbolSdk.MosaicId]>((resolve, reject) => {
            try {
                const address = SymbolSdk.Address.createFromRawAddress(user);
                const mosaicId = new SymbolSdk.MosaicId(rawMosaicId);
                userBalance(address, mosaicId).then((amount) => {
                    resolve([user, amount, mosaicId]);
                }).catch(reject);
            }
            catch (err) {
                reject(err);
            }
        });
        promiseList.push(promise);
    });
    Promise.allSettled(promiseList).then((values) => {
        console.log("Chain over");
        values.forEach((settled) => {
            if (settled.status === "fulfilled")
            {
                const [user, amount, mosaicId] = settled.value;
                console.log(`User ${user}, amount of ${mosaicId.toHex()}: ${amount.toString()}`);
            } else {
                console.log(`Failed to get balance, reason: ${settled.reason}`);
            }
        });
    }).catch(console.error);
}

Here is an example of the output I get:
(node:30500) UnhandledPromiseRejectionWarning: HttpError: HTTP request failed
    at Request._callback (/home/my_user/my_projects/my_symbol_project/node_modules/symbol-openapi-typescript-node-client/dist/api/nodeRoutesApi.js:168:40)
    at Request.self.callback (/home/my_user/my_projects/my_symbol_project/node_modules/request/request.js:185:22)
    at Request.emit (events.js:315:20)
    at Request.<anonymous> (/home/my_user/my_projects/my_symbol_project/node_modules/request/request.js:1154:10)
    at Request.emit (events.js:315:20)
    at IncomingMessage.<anonymous> (/home/my_user/my_projects/my_symbol_project/node_modules/request/request.js:1076:12)
    at Object.onceWrapper (events.js:421:28)
    at IncomingMessage.emit (events.js:327:22)
    at endReadableNT (_stream_readable.js:1225:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:30500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:30500) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:30500) UnhandledPromiseRejectionWarning: HttpError: HTTP request failed
    at Request._callback (/home/my_user/my_projects/my_symbol_project/node_modules/symbol-openapi-typescript-node-client/dist/api/nodeRoutesApi.js:168:40)
    at Request.self.callback (/home/my_user/my_projects/my_symbol_project/node_modules/request/request.js:185:22)
    at Request.emit (events.js:315:20)
    at Request.<anonymous> (/home/my_user/my_projects/my_symbol_project/node_modules/request/request.js:1154:10)
    at Request.emit (events.js:315:20)
    at IncomingMessage.<anonymous> (/home/my_user/my_projects/my_symbol_project/node_modules/request/request.js:1076:12)
    at Object.onceWrapper (events.js:421:28)
    at IncomingMessage.emit (events.js:327:22)
    at endReadableNT (_stream_readable.js:1225:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)
(node:30500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
Chain over
User TCC4A2H6VX4MVBYHBG33JRCL7SI4Z7OKSKUQRNXS, amount of 0874BB5FEAAA53C4:  0
User TBHE2SZCMVGQTDDVSMM6G7KE33IWCXA726WXEV3H, amount of 0874BB5FEAAA53C4:  169489
User TBKFTBO4X5EIEHE4LDWVFALJGQU3HCVTAHN2NXCH, amount of 0874BB5FEAAA53C4:  177213
User TCWUJ4ENXWC4QYJ4N7ESVUHTBXL6IJ4TTPNFME3F, amount of 0874BB5FEAAA53C4:  180560
User TC2X5PCGSOEGX6TPZYTZQZYJBOP2QOPDC4VQ5GCK, amount of 0874BB5FEAAA53C4:  6472738

A:
However it keeps throwing UnhandledPromiseRejectionWarning and I
  cannot find a way to catch these errors.

Here are the examples how to cause this error

window.addEventListener("unhandledrejection", event => {
  console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`);
});

(async _ => {
    throw new Error('from await/async');
})();

new Promise((resolve, reject) => reject('from promise'));

Looks quite trivial, isn't it?
However, It is difficult to spot any issues in your code.
I refactored it a bit and mocked values.

window.module = true;
window.require = {
    main: true
}
window.SymbolSdk = {
    Address: {
        createFromRawAddress: () => ''
    }
}

window.addEventListener("unhandledrejection", event => {
    console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`);
});

window.SymbolSdk.RepositoryFactoryHttp = function() {
        this.createAccountRepository = () => {
            return {
                getAccountInfo: () => Math.random() > 0.5 ? rxjs.throwError('test') : rxjs.of({
                    mosaics: [
                        {
                            id: 1,
                            amount: 10
                        }
                    ]
                })
            }
        }
    },

window.SymbolSdk.MosaicId = function() {
    this.equals = function() {
        return true;
    }
    this.toHex = function() {
        return ''
    }
}

window.SymbolSdk.UInt64 = function() {

}

window.addEventListener("unhandledrejection", event => {
  console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`);
});

if (require.main === module) {
    (async _ => {
    const promiseList = [];
    const userIds = ["TCC4A2H6VX4MVBYHBG33JRCL7SI4Z7OKSKUQRNXS", "TBHE2SZCMVGQTDDVSMM6G7KE33IWCXA726WXEV3H", "TBKFTBO4X5EIEHE4LDWVFALJGQU3HCVTAHN2NXCH",
    "TCWUJ4ENXWC4QYJ4N7ESVUHTBXL6IJ4TTPNFME3F", "TC2X5PCGSOEGX6TPZYTZQZYJBOP2QOPDC4VQ5GCK"];
    const rawMosaicId = "0874BB5FEAAA53C4";

    const users = userIds.map(async (userId) => {
        const address = SymbolSdk.Address.createFromRawAddress(userId);
        const mosaicId = new SymbolSdk.MosaicId(rawMosaicId);
        const amount = await userBalance(address, mosaicId);
        return [userId, amount, mosaicId]
    });

    const values = await Promise.allSettled(users);

    console.log("Chain over");
    for(let settled of values) {
        if (settled.status === "fulfilled")
        {
            const [user, amount, mosaicId] = settled.value;

            console.log(`User ${user}, amount of ${mosaicId.toHex()}: ${amount.toString()}`);
        } else {
            console.log(`Failed to get balance, reason: ${settled.reason}`);
        }
    }
    })();
}

async function userBalance(userAddress, mosaicId) {
    const repositoryFactory = new SymbolSdk.RepositoryFactoryHttp(nodeUrl);
    const accountHttp = repositoryFactory.createAccountRepository();
    let transactions = null;

    transactions = await accountHttp.getAccountInfo(userAddress)
        .toPromise();

    for (const mosaic of transactions.mosaics) {
        if (mosaicId.equals(mosaic.id)) {
            return mosaic.amount;
        }
    }

    return new SymbolSdk.UInt64([0, 0]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>

I think the cause was complex logic inside Promise callback and one can get lost

A: Apparently the problem comes from the multiple creation of accountHttp object from the repositoryFactory.
Moving these two lines up above the global scope so that they are executed only once seem to be fixing the issue.
const repositoryFactory = new SymbolSdk.RepositoryFactoryHttp(nodeUrl);
const accountHttp = repositoryFactory.createAccountRepository();


text:
Q: React-native firebase 5.6.0 Objects are not valid react child I have a question about react native + importing firebase. I got the following error:

React native - objects are not valid as a React child (found: object with keys {$$typeof, type, key, ref, props, _owner, _store})

I looked at issue:
React native - objects are not valid as a React child (found: object with keys {$$typeof, type, key, ref, props, _owner, _store}) But the given solutions didn't work.
I imported the firebase in a seperate component. I changed the import from
import firebase from 'firebase' to import firebase from '@firebase/app'
But this doesn't work somehow! Can someone tell me why and explain how I have to change the code in order to make it work?

Note: Changing the version from firebase from 5.6.0 to 5.0.3 worked, but I want to use the most resent version of firebase, just because I want my app always to be up to date.

dependencies:
"dependencies": {
"firebase": "^5.0.3",
"react": "16.4.1",
"react-native": "0.55.4",
"react-native-action-button": "^2.8.4",
"react-native-elements": "^0.19.1",
"react-native-navigation": "^1.1.483",
"react-native-vector-icons": "^5.0.0",
"react-navigation": "^2.0.2410"
},

the code
import firebase from 'firebase';

// Initialize Firebase
const config = {
    apiKey: "AIzaSyDKGnoKm2lzfDLLuxRU3eDgRKw0agy6vCc",
    authDomain: "turfmeister-37808.firebaseapp.com",
    databaseURL: "https://turfmeister-37808.firebaseio.com",
    projectId: "turfmeister-37808",
    storageBucket: "turfmeister-37808.appspot.com",
    messagingSenderId: "312057996255"
};

firebase.initializeApp(config);

export const f = firebase;
export const database = firebase.database();
export const auth = firebase.auth();
export const storage = firebase.storage();
// These const are not used (yet).
// export const firestore = firebase.firestore();
// export const messaging = firebase.messaging();
// export const functions = firebases.functions();

A: Hi you can use firebase 4.9.1
npm install --save firebase@4.9.1


text:
Q: Default captcha to magento contact us page I am new to magento 1.7. How to add default captcha to contact us form page?
I tried online resources. But it is not useful. Is there any steps to follow, how to create module and assign to contact page. If it so, please send me webpage url, that will be helpful to me.
Can any one please help me?

A: There's a fair amount of steps and code, have a look at this tutorial: http://www.phpfunctionoftheday.com/magento-captcha-contact-form/
Overview of steps taken to incorporate native captcha into contact form page:

*

*Create new module

*Add form label + formId to adminhtml so that the form uses same settings as other pages with forms (register, login, forgotpassword, etc)

*Reference Contact page in local.xml and define child CAPTCHA block there. Also allows you to change width/height of captcha image

*Modify your template (.phtml) file to echo captcha child block

*Define your module's model class location

*Create an observer to validate captcha input

I believe that will help you a lot.
GitHub repo

A: There is a free extension which integrates Magento's native captcha on Contact Us form.
You can find it here: Easy Contact Form Captcha
Also its FREE.

A: This is the link that you are looking for.. http://www.magentocommerce.com/boards/viewthread/298363/ .. Remove the "\\" in the post and add the code as suggested here.. I use this..


text:
Q: Google Cache revalidation I've got a problem with Google Chrome: if i call up an address, google connects two times to the webserver - but only sometimes. I think that has something to do with the cache-control.
Every time that happens, the header HTTP_CACHE_CONTROL is not set in the request. Otherwise it's set to max-age=0.
I don't want Chrome to connect two times to my script - do you know a solution?
I hope you can help me!
Thank You!
EDIT:
maybe it's important to know: in that script there is a 301-redirect.
EDIT 2:
i disabled the "HTTP_CACHE_CONTROL max-age=0" - same problem.
Furthermore: if i call up "http://localhost/admin?foo=bar" there is no GET-variable "foo" in the first request - but in the second there is.
EDIT 3:
If i use javascript instead of the location-header for the redirection, everything works fine.
EDIT 4:
you can test it: download this and unzip it.
Put it in the folder "www/chrome-test/", so you can call up "http://localhost/chrome-test/redirect/".
Everytime you call up "http://localhost/chrome-test/redirect/" you'll be redirected to "http://localhost/chrome-test/example/".
A message generated by the redirect-Script is shown. I use Sessions to "transport" this message.
Then call up "http://localhost/chrome-test/redirect/" again (USE THE ADDRESS BAR AND PRESS RETURN!!!!). Repeat this last step a few times (maybe 20 times).
Sometimes the message "This is a message..." is shown two times - so the redirect-script run two times. But why?

A: Does your icon for the page appears in the Chrome browser?
If not, Chrome looking for favicon.ico, and if your site return 404 page with same code, chrome will do it twice.
<link rel="icon" href="/favicon.ico" sizes="32x32" type="image/png" />


text:
Q: C++: Why need to multiply 1.0, when generate a random number? I use the code as follow to generate a random number between 10000 and 60000.
(int)round(1.0 * rand() / RAND_MAX * 50000 + 10000)
My Question is why 1.0 * rand(), and what is the difference with only rand(), not multiply 0.1?
Your answers are highly appreciated!


text:
Q: Разметка изображений в WPF C# Имеется 10 изображений в окне без рамки WPF формы. Как мне их разместить так, чтобы можно было из другой формы растягивать сразу все изображения сохраняя их пропорции? Во второй форме два слайдера, которыми растягиваем первую форму и что бы изображения так же растягивались?

A: Можно сделать так:
1) Для отображения списка картинок воспользуемся элементом ListBox.
2) Чтобы область просмотра каждой картинки была одинаковой, у элемента ListBox переопределяем ItemsPanel и в качестве панели устанавливаем UniformGrid.
<ListBox>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="2" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

3) Далее определяем шаблон для отображения каждого элемента списка. Так как нам нужно отображать картинки, используем элемент Image. Кроме того, чтобы они растягивались пропорционально, создаем стиль для них в ресурсах окна.
<Window.Resources>
    <!-- Что бы картинки растягивались пропорционально -->
    <Style x:Key="ImageStyle"
           TargetType="Image">
        <Setter Property="Stretch" Value="Uniform" />
    </Style>
</Window.Resources>

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border>
                <Image Source="{Binding Path}"
                               Style="{StaticResource ImageStyle}" />
            </Border>
        </DataTemplate>
</ListBox>

4) Чтобы картинки занимали всю выделенную для них область, устанавливаем свойства ListBox.HorizontalContentAlignment и ListBox.VerticalContentAlignment в значение Stretch, а также отключаем вертикальный и горизонтальный ScrollBar.
<ListBox HorizontalContentAlignment="Stretch"
         VerticalContentAlignment="Stretch"
         ItemsSource="{Binding Images}"
         ScrollViewer.HorizontalScrollBarVisibility="Disabled"
         ScrollViewer.VerticalScrollBarVisibility="Disabled">
</ListBox>

5) Собираем то что сделали вместе.
<Window x:Class="WpfApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.Resources>
        <!-- Что бы картинки растягивались пропорционально -->
        <Style x:Key="ImageStyle"
               TargetType="Image">
            <Setter Property="Stretch" Value="Uniform" />
        </Style>
    </Window.Resources>
    <Grid>
        <ListBox HorizontalContentAlignment="Stretch"
                 VerticalContentAlignment="Stretch"
                 ItemsSource="{Binding Images}"
                 ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                 ScrollViewer.VerticalScrollBarVisibility="Disabled">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border>
                        <Image Source="{Binding Path}"
                               Style="{StaticResource ImageStyle}" />
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <UniformGrid Columns="2" />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
       </ListBox>
    </Grid>
</Window>

Далее во ViewModel заполняем нашу коллекцию картинок данными.
public class MainViewModel : ViewModelBase
{
    public ObservableCollection<MyImg> Images { get; }

    public MainViewModel()
    {
        Images = new ObservableCollection<MyImg>();

        // Заполняем данными коллекцию...
    }
}

// Класс, который представляет нашу картинку.
public class MyImg
{
    public string Path { get; set; }
}