text:
Q: How to get a deleted element in a contenteditable div? I set the root div to contenteditable, and it contains many img and video elements. So when a user edits it and presses backspace to delete one element, How can I get which one the user deleted and get the deleted element's attributes values?

A: If you're interested in the deleted element and its properties, one way is to set a MutationObserver to track modifications to the DOM. Its callback provides changes and affected elements and other userful information.
(new MutationObserver(function(mutations){
    mutations.forEach(function(mutation){
        if(mutation.type=='attributes')
            console.log('Element attributes may have changed, see record:',mutation);
        else
        if(mutation.type=='childList')
            console.log('Child nodes were modified, see record:',mutation,
                        'or removedNodes:',mutation.removedNodes);
});})).observe(document.getElementById('edit'),{
    subtree:true,
    attributes:true,
    childList:true,
    characterData:true,
    characterDataOldValue:true
});

Fiddle: https://jsfiddle.net/0tdm1wwv/2/
Take a look at it in other browsers too, since contenteditable has some interesting flavors.

A:
https://developer.mozilla.org/en-US/docs/Web/Events/input

Register an eventlistener for the event input. If you need IE support you might consider using keypress event instead.
The events might fire before the actual change happend, and keypress might not register paste and cut changes, so you want to handle those events as well (input fires on those too).
Then calculate the difference before and after the edit, analyse it and there you go.

A: https://jsfiddle.net/814j80z2/

            Google

            Google

            Google

Edit: Added onkeydown for elder IE versions.


text:
Q: pass a string array from gatling CSV feeder Is it possible to pass the string array from feeder to post requests.
my csv file :
sourceId,date,keywords,payload
stg_st_record1,"2017-10-10T00:53:42Z",["SAVE_ALL","John","configs"],"Here is some payload1"
stg_st_record2,"2017-10-10T00:53:42Z",["SAVE_ALL","John","configs"],"Here is some payload2"

my gatling script
def PostActionLog():ChainBuilder = {
repeat(times = 10) {
feed(csvPostFeeder)
.exec (http("Post Action logs")
.post("/api/actionlogs")
.body(StringBody("""{"sourceId": "${sourceId}","date": "${date}", "keywords": ${keywords},
 "payload": "${payload}" }"""))
.check(status.is(201)))
 }
}

The error message I am receiving :
byteArraysBody={"sourceId": "stg_st_record2","date": "2017-10-10T00:53:42Z", "keywords":
 ["SAVE_ALL", "payload": "John" }

 HTTP response:
 status=
 415 Unsupported Media Type
 headers=
 Content-Type: application/json; charset=utf-8
 Date: Wed, 25 Mar 2020 17:05:24 GMT
 Server: Kestrel
 Content-Length: 147

Seems like Gatling does not receiving the feeder data correctly, I guess breaking point is the way that string array values pass to gatling post request, Is there a way to achieve this ?

A: The problem is your file is very malformed CSV.
CSV has a spec: RFC4180.

*

*If comma is the separator, if a comma character is inside a value, the value must be wrapped with double quotes.

*If a double quote character is inside a wrapped value, it must be escaped with a preceding double quote.

sourceId,date,keywords,payload
stg_st_record1,"2017-10-10T00:53:42Z","[""SAVE_ALL"",""John"",""configs""]","Here is some payload1"
stg_st_record2,"2017-10-10T00:53:42Z","[""SAVE_ALL"",""John"",""configs""]","Here is some payload2"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need help with boost converter for solenoid I have a pull-solenoid with 32 ohms of resistance. I would like to supply 1 Amp to it with a 1 cell lipo battery: 3.7v nominal, 15 amp draw, 720mah. The power draw only needs to last for a fraction of a second to actuate the piston on the solenoid.
Using pspice I found that charging the solenoid by itself and then opening a switch to force the current through a zener diode forced the voltage to rise to the breakdown voltage of the zener because of flyback effect from the inductor. I then tried to use a TIP102 to allow a path for the 1 amp to flow but have had no luck.
With the TIP102 in the circuit, the voltage on the zener doesn't spike nearly as high and the current into the base is less than before the switch opens and little current enters the collector.
Battery through inductor with switch opening after 1us. When the switch opens, the voltage across the inductor increases until it reaches the breakdown voltage of the zener, in this case 30V. This is shown correct in pspice sim. The theory here is the inductor will create enough voltage potential in the circuit to pull an amp through itself.

When the flyback voltage rises to the breakdown voltage, current enters the base of the TIP102 and a large amount of current can flow into the collector

*

*Edited for more explanation

A: You will need a boost converter that takes your ~3 volt battery and boosts it to 32 volts. Your solenoid will then draw 1 amp from the 32 volt supply.
You should anticipate though, that your battery will not last very long. The boost converter will draw ~10 amps from your battery so its life between charges will be measured in minutes.

A: The classic approach is to charge a capacitor bank.  You will need a big enough bank to provide the 1 amp for enough time to shift the solenoid, which is dependent on the load and the stroke, but usually tens of milliseconds.  There are many IC's available to charge capacitors, designed for flashes in cameras.
Once you have shifted the solenoid, you will require much less current to hold it in place, and probably can use the battery voltage directly.  You will need to experiment with the hold current to see if the battery voltage is sufficient to hold your load once it is pulled in.
If you use this approach, you will greatly increase your battery life, but keep in mind that you will need time to re-charge the capacitor bank between actuations.  If you use the boost converter as @Glenn W9IQ suggests, you can still drop the voltage to a lower level while holding the solenoid closed so you won't kill your battery so quickly, but your battery would have to deliver the 10 amps during pull-in.  By charging the cap bank, you can reduce the instantaneous battery current.


text:
Q: Update Excel object embedded in Word document when opened I have an Excel sheet embedded in a Word document, this object was created from Word and no xlsx file exist for it.
There is only one cell and it has a random number formula that returns a new number each time the document is opened when used in Excel, but does not refresh on Word until I open the embedded object.
Desired behavior would be to refresh when Word document is opened without editing the embedded object.
"Update automatic links at open" is already enabled, the object is not a link.

A: This is not possible - the object needs to be activated in order for it to "be" an Excel object. As far as Word is concerned, an embedded object is like a picture (programmatically a Shape or an InlineShape). Only once it's activated does it have access to its "OLE Server" (the thing that tells it how to behave) - Excel, in this case.
It would be possible to use macro code, an macro named AutoOpen for example, to trigger this.


text:
Q: Removal of a repeated syllable for ease of pronunciation What do you call the removal of a repeated syllable in words for ease of pronunciation?
I read about it once. I think it has to do with alliterative sounds. Not sure if it was deliberate or not.

A: Wikipedia says:

Haplology (from Greek ἁπλόος haplóos "simple" and λόγος lógos, "speech") is defined as the elimination of a syllable when two identical or similar syllables occur consecutively. The phenomenon was identified by American philologist Maurice Bloomfield in the 20th century. Linguists sometimes jokingly refer to the phenomenon as "haplogy".

The Wikipedia article lists a handful of examples, including:

*

*probly (colloquial for probably)

*urine analysis > urinalysis
Now, if you'd excuse me, my grandson is asking for a "bana".


text:
Q: MapBox SDK RouteLeg does not contain any information I am new to Android and MapBox so the solution might be obvious and I am just not seeing it.
I am attempting to implement a turn-by-turn direction type app for Android using MapBox. I have been able to figure out how to create a route, draw a polyline following the route, and have the user follow the polyline and reroute if the user goes off the polyline. But, for some reason when I try to get the next RouteStep from a RouteLeg of the Route, the RouteStep array comes up empty and I have no clue why this is happening. I have posted the section of my code that I am talking about below.
            currentRoute = response.body().getRoutes().get(0);
            Log.d(TAG, "Distance: " + currentRoute.getDistance());
            Toast.makeText(
                    FollowRouteActivity.this,
                    "Route is " + currentRoute.getDistance() + " meters long.",
                    Toast.LENGTH_SHORT).show();

            RouteLeg routeLeg = currentRoute.getLegs().get(0);
            Log.d(TAG, "Next route leg distance: " + routeLeg.getDistance());
            if (routeLeg.getSteps().size() > 0)
                Log.d(TAG, "Next route step distance: " + routeLeg.getSteps().get(0).getDistance());
            else
                Log.d(TAG, "Next route step: No step found");

            drawRoute(currentRoute);

This code snippet always display "Next route step: No step found" to the log.
Thank you for the help in advance!

A: in your directions request, are you setting setSteps() to true? This should result in providing text instructions among other information.


text:
Q: How to assign values with respective variable name? How to create a new column by using loop to assign different number with respective string in data frame? For example:['buy','sell',hold'] to [-1,+1,0] ?
This is my column and i wish to add a new column
enter image description here

A: Use multiple assignment statements. (I'm not sure what you meant by adding a new column, so perhaps you could illustrate the data structure you're thinking about.)
Example:
    >>> d = {'buy': [1], 'sell': [3], 'hold': [5]}
    >>> df = pd.DataFrame(data=d)
    >>> d['buy'],d['sell'],d['hold'] = -1, 1, 0
    >>> print (d)
        {'sell': 1, 'hold': 0, 'buy': -1}

A: It sounds like you're just looking for Pandas' map method:
>>> df = pd.DataFrame({
...     'stock': ['AAAA', 'BBBB', 'CCCC', 'DDDD', 'EEEE', 'FFFF'],
...     'disposition': ['buy', 'buy', 'sell', 'hold', 'buy', 'sell']})
>>> df['change'] = df.disposition.map({'buy': -1, 'sell': +1, 'hold': 0})
>>> df
  disposition stock  change
0         buy  AAAA      -1
1         buy  BBBB      -1
2        sell  CCCC       1
3        hold  DDDD       0
4         buy  EEEE      -1
5        sell  FFFF       1


text:
Q: Attributes of my Time dimension table in star schema I'm building a DW with a star schema modeling. I'll use it for a BI project with pentaho.
I'll have of course a time dimension table. I'll analyze my fact table with differents granularity (day, week, month year, perhaps other)
Should I put one attribute for each of those granularity in my dimension table (so I have one day attribute, one month attribute, one year attribute ...) or should I just write the date and then calculate everything with this date (get the month of the date, the year of the date ...)?
thks a lot for your help

A: In addition to day, week, month, and year,  you should think of other attributes like "company holiday", or "fiscal quarter".  This can be an enormous resource for driving the same query off of different time windows.

A: I would add the attributes of the dates as their own columns. This does not take up significantly more space, and generally gives the query optimiser a better shot at working out how many of the dimension table records match a given criterion (for example, that the day_of_month = 31).

A: Typically, the more, the merrier.
Here is an example I'm using...

ledger@localhost->  select * from date_dimension where date = '2015-12-25';
-[ RECORD 1 ]----+--------------------
date             | 2015-12-25
year             | 2015
month            | 12
monthname        | December
day              | 25
dayofyear        | 359
weekdayname      | Friday
calendarweek     | 52
formatteddate    | 25. 12. 2015
quartal          | Q4
yearquartal      | 2015/Q4
yearmonth        | 2015/12
yearcalendarweek | 2015/52
weekend          | Weekday
americanholiday  | Holiday
austrianholiday  | Holiday
canadianholiday  | Holiday
period           | Christmas season
cwstart          | 2015-12-21
cwend            | 2015-12-27
monthstart       | 2015-12-01
monthend         | 2015-12-31 00:00:00

It's based on queries from the PostgreSQL wiki here...  https://wiki.postgresql.org/wiki/Date_and_Time_dimensions
It would be interesting to augment this with further things:

*

*Religious days (Easter, some of the numerous Saints' days, Ramadan, Jewish festivals, etc)

*Statutory holidays for relevant jurisdictions.  The firm I work for winds up publicizing Irish banking holidays because a number of the customers pay via bank transfers.

*If you operate in France, you might want Lundi, Mardi, Mercredi, ... rather than English day names.

*Daylight Savings Time (as true/false) would be a nice addition.


text:
Q: Objective C Read String with White Spaces I have the following code, but can't get it to display the name at all.
If I have scanf("%s", inputBuffer); i get only the first word. It Breaks at the whitespace. So I changed it to scanf("%[\n]", inputBuffer); but still does not work. Any help please...
> int main (int argc, char *argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int number;
    double payRate, hours, totalPay;
    NSString *name;
    char inputBuffer[200];

    NSLog (@"Enter the number of entries to be processed: ");
    scanf ("%i", &number);

    for(int i = 1; i <= number; i++){
        NSLog (@"Enter the name:");
        scanf("%[\n]", inputBuffer);
        name = [[NSString alloc] initWithUTF8String:inputBuffer];

        NSLog(@"Name: %@", name);
        NSLog(@"Hours:%.2lf", hours);
        NSLog(@"Pay Rate:%.2lf",payRate);
        NSLog(@"Total Pay:%.2lf", totalPay);

    }

A: This works for me:
scanf("%[^\n]", inputBuffer);


text:
Q: High chrony drift with ubuntu 19.04 and intel purley lake (xeon gold 6146) on a newly setup supermicro server using a pair xeon gold 6146 we're having a lot of trouble with time synchronization. The issue is a consistent high drift value:
cat /var/lib/chrony/chrony.drift
        19659.271230             1.281228

The vendor can reproduce the issue on ubuntu 19.04 but not on redhat 7.2, so they believe that ubuntu  does not support purview lake properly. On our end we did the same setup on an older cpu (an ivy bridge i5 3570) and also found it working just fine.
This is the kernel version we use:
uname -r
5.0.0-20-generic

This is how we setup chrony/timemaster
#first make sure that ntpd and ptpd are removed
sudo apt autoremove ntp
sudo apt autoremove ptpd

#chronyd daemon and chronyc client
sudo apt install chrony
#ptp4l, timemaster and phc2sys
sudo apt install linuxptp

# disable apparmor on chrony
sudo ln -s /etc/apparmor.d/usr.sbin.chronyd /etc/apparmor.d/disable/
sudo apparmor_parser -R /etc/apparmor.d/usr.sbin.chronyd

$ cat /etc/linuxptp/timemaster.conf
# Configuration file for timemaster

[ntp_server 2.debian.pool.ntp.org]
#minpoll 4
#maxpoll 4

#[ptp_domain 0]
#interfaces enp59s0f3
#delay 10e-6

[timemaster]
ntp_program chronyd

[chrony.conf]
include /etc/chrony/chrony.conf

#[ntp.conf]
#includefile /etc/ntp.conf

[ptp4l.conf]

[chronyd]
path /usr/sbin/chronyd

#[ntpd]
#path /usr/sbin/ntpd
#options -u ntp:ntp -g

[phc2sys]
path /usr/sbin/phc2sys

[ptp4l]
path /usr/sbin/ptp4l

chronyc output
$ chronyc sources -v
210 Number of sources = 12

  .-- Source mode  '^' = server, '=' = peer, '#' = local clock.
 / .- Source state '*' = current synced, '+' = combined , '-' = not combined,
| /   '?' = unreachable, 'x' = time may be in error, '~' = time too variable.
||                                                 .- xxxx [ yyyy ] +/- zzzz
||      Reachability register (octal) -.           |  xxxx = adjusted offset,
||      Log2(Polling interval) --.      |          |  yyyy = measured offset,
||                                \     |          |  zzzz = estimated error.
||                                 |    |           \
MS Name/IP address         Stratum Poll Reach LastRx Last sample
===============================================================================
^? 10.1.196.1                    0   8     0     -     +0ns[   +0ns] +/-    0ns
^? 10.8.196.1                    0   8     0     -     +0ns[   +0ns] +/-    0ns
^? golem.canonical.com           0   6     0     -     +0ns[   +0ns] +/-    0ns
^+ chilipepper.canonical.com     2   6   377    15  -3140us[-3178us] +/-  124ms
^+ alphyn.canonical.com          2   6   377    14  +4956us[+4956us] +/-  206ms
^+ golem.canonical.com           2   6   377    15  -3504us[-3504us] +/-  118ms
^* 202.29.58.214                 3   6   177    15  -4189us[-4227us] +/-   83ms
^? 2001:3c8:1501:65::1501:11     0   6     0     -     +0ns[   +0ns] +/-    0ns
^? clock.kku.ac.th               0   6     0     -     +0ns[   +0ns] +/-    0ns
^? 2401:5700:100:503::1813       0   6     0     -     +0ns[   +0ns] +/-    0ns
^? ntp1.cpe.rmutt.ac.th          0   6     0     -     +0ns[   +0ns] +/-    0ns
^+ 202.29.58.130                 2   6    37    26  +4447us[+4406us] +/-   48ms


text:
Q: How can I install pflogsumm for Postfix mail log analyzer? I am useing Postfix mail server in Ubuntu 13.04. I want to install pflogsumm in my server and analyze the mail log. How can I do this?

A: to install pflogsumm  in your Ubuntu,  open your terminal with CTRL+ALT+T and type as
sudo apt-get install pflogsumm

Configuration:
We want pflogsumm to be run by a cron job each day and send the report to postmaster@example.com. Therefore we must configure our system that it writes one mail log file for 24 hours, and afterwards starts the next mail log so that we can feed the old mail log to pflogsumm. Therefore we configure logrotate (that's the program that rotates our system's log files) like this: open /etc/logrotate.conf and append the following stanza to it, after the line # system-specific logs may be configured here:
in terminal do as
sudo -i

nano /etc/logrotate.conf

then
/var/log/mail.log {
    missingok
    daily
    rotate 7
    create
    compress
    start 0
}

There's a logrotate script in /etc/cron.daily. This script is called everyday between 06:00h and 07:00h. With the configuration we just made, it will copy the current Postfix log /var/log/mail.log to /var/log/mail.log.0 and compress it, and the compressed file will be /var/log/mail.log.0.gz. It will also create a new, empty /var/log/mail.log to which Postfix can log for the next 24 hours.
Now we create the script /usr/local/sbin/postfix_report.sh which invokes pflogsumm and makes it send the report to postmaster@example.com:
nano /usr/local/sbin/postfix_report.sh

script as
#!/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
gunzip /var/log/mail.log.0.gz

pflogsumm /var/log/mail.log.0 | formail -c -I"Subject: Mail Statistics" -I"From: pflogsumm@localhost" -I"To: postmaster@example.com" -I"Received: from www.example.com ([192.168.0.100])" | sendmail postmaster@example.com

gzip /var/log/mail.log.0
exit 0

We must make this script executable:
chmod 755 /usr/local/sbin/postfix_report.sh

Then we create a cron job which calls the script everyday at 07:00h:
crontab -e

then
 0 7 * * * /usr/local/sbin/postfix_report.sh &> /dev/null

This will send the report to postmaster@example.com. It looks like this in an email client:

For more information & must read : click here


text:
Q: Syntax error: WITH is not valid input in this position So I have this similar request
    WITH customers_in_usa AS (
        SELECT
           customerName, state
        FROM
           customers
        WHERE
           country = 'USA'
    ) SELECT
        customerName
    FROM
        customers_in_usa
    WHERE
        state = 'CA'
    ORDER BY customerName;

But when wrote it I caught an error: 'WITH is not valid input in this position' error_picture. Can you help me to understand what's wrong in this code?

A: WITH customers_in_usa AS is for now invalid MySQL code.
MySQL will support CTE's in the future in MySQL version 8..
You could rewrite your SQL code, that should give the same results.
SELECT
    customerName
  , state
FROM
   customers
WHERE
   country = 'USA'
 AND
   state = 'CA'
ORDER BY
   customerName

A: MySQL doesn't support common table expressions and WITH syntax until version 8.0.1.
Version 8.0 is still not production-ready as I write this (but it's in Release Candidate status, so it'll be GA pretty soon).

Update: MySQL 8.0 released its first GA version 8.0.11 on 2018-04-19.


text:
Q: python plain text regex parsing I need to write a small parser that will extract data from a form.
The data will be posted in a consistent pattern all the time. As follows:
Panakamanana
104412=Trident of Corrupted Waters
104411=Immerseus' Crystalline Eye
104435=Stonetoe's Tormented Treads
104455=Reality Ripper Ring
99716=Chest of the Cursed Protector
104509=Laser Burn Bracers
104531=Haromm's Talisman
99722=Gauntlets of the Cursed Protector
104562=Ring of Restless Energy
104606=Gleaming Eye of the Devilsaur
99725=Helm of the Cursed Protector
99719=Shoulders of the Cursed Protector
104616=Ticking Ebon Detonator
105686=Hellscream's Pig Sticker

The only data I'm interested in is each integer before the = sign. I want to then be able to iterate over these so perhaps putting them in a dict or array or something would be great.

A: Here is one way to get it done:
with open('somefile.txt') as f:
   next(f) # Skips the first line, which doesn't have =
   numbers = [line.split('=')[0] for line in f if len(line.strip())]

print(numbers)

If you want to use regular expressions:
>>> import re
>>> s = "104412=Trident of Corrupted Waters"
>>> re.findall(r'^(\d+)', s)[0]
'104412'

A: Just split the string up using '=' as the delimiter. The most Pythonic way to implement this would be to use a list comprehension:
>>> [int(line.split('=')[0]) for line in your_lines[1:]]
[104412, 104411, ..., 105686]

Where your_lines is a list of the lines demonstrated in your question.

A: You can simply do that as follows:
new_list = [int(line[:line.find('=')]) for line in your_list]

print new_list


text: Q: generalized Noether-Lefschetz Theorem I have always had problems in understanding what people mean when they say "the generalized Theorem of ...". For instance, I seem to understand that there are a few different generazlized Noether-Lefschetz theorems. Can someone list the different versions?


text:
Q: Threads not coming to a halt even when trying to acquire the same lock from the JVM static initialization process In the Java Concurrency in Practice book, it says that
"Static initializers are run by the JVM at class initialization time, after class loading
    but before the class is used by any thread. Because the JVM acquires a lock during initialization [JLS 12.4.2] and
    this lock is acquired by each thread at least once to ensure that the class has been loaded,
    memory writes made during static initialization are automatically visible to all threads."(Goetz 16.2.3)
Idea 1: first interpretation
I first thought that meant that the JVM decides upon seeing some class using the static field, to temporarily have all threads try to acquire the lock used by the static initialization and if that lock was never let go, then it would halt all threads to wait for that lock forever.
Idea 2: possible interpretation that makes more sense especially with how the sample code is behaving
If it was the case that, only after the static field was initialized, then the JVM has all threads try to acquire the lock used by the static initialization this would be fine. The other threads that wasn't the first to use the static field, would be just fine and not halt because it's not waiting on the lock. However, I am not sure if that is the case. Can anyone confirm that idea 2 is the correct interpretation?
Finally here is the program which looks something like this and keeps on printing thread-0 and thread-1
public class StaticBlockAndLineInterpretation {
    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> keepLooping()).start();
        new Thread(() -> keepLooping()).start();
        Thread.sleep(2500);
        int x = AllThreadsStopper.threadStopper;
    }

    static void keepLooping() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {}
            System.out.println("This is thread " + Thread.currentThread().getName());
        }
    }
}

class AllThreadsStopper {
    static int threadStopper;

    static {
        try {
            threadStopper = haltAllThreadsAndNeverReturn();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static int haltAllThreadsAndNeverReturn() throws InterruptedException {
        System.out.println("haltAllThreadsAndNeverReturn called");
        new CountDownLatch(1).await();
        return 0;
    }
}

console output snippet:
    This is thread Thread-0
    This is thread Thread-1
    This is thread Thread-0
    This is thread Thread-1
    haltAllThreadsAndNeverReturn called
    This is thread Thread-0
    This is thread Thread-1
    This is thread Thread-0
    This is thread Thread-1
    This is thread Thread-0 and so forth...

A: The cited section is, of course, about threads using that class, as otherwise, without shared data, there is no need to discuss thread safety.
JLS§12.4.2 describes acquiring the lock as part of the initialization procedure of the class, where threads have to go into the blocked state when they detect that another thread is currently performing the initialization:

For each class or interface C, there is a unique initialization lock
  LC. The mapping from C to LC is left to the discretion of the
  Java Virtual Machine implementation. The procedure for initializing C is then as
  follows:

*

*Synchronize on the initialization lock, LC, for C. This involves waiting until the current thread can acquire LC.

*If the Class object for C indicates that initialization is in progress for C by some other thread, then release LC and block the current thread until informed that the in-progress initialization has completed, at which time repeat this step.

*If the Class object for C indicates that initialization is in progress for C by the current thread, then this must be a recursive request for initialization. Release LC and complete normally.

*If the Class object for C indicates that C has already been initialized, then no further action is required. Release LC and complete normally.

  …

Note that this implies doing nothing if the class turns out to be already initialized (in 4.), but still acquiring and releasing the lock, which is the formal definition of the memory visibility constraint and happens-before relationship which Brian Goetz mentioned.
But being part of the formal definition of class initialization, it only applies to code actually triggering a class initialization, which is specified in JLS §12.4.1., "When Initialization Occurs":

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

*

*T is a class and an instance of T is created.

*A static method declared by T is invoked.

*A static field declared by T is assigned.

*A static field declared by T is used and the field is not a constant variable (§4.12.4).

*T is a top level class (§7.6) and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.

  When a class is initialized, its superclasses are initialized (if they have not been previously initialized),  as well as any superinterfaces
  (§8.1.5) that declare any default methods (§9.4.3) (if they have not been previously initialized).

Since in your case, the two threads are not performing any of the specified actions, not even indirectly, they are not triggering a class initialization, hence, not attempting to acquire the class initialization lock.
You can easily cause blocking of your example's threads by inserting an action from the list, e.g.
static void keepLooping() {
    while (true) {
        try {
            Thread.sleep(1000);
            new AllThreadsStopper();
        } catch (InterruptedException e) {}
        System.out.println("This is thread " + Thread.currentThread().getName());
    }
}

Since creating of an instance of a class triggers the initialization of the class, the threads now get blocked.
For completeness, §12.4.2. also mentions:

An implementation may optimize this procedure by eliding the lock acquisition in step 1 (and release in step 4/5) when it can determine that the initialization of the class has already completed, provided that, in terms of the memory model, all happens-before orderings that would exist if the lock were acquired, still exist when the optimization is performed.

Which is what Brian Goetz' book is about when he says "This technique can be combined with the JVM's lazy class loading to create a lazy initialization technique that does not require synchronization on the common code path". It's very efficient, as threads may access the initialized class without synchronization costs, once the initialization has completed. In your example, where the initialization never completes, this optimization is not possible and threads have to acquire the lock, if they are using the class in terms of JLS §12.4.1.


text:
Q: Imagemagick convert opaque pixels to specific color I would like to batch convert a bundle of PNG files using ImageMagick in aim to change all opaque pixels in each image to specific hexa color.
I tried
for f in *.png; do convert "$f" -colorspace Gray -auto-level "${file%%.png}_gray.png"; done

result of just one image converted where all opaque pixels converted to white
I tried without batching , each command successfully done but always wite pixels.
How could I do to set opaque pixels to #AAA ?
Thanks!

A: When you say opaque pixels, I am not sure if you mean pixels with 100% opacity or pixels with non-zero transparency.
Method 1
So, if we start with this image which is a blue square with a transparent surround and a further blue surround:

Then we can make the non-transparent pixels yellow with:
convert image.png -fill yellow -colorize 100% result.png

You would use '#AAA' in place of yellow.
Method 2
Another way of thinking about it is to set each RGB pixel to 10/16, i.e. A on a hex scale:
convert image.png -channel RGB -fx '10/16' result.png

Method 3
Or you may have mean that if you start with this - which is a gradient from transparent at the top to black with a red border:

then you want all except the fully transparent pixels (near the top) to become #AAA (shown here with yellow instead):
convert start.png -channel A -threshold 1 -channel RGB -fill yellow -colorize 100% result.png


text:
Q: Occasional AngularJS error when directive is compiling I have an AngularJS directive that renders into a custom social share widget.  Out of about 10,000 page views per day, around 1 or 2 of those times, Angular errors out after starting to compile the directive. This leaves the raw HTML partial in the DOM, visible to the user.
I only came to know of this error because it was reported by several users.  I can't reproduce it, but I have devised some informative logging which shows that it is occurring.
Each time this has occurred:

*

*Browser is always Chrome

*OS is Mac or Windows

*Angular starts the compile phase, but fails before starting post link

*Angular reports an error during the compile phase, but the 'exception' object passed to the '$exceptionHandler' service is always null.

*No other JavaScript errors are reported

This error is occurring for some of the same IPs across multiple days.
Has anyone out there had a similar issue?
Edit
Here's my code...
JavaScript:
(function () {

  angular.module('common', []);

  angular.module('common')
    .filter('encodeURIComponent', function () {
      return window.encodeURIComponent;
    });

  function configure($provide) {

    // Pass all Angular errors to Loggly
    $provide.decorator("$exceptionHandler", function ($delegate) {
      return function exceptionHandlerDecorator(exception, cause) {
        $delegate(exception, cause);
        _LTracker.push({
          'error': 'angularError',
          'app': 'shareCounts',
          'err': exception,
          'element': cause
        });
      };
    });

  }

  angular.module('common')
    .config(['$provide', configure]);

  function configure($provide) {

    // Defines available share options as well as behaviors of the share popup windows
    function shareLinksConfig() {
      return {
        'facebook': {
          width: 670,
          height: 200,
          urlBase: 'https://www.facebook.com/sharer/sharer.php?',
          shareParamPre: 'u=',
          msgParamPre: '',
          mediaParamPre: '',
          addParams: ''
        },
        'twitter': {
          width: 550,
          height: 420,
          urlBase: 'https://twitter.com/intent/tweet?',
          shareParamPre: 'url=',
          msgParamPre: '&text=',
          mediaParamPre: ''
        },
        'googlePlus': {
          width: 600,
          height: 600,
          urlBase: 'https://plus.google.com/share?',
          shareParamPre: 'url=',
          msgParamPre: '',
          mediaParamPre: '',
          addParams: ''
        },
        'linkedIn': {
          width: 600,
          height: 400,
          urlBase: 'http://www.linkedin.com/shareArticle?',
          shareParamPre: 'url=',
          msgParamPre: '',
          mediaParamPre: '',
          addParams: '&mini=true'
        },
        'pinterest': {
          width: 750,
          height: 320,
          urlBase: 'https://www.pinterest.com/pin/create/button/?',
          shareParamPre: 'url=',
          msgParamPre: '&description=',
          mediaParamPre: '&media=',
          addParams: ''
        },
        'email': {
          width: 0,
          height: 0,
          urlBase: '',
          shareParamPre: '',
          msgParamPre: '',
          mediaParamPre: '',
          addParams: ''
        }
      };
    }
    $provide.factory('shareLinksConfig', shareLinksConfig);

  }

  angular.module('common')
    .config(['$provide', configure]);

  function ShareLinksController($scope, shareLinksService) {
    sendToLoggly.push("A \"ShareLinksController\" started constructing...");
    sendToLoggly.push("...and the $scope is typeof...");
    sendToLoggly.push(typeof $scope);

    var vm = this;

    vm.share = function ($event, shareVia) {
      if (shareVia !== 'email') {
        $event.preventDefault();
        // console.log($scope.mediaUrl);
        shareLinksService.openPopUp(shareVia, $scope.shareUrl, $scope.shareMsg, $scope.mediaUrl);
      }

      // Tell Google Analytics share link was clicked
      shareLinksService.pushGAEvent($scope.analyticsLocation, shareVia, $scope.shareUrl);
    };

    $scope.shareLinksShown = true; // Initialized to true, but then this gets set to false in the directive's link function if slideIn is true
    vm.toggle = function ($event) {
      $event.preventDefault();
      $scope.shareLinksShown = !$scope.shareLinksShown;
    };

    sendToLoggly.push("...and controller finished constructing.");
  }

  angular.module('common')
    .controller('ShareLinksController', ["$scope", "shareLinksService",
                ShareLinksController]);

  function fuShareLinks($http, shareLinksConfig, testRenderingService) {

    function compile() {

      sendToLoggly.push("A \"fuShareLinks\" directive started compiling...");

      testRenderingService.testShareCounts();

      return function postLink(scope) {
        sendToLoggly.push("A \"fuShareLinks\" directive started postLinking...");

        function Settings(shareVia, slideInDir, slideToggleLabel, colorized, showCounts) {
          var self = this,
            prop,
            splitArray;

          /* --------
             ShareVia
             --------
             Comma separated list of ways to share
             Accepted options are: 'facebook, twitter, googlePlus, linkedIn, pinterest, email' */

          // Copy the properties from the config and initialize to false
          self.shareVia = {};
          for (prop in shareLinksConfig) {
            if (shareLinksConfig.hasOwnProperty(prop)) {
              self.shareVia[prop] = false;
            }
          }
          if (typeof shareVia === 'string') {
            splitArray = shareVia.split(',');
          } else {
            splitArray = [];
          }
          // Check each value of splitArray, if it is in possible share options,
          // set that option to true.
          angular.forEach(splitArray, function (value) {
            // Clean up 'value' a bit by removing spaces
            value = value.trim();
            if (value.length > 0) {
              if (self.shareVia.hasOwnProperty(value)) {
                self.shareVia[value] = true;
              }
            }
          });

          /* --------
             Slide In
             --------
             The slide-in functionality is activated by passing a value to 'slideInDir'.
             Accepted values are 'left' or 'down' (case insensitive)
             The 'slideToggleLabel' can be any string, if empty, it defaults to 'Share'. */
          self.slideIn = {
            direction: '',
            label: 'Share'
          };
          if (typeof slideInDir === 'string') {
            slideInDir = slideInDir.toUpperCase();
          }
          switch (slideInDir) {
          case 'LEFT':
            self.slideIn.direction = 'left';
            break;
          case 'DOWN':
            self.slideIn.direction = 'down';
            break;
          }
          if (typeof slideToggleLabel === 'string') {
            self.slideIn.label = slideToggleLabel;
          }

          /* ---------
             Colorized
             ---------
             'true', 'yes', or 'colorized' (case insensitive) -- results in true
             defaults to false */
          self.colorized = false;
          if (typeof colorized === 'string') {
            colorized = colorized.toUpperCase();
          }
          switch (colorized) {
          case 'TRUE':
            self.colorized = true;
            break;
          case 'YES':
            self.colorized = true;
            break;
          case 'COLORIZED':
            self.colorized = true;
            break;
          }

          /* -----------
             Show Counts
             -----------
             'true', 'yes', or 'show' (case insensitive) -- results in true
             defaults to false */
          self.showCounts = false;
          if (typeof showCounts === 'string') {
            showCounts = showCounts.toUpperCase();
          }
          switch (showCounts) {
          case 'TRUE':
            self.showCounts = true;
            break;
          case 'YES':
            self.showCounts = true;
            break;
          case 'SHOW':
            self.showCounts = true;
            break;
          }

        }

        scope.settings = new Settings(
          scope.shareVia,
          scope.slideInDir,
          scope.slideToggleLabel,
          scope.colorized,
          scope.showCounts
        );
        // Initally hide the share links, if they are set to toggle
        if (scope.settings.slideIn.direction !== '') {
          scope.shareLinksShown = false;
        }

        function ShareCounts(shareVia) {
          var self = this;

          angular.forEach(shareVia, function (value, name) {
            self[name] = 0;
          });

          $http.get(
            '/local/social-share-counts/?url=' +
              encodeURIComponent(scope.shareUrl)
          ).success(function (data) {
            /* Check for share counts in the returned data.

               Must use consistent naming for the social networks
               from shareLinksConfig properties all the way to the
               JSON data containting the counts.

               Expected JSON format:
               {
                "twitter": {
                  "count": 42,
                  "updated": "2015-03-25T15:13:48.355422"
                },
                "facebook": {
                  "count": 120,
                  "updated": "2015-03-25T15:13:47.470778"
                }
               }
            */
            angular.forEach(shareVia, function (value, name) {
              if (data[name] && data[name]["count"]) {
                self[name] = data[name]["count"];
              }
            });
          }).error(function (data, status) {
            sendToLoggly.push("HTTP Response " + status);
          });

        }

        // If showing share counts, get the counts from the specified networks
        if (scope.settings.showCounts) {
          scope.shareCounts = new ShareCounts(scope.settings.shareVia);
        }

        sendToLoggly.push("...and directive finished postLinking.");
      };

      sendToLoggly.push("...and directive finished compiling.");
    }

    return {
      restrict: 'E',
      scope: {
        shareVia: '@',
        shareUrl: '@',
        shareMsg: '@',
        mediaUrl: '@',
        analyticsLocation: '@',
        slideInDir: '@',
        slideToggleLabel: '@',
        colorized: '@',
        showCounts: '@'
      },
      controller: 'ShareLinksController',
      controllerAs: 'shrLnksCtrl',
      templateUrl: '/angular-partials/common.share-links.html',
      compile: compile
    };

  }

  angular.module('common')
    .directive('fuShareLinks', ['$http', 'shareLinksConfig', 'testRenderingService', fuShareLinks])

    .factory('testRenderingService', function () {
      var timerId = null;
      function evalShareRender() {
        var renderError = (-1 < $('em.ng-binding')
          .text()
          .indexOf('{{'));

        if (renderError) {
          console.error('RENDER ERROR');
          _LTracker.push({
            'error': 'rendering',
            'app': 'shareCounts',
            'statusMsgs': sendToLoggly,
            'userAgent': navigator.userAgent
          });
        }
      }
      return {
        testShareCounts: function () {
          if (!timerId) {
            timerId = window.setTimeout(evalShareRender, 5000);
          }
        }
      };
    });

  function shareLinksService(shareLinksConfig) {

    function openPopUp(shareVia, shareUrl, shareMsg, mediaUrl) {
      var width,
        height,
        urlBase,
        shareParamPre,
        msgParamPre,
        mediaParamPre,
        addParams,
        popUpUrl;

      width = shareLinksConfig[shareVia].width;
      height = shareLinksConfig[shareVia].height;

      urlBase = shareLinksConfig[shareVia].urlBase;
      shareParamPre = shareLinksConfig[shareVia].shareParamPre;
      msgParamPre = shareLinksConfig[shareVia].msgParamPre;
      mediaParamPre = shareLinksConfig[shareVia].mediaParamPre;
      addParams = shareLinksConfig[shareVia].addParams;

      popUpUrl = encodeURI(urlBase);
      popUpUrl += encodeURI(shareParamPre);
      popUpUrl += encodeURIComponent(shareUrl);
      if (msgParamPre && shareMsg) {
        popUpUrl += encodeURI(msgParamPre);
        popUpUrl += encodeURIComponent(shareMsg);
      }
      if (mediaParamPre && mediaUrl) {
        popUpUrl += encodeURI(mediaParamPre);
        popUpUrl += encodeURIComponent(mediaUrl);
      }
      popUpUrl += encodeURI(addParams);

      // Open the social share window
      window.open(popUpUrl, '_blank', 'width=' + width + ',height=' + height);
    }

    function pushGAEvent(analyticsLocation, shareVia, shareUrl) {

      function capitalize(firstLetter) {
        return firstLetter.toUpperCase();
      }

      var gaEventAction = shareVia;
      gaEventAction = gaEventAction.replace(/^[a-z]/, capitalize);
      gaEventAction += ' - Clicked';

      _gaq.push([
        '_trackEvent',
        analyticsLocation + ' - SocialShare',
        gaEventAction,
        shareUrl
      ]);
    }

    return {
      openPopUp: openPopUp,
      pushGAEvent: pushGAEvent
    };

  }

  angular.module('common')
    .factory('shareLinksService', ['shareLinksConfig', shareLinksService]);

}());

HTML:

    {{ settings.slideIn.label }}

         0">
          {{ shareCounts.facebook }}

         0">
          {{ shareCounts.twitter }}

         0">
          {{ shareCounts.googlePlus }}

         0">
          {{ shareCounts.linkedIn }}

         0">
          {{ shareCounts.pinterest }}

A: Not had such an issue, but as its so infrequent could you make it reload the page?
Also, do you know about ng-cloak? it can be useful to hide the raw stuff :)
Could it be a race condition?


text:
Q: Calling an object from a class with Default Constructor I'm wondering what a call to an object is supposed to display. I have a class called big_number that has a few different constructors. In another method, I'm declaring an object 'a' using class big_number as follows:
big_number a;

cout << "Default constructor gives " << a << endl;

And my constructor is:
big_number::big_number()
{
    head_ptr = 0;
    tail_ptr = 0;
    positive = false;
    digits = 0;
    base = 10;
}

(Although I'm sure that this constructor is wrong).
The full code of the testing file:
    int main()
{
    int n1, n2;
    unsigned int base;
    string s;

    char choice;
    do
    {
        cout << "Type 'd' to test default constructor" << endl;
        cout << "Type 'i' to test int constructor" << endl;
        cout << "Type 's' to test string constructor" << endl;
        cout << "Type 'a' to test assignment" << endl;
        cout << "Type '>' to test input operator" << endl;
        cout << "Type '=' to test comparison operators" << endl;
        cout << "Type 'q' to quit" << endl;
        cin >> choice;

        if (toupper(choice) == 'D')
        {
            big_number a;
            cout << "Default constructor gives " << a << endl;
        }
//More Code

A: If by "call to an object" you mean your call of the operator<< on the object a with cout as the stream argument: It displays whatever you define it to display (in a member function of big_number or a free function). There is no "default" operator<< for user-defined classes. So, if you define it like
#include <iostream>

struct big_number
{
    template<typename T>
    friend T& operator<< (T& stream, const big_number& bn);
};

template<typename T>
T& operator<<(T& stream, const big_number& bn) {
    return (stream << "Hello World");
}

int main()
{
    big_number a;
    std::cout << a << std::endl;
}

... it will just display "Hello world".
The purpose of making it a friend function is so it can access the private data members of big_number (since you usually want it to display something that depends on the data stored in the object, and not a constant "Hello world"). So, within the operator<< definition, you would probably iterate through the digits in your linked list and push them to the stream (if I understand correctly what you are trying to do).


text:
Q: How do you setup multi-mon support in VirtualBox machine I am a heavy VirtualBox user.  I run VirtualBox on a Windows 7 host and mostly Windox XP guests...but some linux and others as well.
When using my Windowx XP guests, I REALLY miss the multi-monitor support you get when not in a VM.
I would love to be pointed to some step-by-step instructions for getting this to reliably work for my Windows XP guest VMs.
Any thoughts?
Seth

A: If you're using Virtualbox 3.2.x or 4.x, this feature is available out of the box, with no complicated setup. From this question:

Basic Setup:

*

*Power off your virtual machine if it's on.

*From the main VirtualBox window, select your VM and choose Settings.

*Choose display.

*Below "Video Memory" is Monitor Count. Slide it to 2, and adjust 1.
your video memory if VirtualBox
complains.

*Start your guest and perform the standard "Extend the desktop onto 1.
this display" method based on the
Guest OS. (Guest Additions need to 1.
be installed.)

*A second "Oracle VM VirtualBox" window will appear with the second
display. You can resize it however you
want.

A: You could try using Seamless Mode and just place the individual virtualized application windows on your existing multi-monitor setup.

A: You can try the suggestions from this thread (only works with XP guests):
Effectively using Virtualbox with Dual-Monitor-Host
Or (and this the easy way out) simply resize the VirtualBox and span it over two monitors (but do increase the shared video memory).

(View bigger)

A: It looks like multiple monitors are only supported for the VBoxHeadless Frontend. According to the VirtualBox User Manual:

VirtualBox allows the guest to use
  multiple virtual monitors. Up to
  sixty-four virtual monitors are
  supported.
Note:

*

*Multiple monitors currently work only with Windows XP guests, and Guest
  Additions must be installed, as the
  implementation resides in the Guest
  Additions video driver.

*Multiple monitors work only with the VBoxHeadless frontend. You must
  also enable VRDP multiconnection mode
  (see the section called "VRDP multiple
  connections") to access two or more VM
  displays when the guest is using
  multiple monitors.

*The guest video RAM size should be increased when multiple monitors
  are used. The VRAM is shared among the
  virtual monitors so that only part of
  it is available for each one.
  Therefore the available resolutions
  and color depths will be reduced if
  the VRAM size remains the same and
  multiple monitors are enabled.


text:
Q: Formulating posterior predictive distribution from hierarchical model I have been reading a couple related papers using Bayesian inference in hierarchical models1,2,3  but am struggling to bridge the gap in one aspect of the papers. I think the struggle is in relation to the posterior predictive distribution. The model is described as
$$log(y_{i,t}) \sim \mathcal{N}(\beta_{0,i} + \beta_{1,i}a_{i,t} + \eta_t, \sigma_y^2)$$
$$\eta_t \sim \mathcal{N}(\beta_2 x_t, \sigma_{\eta}^2)$$
$$x_t \sim \mathcal{N}(\mu_x, \sigma_x^2)$$
In this case, $y_{i,t}$, $a_{i,t}$, $x_t$ are measured but the goal will be to predict new values of $x_t$ (climate) for which we have measures of $y_{i,t}$ and $a_{i,t}$. They state that the posterior predictive distribution can be sampled from
$$x_t^{(j)} \sim \mathcal{N}\left(\frac{\sigma_{\eta}^{2(j)}\mu_x^{(j)} + \sigma_x^{2(j)}\beta_2^{(j)}\eta_t^{(j)}}{\sigma_{\eta}^{2(j)} + \sigma_x^{2(j)}\beta_2^{2(j)}}, \left[\frac{1}{\sigma_x^{2(j)}} + \frac{\beta_2^{2(j)}}{\sigma_{\eta}^{2(j)}} \right] \right) $$
where $(j)$ represents the $j^{th}$ MCMC sample. I know that the posterior predictive distribution is defined as
$$p(\tilde{x} \mid x) = \int_\theta p(\tilde{x} \mid \theta)p(\theta \mid x)d\theta$$
However, I am unable to get from the model description to the posterior using this equation. Could anyone walk me through the probability/integration steps necessary to come up with this specific posterior predictive distribution?

1. Schofield et al. 2016↩
2. Steinschneider et al. 2017↩
3. Schofield and Barker 2017↩

A: It appears that the stated distribution is for $x_t^{(j)} | \eta_t^{(j)}$ and the random variable $y_{i,t}$ is being ignored for now.  It also appears that the authors are being a bit loose in their notation for the normal distribution, using the variance parameter in some statements and the precision parameter in others.  (I will parameterise with the variance unless otherwise stated.)  To obtain the conditional density we take the joint density kernel and "complete the square" to simplify.  Taking proportionality with respect to the $x$ variable gives:
$$\begin{aligned}
p(x| \eta)
&\equiv p(x_t^{(j)} = x| \eta_t^{(j)} = \eta) \\[12pt]
&\overset{x}{\propto} p(x_t^{(j)} = x, \eta_t^{(j)} = \eta) \\[12pt]
&= p(\eta_t^{(j)} = \eta | x_t^{(j)} = x) \cdot p(x_t^{(j)} = x) \\[12pt]
&= \text{N}(\eta | \beta_2 x, \sigma_\eta^2) \cdot \text{N}(x | \mu_x, \sigma_x^2) \\[6pt]
&\overset{x}{\propto} \exp \bigg( - \frac{1}{2 \sigma_\eta^2} (\eta - \beta_2 x)^2 \bigg) \cdot \exp \bigg( - \frac{1}{2 \sigma_x^2} (x - \mu_x)^2 \bigg) \\[6pt]
&= \exp \bigg( - \frac{1}{2} \bigg[ \frac{1}{\sigma_\eta^2} (\eta - \beta_2 x)^2 + \frac{1}{\sigma_x^2} (x - \mu_x)^2 \bigg] \bigg) \\[6pt]
&= \exp \bigg( - \frac{1}{2} \bigg[ \frac{1}{\sigma_\eta^2} (\eta^2 - 2 \eta \beta_2 x + \beta_2^2 x^2) + \frac{1}{\sigma_x^2} (x^2 - 2 \mu_x x + \mu_x^2) \bigg] \bigg) \\[6pt]
&= \exp \bigg( - \frac{1}{2} \bigg[ \Big( \frac{1}{\sigma_x^2} + \frac{\beta_2^2}{\sigma_\eta^2} \Big) x^2 -2 \Big( \frac{\mu_x}{\sigma_x^2} + \frac{\eta \beta_2}{\sigma_\eta^2} \Big) x + \Big( \frac{\eta^2}{\sigma_\eta^2} + \frac{\mu_x^2}{\sigma_x^2} \Big) \bigg] \bigg) \\[6pt]
&= \exp \bigg( - \frac{1}{2} \Big( \frac{1}{\sigma_x^2} + \frac{\beta_2^2}{\sigma_\eta^2} \Big) \bigg[ x^2 -2 \Big( \frac{\eta \sigma_x^2 \beta_2^2 + \mu_x \sigma_\eta^2}{\sigma_x^2 \beta_2^2 + \sigma_\eta^2} \Big) x + \text{const} \bigg] \bigg) \\[6pt]
&\overset{x}{\propto} \exp \bigg( - \frac{1}{2} \Big( \frac{1}{\sigma_x^2} + \frac{\beta_2^2}{\sigma_\eta^2} \Big) \bigg( x - \frac{\eta \sigma_x^2 \beta_2^2 + \mu_x \sigma_\eta^2}{\sigma_x^2 \beta_2^2 + \sigma_\eta^2} \bigg)^2 \bigg) \\[6pt]
&\overset{x}{\propto} \text{N}\bigg( x \Bigg| \text{Mean} = \frac{\eta \sigma_x^2 \beta_2^2 + \mu_x \sigma_\eta^2}{\sigma_x^2 \beta_2^2 + \sigma_\eta^2}, \text{Precision} = \frac{1}{\sigma_x^2} + \frac{\beta_2^2}{\sigma_\eta^2} \bigg). \\[6pt]
\end{aligned}$$
Thus, the conditional distribution is:
$$x_t^{(j)} | \eta_t^{(j)} \sim \text{N}\bigg(\text{Mean} = \frac{\eta_t^{(j)} \sigma_x^2 \beta_2^2 + \mu_x \sigma_\eta^2}{\sigma_x^2 \beta_2^2 + \sigma_\eta^2}, \text{Precision} = \frac{1}{\sigma_x^2} + \frac{\beta_2^2}{\sigma_\eta^2} \bigg).$$


text:
Q: How do I get rid of this overload error when I extend Express' Request object? I'm trying to extend Express' Request object so that I can access req.user, but I keep running into an overload error. I tried both of these solutions here but they don't work for me.
EDIT: I am using passport.js and jwt
Extend Express Request object using Typescript
Unable to extend Express Request in TypeScript
I have tried extending Express' Request object in different two ways:

*

*Using interface extend. This works (kind of) but I get an overload error so I can't compile using 'tsc':

overload error
// index.d.ts file

import { IUser } from "../models/user";
import { Request } from "express";

export interface IUserRequest extends Request {
  user: IUser; // or any other type
}

*Creating a global namespace. This does not work because I am unable to access the req.user property. I have tried importing { Request } from "express" but this doesn't work for this option because it says Request is declared but never used:

//index.d.ts file

import { IUser } from "../models/user";
// import { Request } from "express"

export {};

declare global {
  namespace Express {
    interface Request {
      user?: IUser;
    }
  }
}

This is my post controller that's trying to access req.user:
export const admin_code_post = [
  body("admin_code", "Wrong code buddy")
    .trim()
    .escape()
    .custom((value: string) => {
      if (value !== process.env.SECRET_CODE) {
        throw new Error("Admin code is incorrect");
      }
      return true;
    }),
  (req: IUserRequest, res: Response, next: NextFunction) => {
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
      res.render("admin_code", {
        title: "Enter Code",
        errors: errors.array(),
        user: req.user,
      });
      return;
    }

    User.findOneAndUpdate(
      { username: req.user?.username }, // issue here if I create a global namespace
      { admin: true },
      (err: Error, user: IUser) => {
        if (err) return next(err);

        res.render("index", {
          title: "Welcome",
          user,
        });
      }
    );
  },
];

Unable to find req.user when using global namespace method
This is my tsconfig.json :
{
    "compilerOptions": {
      "target": "es2016",
      "module": "commonjs",
      "rootDir": "./src",
      "typeRoots": [
        "./node_modules/@types",
        "./types"
      ],
      "sourceMap": true,
      "outDir": "dist",
      "noEmitOnError": true,
      "esModuleInterop": true,
      "forceConsistentCasingInFileNames": true,
      "strict": true,
      "noImplicitAny": true
    },
    "include": ["./src/**/*"],
    "exclude": ["node_modules"],
    "ts-node": {
      "files": true
    },
    "files": [
      "./src/types/index.d.ts"
    ]
  }

What am I doing wrong? Any advice would be appreciated.

A: Your 2nd approach should work with the following changes,
import { IUser } from "../models/user";

// export {}; <-- you don't need this

declare global {
  namespace Express {
    export interface Request { // <-- you have to export the interface
      user?: IUser;
    }
  }
}

Make sure this code is in a *.d.ts file. Please check the documentation to learn more about how namespaces & declaration merging works
UPDATE
Just noticed that you use passport js. If you check the index.d.ts file of the passport js you can find following code lines,
declare global {
    namespace Express {
        // tslint:disable-next-line:no-empty-interface
        interface AuthInfo {}
        // tslint:disable-next-line:no-empty-interface
        interface User {} // <-- empty interface

        interface Request {
            authInfo?: AuthInfo | undefined;
            user?: User | undefined; // <-- using that as the type of req.user

so the one we define won't work. You can try,
const user = req.user as IUser example
or you can change your index.d.ts as,
// see - https://stackoverflow.com/a/63973683/11306028
export {};

declare global {
  namespace Express {
    interface User {
      first_name: string;
      last_name: string;
      username: string;
      email: string;
      admin: boolean;
    }
  }
}


text:
Q: Windows 10 - bring background task into foreground I have a scheduled task that runs an exe in the background. Every once in a while I'm suspicious that the exe isn't running properly but I have no way to see the output since it's hidden and I can only be aware of the process in task manager.
Question
Is it possible to bring a background task to the foreground?

A: Task Scheduler tasks by default cannot interface with the logged-in user
session/desktop.
The isolation rules of scheduled tasks change with each new Windows version,
but do define the task with "Run only when user is logged on".
When this option is selected, your user account should be displayed under
"When running the task, use the following user account:".
With these options, the scheduled task will be able to interface with the
desktop session of the defined user, so it can be brought to the front.
You may undo the above once you no longer wish to see the task's window.

A: In the light of the answer by @harrymc I'm not sure I've understood the question but I'll plough on anyway.
If you have a lot of tasks open (including Task Manager) you can use Alt/Tab to see a list of everything that's running and bring a selected one to the top.

*

*Press and hold Alt
then, whilst still holding
2a. Repeatedly tap and release Tab to cycle through the windows. When you're on the one you want, release Tab and it will come to the top.
or (better)
2b. While hold Alt, tap Tab once and then mouse-click on the one you're interested in. It will come to the front.
or
2c. Examine the thumbnail you are interested in - it will show you the current state of what's running.

You can also experiment with WindowKey  plus Tab.
There are other shortcuts depending on what exactly you are trying to do.


text:
Q: How to get the properties group names in autodesk forge I would like to know is there any way to get the property group names in autodesk forge. I have tried with getProperties() and getBulkProperties() but I cant get the group names. How to achieve this. Thanks in advance.

A: Property group is not named as group in the Forge viewer. It's called category in this case, and can be accessed via the displayCategory. Here is an example:
var selection = viewer.getSelection();
viewer.getProperties( selection[0], function( result ) {
    const props = result.properties;
    for( let i = 0; i < props .length; i++ ) {
        const property = props[i];
        if( property.hidden) return;

        const category = props[i].displayCategory;
        if( category && typeof category === 'string' && category !== '' ) {
            // The property group you want
            console.log( category );
        }
    }
});

BTW, you can see more detail from this blog:https://forge.autodesk.com/cloud_and_mobile/2015/05/adding-custom-meta-properties-to-the-viewer-property-panel.html
Hope this help.


text:
Q: ArrayPHP Notice: Array to string conversion in I'm testing this code because I want to get the value of &posted_data['sample'] from two different variables ($total and $currentcy). Can anyone give me a clue of how to do that? I've been reading about it and testing some codes, but nothing! According to this code, the output shuld be 1000€
This is my code:
$currency = '€';
$wedding_budget = '2000,00';

if(trim(strlen($wedding_budget)) >= '6') {

    $wedding_budget =  preg_replace('/[\.,]/', '', $wedding_budget );

} else {

    $wedding_budget = preg_replace('/\.[0-9]{1,2}$/', '', $wedding_budget);

}

$total = $wedding_budget / 2;
$posted_data['sample'] = compact('total', 'currency');
echo $posted_data['sample'];

A: This will achieve what you want in an easier way
$currency = '€';
$wedding_budget = '2000,00';

$wedding_budget = str_replace(',', '.', $wedding_budget);

$total = $wedding_budget / 2;
$posted_data['sample'] = $total . $currency;
echo $posted_data['sample'];

A: $posted_data['sample']; is an array. You can print by:
echo $posted_data['sample']['total'];
echo $posted_data['sample']['currency'];

Regards


text:
Q: Navigation across multiple sites / code languages with 1 source Scenario:
We have a client who has multiple large sites, a huge number of stakeholders and decision makers which rules out a redevelopment involving all of them at the moment. Some sites are php, some are coldfusion and others are ASP.NET. We are building them a new site with a "TopHat" navigation that will be used across these site to link them together. Google and LinkedIn do something similar (Screenshots attached).
Question:
Is there a common term for this UI element? We invented the term "TopHat" to be able to collectively discuss the element.
Solution:
While googling, I discovered closure templates: http://code.google.com/closure/templates/index.html Would a closure template be a good approach? From what I read I can then notify the devs of each site to include the javascript in their code. Any ideas or feedback would be much appreciated.

A: If you only need JavaScript templates then Google Closure Templates will work for you as you compile the template code to JavaScript functions which will be called with parameters.
On the server side Google Closure Templates lack libraries for the languages you mentioned other than JavaScript and Java.
If you rely on multiple server side languages handling the same templates you can consider Mustache. Mustache 2 should also be able to be compiled to small JavaScript functions per template.
Regarding your solution. If you develope new functionalities you just have to pass the new JavaScript file to your deveopers. But again - only if JavaScript is the only rendering language.


text:
Q: Menu Creation....at the place of Dialog Box
Wanna create menu at the place of delete Dialog,which will contain open,delete,etc like options.Help me acc.ly.
  New to Android and Java. :)

new AlertDialog.Builder(this)
.setTitle("Confirm Restore")
.setMessage("Do you want to restore this File?")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {}

A: See 'Adding a list' at http://developer.android.com/guide/topics/ui/dialogs.html

A: You cant show Menu options (by pressing menu key) when a dialog is visible.


text:
Q: Scons for C# setup question I use Scons from time to time, and I see it's a good tool for building simple C# project.
I guess there should be some modification of Scons for using C#.
Can I get some help on how to do this?

A: You can start with the SCONS C# builder wiki page, and work through issues with people on the SCONS mailing lists.  Some people have already done some work in this area, but it seems it may have fallen off and/or been some time ago.
I would guess that working through things there - and especially looking at what was already done - would be much more fruitful than a single question here, as the vast majority of mainstream c# users use msbuild, nant, psake, or another .net specific tool-chain.


text:
Q: How to get sum of all Map values in javascript? I have map where values are numbers. Is there any way to get the sum of all its values?
Example:
{"key1":6,"key2":5}

Thanks in advance
EDITED: Map example:
Map(2) {23 => 1, 24 => 3}

A: You can simply loop over the Object and sum the values,

const ob = {"key1":6,"key2":5}

let sum = 0;
for (let key in ob) {
  sum += ob[key];
}
console.log(sum);

A concise way could be:

const ob = {"key1":6,"key2":5}

const sum = Object.values(ob).reduce((acc, val) => acc + val, 0);
console.log(sum);

If you have a Map, then you can loop over it and find the sum, maybe like shown below:

const myMap = new Map([[23, 1], [24, 3]]);
let sum = 0;
myMap.forEach((v) => {
  sum += v;
});

console.log(sum)

A: Firstly, this is an object, not a Map. To sum values, you can either use for...in or Object.values().reduce:

const obj = {
  "key1": 6,
  "key2": 5
};

let sum = 0;

for (let prop in obj) {
  sum += obj[prop];
}

console.log(sum);

const obj = {
  "key1": 6,
  "key2": 5
};

const sum = Object.values(obj).reduce((a, c) => a + c, 0);

console.log(sum);


text:
Q: What is the difference in floor function and truncate function? What is the difference between Math.Floor() and Math.Truncate() in .NET?
For example, Math.Floor(4.4) = 4 Math.Truncate(4.4) = 4.

A: These function behave differently for negative numbers.
Math.Truncate(-4.5) = -4
Math.Floor(-4.5) = -5

A: Math.Floor rounds down Math.Ceiling rounds up and Math.Truncate rounds towards zero. Thus, Math.Truncate is like Math.Floor for positive numbers, and like Math.Ceiling for negative numbers.


text:
Q: Mac on starting show black screen with folder icon
I'm on Macbook Air Macos Sierra
I actually deleted the Recovery HD partition. Although I backed up the recovery files in external. Have MacBackup with Time Machine.I was trying to recover space by removing ubuntu OS partition space which I did successfully. But then I end up messing things in the attempt of increasing Macintosh HD CoreStorage Volume.


text:
Q: 1>0 in a field with order relation modern algebrn Just a quick question.In a field, how to prove that 1>0, i don't know how to deal with it if the field has order relation,and if x>y then x+z>y+z

A: You also need to use the other requirement on the order: that if $0\le x$ and $0\le y$, then $0\le xy$. Suppose that $1<0$. Then $0=1+(-1)<0+(-1)=-1$, i.e., $0<-1$. But then $0<(-1)^2=1$, a contradiction.


text:
Q: Is there any networking app for iPhone that can work together with other apps? Is there any networking app for iPhone that can work together with other apps?

A: There is an app called NetworkToolbox for iPhone and iPad which can be integrated with external apps. For example, a remote access app can be used from inside Network Toolbox and vice versa. Network Toolbox can also be started using Safari.
https://itunes.apple.com/us/app/networktoolbox-network-scanning/id651691453?mt=8


text:
Q: Is it possible to include temporary script files to be run by postinst in a Debian package? I want to create a Debian package that runs a few scripts in postinst. These scripts are only needed in postinst (they're just too unwieldy to include in postinst itself).
Is there a standard way to have them included and accessible in the installation process and then discarded, or should I simply put them in /usr/share/package-name/ and run them from there?

I decided to put the scripts in /usr/share/package-name/ and run them there, but I'm still interested in an answer to the question.

A: /usr/share/package-name/ is the way to go; packages are made of control files and content and nothing else.
The really complicated setups like exim4-config, ldap-auth-config and krb5-config get their own packages to hold configuration scripts and semi-generated conffiles. Things like ebox are also in large part configuration generators.


text:
Q: How to install the VS2019 CodeAnalyis tools using vs_BuildTools.exe We're upgrading our build agents from VS2017 to VS2019.  We use CodeAnalysis in our CI pipeline, so we install the CodeAnalysis workload using:
C:\TEMP\vs_buildtools.exe --quiet --wait --norestart --nocache `
    --add Microsoft.VisualStudio.Component.Static.Analysis.Tools

This creates a directory called C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\Microsoft\VisualStudio\v15.0\CodeAnalysis
When I try this with VS2019, I don't get such a directory.  I've checked other possible locations by searching for Microsoft.CodeAnalysis.Targets as well.
The docs seem to say it's in Microsoft.VisualStudio.Workload.VisualStudioExtensionBuildTools, but that doesn't work either.  I've also tried Microsoft.VisualStudio.ComponentGroup.ArchitectureTools.Managed and Microsoft.Component.CodeAnalysis.SDK but no luck.  Anyone know how to install this from the command line?

A: This worked for me
--add Microsoft.VisualStudio.Component.Roslyn.LanguageServices


text:
Q: Open the main app from a iOS Safari Share Extension I have a Safari share extension where I want the ability to open the main app from within the extension. The user is presented with an alert where they have the option to open the app.
func openAppHandler() {
    self.extensionContext?.completeRequest(returningItems: []) { (success) in
        if let url = URL(string: "myapp://...") {
            self.extensionContext?.open(url, completionHandler: nil)
        }
    }
}

The alert appears after the method  didSelectPost() is called, and as you can see it occurs in the background priority completion block for the extension. The open method says in it's docs "In iOS 8, only the Today extension point (used for creating widgets) supports this method." I'm guessing it's still the case that it's still not supported in the Safari Share Extension.
Does anyone know of a way to open my main app from a share extension?

A: I found a solution here. I'm not sure if this is technically ok with Apple, but it works just as I need it to.
@objc func openURL(_ url: URL) {
    return
}

func openContainerApp() {
    var responder: UIResponder? = self as UIResponder
    let selector = #selector(MyViewController.openURL(_:))

    while responder != nil {
        if responder!.responds(to: selector) && responder != self {
            responder!.perform(selector, with: URL(string: "myapp://url")!)
            return
        }
        responder = responder?.next
    }
}


text:
Q: R - Subset dataframe based on a repeated sequence I am trying to subset a data frame based on specific sequence occurring in column v3.
A sample of a dataframe:
v1 <- c(1:20)
v2 <- c(1,1,0,0,1,0,1,1,1,0,1,1,0,0,0,1,1,0,0,0)
v3 <- c(4,4,2,3,2,3,2,4,4,2,3,2,3,3,3,4,4,2,3,3)
my_df <- data.frame(v1,v2,v3)         # creating a dataframe

sample output for my_df
   v1 v2 v3
1   1  1  4
2   2  1  4
3   3  0  2
4   4  0  3
5   5  1  2
6   6  0  3
7   7  1  2
8   8  1  4
9   9  1  4
10 10  0  2
11 11  1  3
12 12  1  2
13 13  0  3
14 14  0  3
15 15  0  3
16 16  1  4
17 17  1  4
18 18  0  2
19 19  0  3
20 20  0  3

The output I am trying to achieve should look like this
1   1  1  4
2   2  1  4
3   3  0  2
8   8  1  4
9   9  1  4
10 10  0  2
16 16  1  4
17 17  1  4
18 18  0  2

So I want to subset my df according to sequence of 4 4 2 in column v3. What I tried so far is:
my_df[which(c(diff(v3))==-2),]

but this only extracts the middle four of the sequence 4 4 2 like
v1 v2 v3
 2  2  1  4
 9  9  1  4
17 17  1  4

Another option I tried:
m = match(v3, c(4,4,2))
> m
 [1]  1  1  3 NA  3 NA  3  1  1  3 NA  3 NA NA NA  1  1  3 NA NA
> my_df[!is.na(m),]
   v1 v2 v3
1   1  1  4
2   2  1  4
3   3  0  2
5   5  1  2
7   7  1  2
8   8  1  4
9   9  1  4
10 10  0  2
12 12  1  2
16 16  1  4
17 17  1  4
18 18  0  2

This output gives me all 4 and 2 but not the sequence 4 4 2 that I want. Any help would be appreciated.
I already achieved this in matlab with for and if loop but I am just wondering how I can solve this in R in a loopless way.

A: We can do this with data.table.  Convert the 'data.frame' to 'data.table' (setDT(my_df)).  Using shift from data.table, we get the next element with type = "lead".  As shift takes a vector of n, we specify n = 0:2, so that we get three columns with the n = 0 corresponds to the original 'v3' column and others 1st and 2nd next values.  Then, paste the elements rowwise (do.call(paste0, ...), check whether it is equal to 442, get the index of TRUE values (which), use rep to replicate the index and add with 0:2 so that we get the index of the three rows for each index.  This can be used to subset the original dataset rows.
library(data.table)
setDT(my_df)[my_df[, rep(which(do.call(paste0, shift(v3, 0:2,
                 type= "lead")) == 442), each = 3) + 0:2]]
#   v1 v2 v3
#1:  1  1  4
#2:  2  1  4
#3:  3  0  2
#4:  8  1  4
#5:  9  1  4
#6: 10  0  2
#7: 16  1  4
#8: 17  1  4
#9: 18  0  2

data
my_df <- structure(list(v1 = 1:20, v2 = c(1L, 1L, 0L, 0L, 1L, 0L, 1L,
1L, 1L, 0L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L), v3 = c(4L,
4L, 2L, 3L, 2L, 3L, 2L, 4L, 4L, 2L, 3L, 2L, 3L, 3L, 3L, 4L, 4L,
2L, 3L, 3L)), .Names = c("v1", "v2", "v3"), class = "data.frame",
row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20"))

A: As long as v3 does not have any missing values and the values of v3 are single characters, you can also use gregexpr to accomplish this as follows
# get the row indices where the pattern 442 starts c(1 , 8, 16)
rowstarts <- unlist(gregexpr("442", paste(my_df$v3, collapse="")))

# extract rows from the data fram
dfNew <- my_df[sort(c(outer(rowstarts, (0:2), "+"))), ]

which returns
dfNew
   v1 v2 v3
1   1  1  4
2   2  1  4
3   3  0  2
8   8  1  4
9   9  1  4
10 10  0  2
16 16  1  4
17 17  1  4
18 18  0  2

paste with the collapse argument turns the vector v3 into a single character string. grexpr then finds the starting position in this string for any "442" subexpression.
The final step subsets the data.frame using the outer function suggested by @alexis-laz's in the comments above.


text:
Q: seperate the cuda host code in .cpp file main.cpp
#include<iostream>
#include "cuda.h"

using namespace std;
void cuda_calculation();

int main()
{
    cuda_calculation();
    return 0;
}

cu.h
void call(int , int ,float*  , int  );

cuda.cpp
#include <stdio.h>
#include <cuda.h>
#include "cu.h"

void cuda_calculation()
{
  float *a_h, *a_d;  // Pointer to host & device arrays
  const int N = 10;  // Number of elements in arrays
  size_t size = N * sizeof(float);
  a_h = (float *)malloc(size);        // Allocate array on host
  cudaMalloc((void **) &a_d, size);   // Allocate array on device
  // Initialize host array and copy it to CUDA device
  for (int i=0; i<N; i++) a_h[i] = (float)i;
  cudaMemcpy(a_d, a_h, size, cudaMemcpyHostToDevice);
  // Do calculation on device:
  int block_size = 4;
  int n_blocks = N/block_size + (N%block_size == 0 ? 0:1);
  void call(n_blocks, block_size,&a_d, N);
  /*square_array <<< n_blocks, block_size >>> (a_d, N);*/
  // Retrieve result from device and store it in host array
  cudaMemcpy(a_h, a_d, sizeof(float)*N, cudaMemcpyDeviceToHost);
  // Print results
  for (int i=0; i<N; i++) printf("%d %f\n", i, a_h[i]);
  // Cleanup
  free(a_h); cudaFree(a_d);
}

cu.cu
#include <stdio.h>
#include "cu.h"
#include <cuda.h>

// Kernel that executes on the CUDA device
__global__ void square_array(float *a, int N)
{
  int idx = blockIdx.x * blockDim.x + threadIdx.x;
  if (idx<N) a[idx] = a[idx] * a[idx];
}

//}

void call(int a,int b,float* c,int d)
{
square_array <<< 3,4 >>> (c,d);
}

I tried to seperate the kernal code and host code in a cpp file, however the following error prevails:
Error    'cudaMemcpy': identifier not found and the other cuda related identifier is not identified.

how to use the cuda related identifier in cpp file and call the kernal functions

A: There are some errors: void cuda_calculation(); needs to be visible to main.cpp through a header file (cu.h).
Also make sure to compile your .cu files with nvcc and NOT as a standard C++ file. Use CUDA compilation rules to make this process easy (installed by default as part of CUDA toolkit)

A: after a long trial ,I came with the proper output,
to include the cuda identifier in the cpp files we not only need to include cuda.h but also we need to include cuda_runtime.h as
cuda.cpp as
#include <stdio.h>
#include <cuda.h>
#include<cuda_runtime.h>

#include "cu.h"
#include "cud.h"

//void call(int , int ,float * , int  );

void cuda_calculation()
{
  float *a_h, *a_d;  // Pointer to host & device arrays
  const int N = 10;  // Number of elements in arrays
  size_t size = N * sizeof(float);
  a_h = (float *)malloc(size);        // Allocate array on host
  cudaMalloc((void **) &a_d, size);   // Allocate array on device
  // Initialize host array and copy it to CUDA device
  for (int i=0; i<N; i++) a_h[i] = (float)i;
  cudaMemcpy(a_d, a_h, size, cudaMemcpyHostToDevice);
  // Do calculation on device:
  int block_size = 4;
  int n_blocks = N/block_size + (N%block_size == 0 ? 0:1);
   call(n_blocks, block_size,a_d, N);
  /*square_array <<< n_blocks, block_size >>> (a_d, N);*/
  // Retrieve result from device and store it in host array
  cudaMemcpy(a_h, a_d, sizeof(float)*N, cudaMemcpyDeviceToHost);
  // Print results
  for (int i=0; i<N; i++) printf("%d %f\n", i, a_h[i]);
  // Cleanup
  free(a_h);
  cudaFree(a_d);
}

so the others files are
main.cpp
#include<iostream>
#include "cud.h"

using namespace std;

int main()
{
    cuda_calculation();
    return 0;
}

cud.h
void cuda_calculation();

cu.h
void call(int , int ,float*  , int  );

cu.cu
#include <stdio.h>
#include "cu.h"
#include <cuda.h>

// Kernel that executes on the CUDA device
__global__ void square_array(float *a, int N)
{
  int idx = blockIdx.x * blockDim.x + threadIdx.x;
  if (idx<N) a[idx] = a[idx] * a[idx];
}

//}

void call(int a,int b,float* c,int d)
{
square_array <<< 3,4 >>> (c,d);
}


text:
Q: Create self extracting archive with autorun on linux for windows platform Our application is distributed as a zip file, with a small bat/shell script that the user runs after extracting the archive to install the application. This zip file is currently created via mavens assembly plugin.
The zip file we distribute contains a lib folder with an executable jar, as well as all the files we need as part off the deployment off the actual application.
What we want is a self extracting zip-file that executes that contained bat file after the zip file has been extracted. And this should be created as a part off the build process.
I have read creating-a-self-extracting-zip-archive-on-a-linux-box, and can do that. But I don't see anywhere how to also execute a bat file within the extracted archive when it's done.
I have found winzip self-extractor, but I would prefer something that can be run on any platform. The build server and some developers use linux. I also found some VB code which leads me to believe that there might be some autorun properties on zip files.

A: Did you consider using IzPack (and the IzPack Maven Plugin) to generate a cross-platform installer?

A: The previous replier suggested lzpack, it's documentation contains the following pointer:
""The 7-Zip project (see http://www.7-zip.org/) provides a so-called SFX for installers, i.e., an image that can be use to create self-extracting Windows executables. Once its content has been extracted, such a self-extracting executable can launch an executable or a file. In the later case, it is assumed that there exists an association between a file extension and a software component.""
7-zip is cross platform, although I haven't tried whether you can build sfx files for windows on linux.

A: The 7zip manpage says you can do this.

EXAMPLE 2
       7z a -sfx archive.exe dir1
              add all files from directory "dir1" to  SFX  archive
              archive.exe  (Remark  :  SFX  archive  MUST end with
              ".exe")

A: While it's a bit late:
We just released a Maven plugin that can do this (docs at https://zephyr.sunshower.io/site/).  It's free, open-source, and permissively licensed.
We bundle a JRE with our application using this plugin, then launch an IzPack installer with that JRE.  It also supports code-signing, which we expect to have documented within the week.


text:
Q: Batch UPDATE not working We are updating multiple cells using batch UPDATE in Google Spreadsheets. In the recent days, we see that some rows are not updated for some of our users for a a few days and then works normally. I will explain the use-case exactly.
For example, in a sheet, content would get added upto 71 rows(this can be any number. 71 is used as an example) by Google Sheets batch update and we try updating 72nd row but it doesn't update and we do not get any exception. 72nd row will be empty and this won't get updated even if we try multiple times. But, it will work if we try to add some content above 73rd row. It may again fail somewhere in 156th row (randomly). After a few days if we try to add content in 72nd row it would work normally.
Please help us troubleshoot this issue. This is the code we are using,
// Prepare the update
CellFeed batchRequest = new CellFeed();
    for (CellInfo cellAddr : cellAddrs) {
         CellEntry batchEntry = new CellEntry(cellAddr.row, cellAddr.col, cellAddr.idString);
          batchEntry.setId(String.format("%s/%s", worksheet.getCellFeedUrl().toString(), cellAddr.idString));
          BatchUtils.setBatchId(batchEntry, cellAddr.idString);
          BatchUtils.setBatchOperationType(batchEntry, BatchOperationType.UPDATE);
          batchRequest.getEntries().add(batchEntry);

    }
// Submit the update
CellFeed cellfeed = service.getFeed(cellFeedUrl, CellFeed.class);
    Link batchLink = cellfeed.getLink(Link.Rel.FEED_BATCH, Link.Type.ATOM);
    URL batchUrl = new URL(batchLink.getHref());
    service.setHeader("If-Match", "*");
    CellFeed batchResponse = service.batch(batchUrl, batchRequest);
    service.setHeader("If-Match", "*");


text:
Q: join/leave multicast group using libpcap I need to receive a multicast stream but filter incoming packets by source MAC address on CentOS 5.5.
I'm planning to use libpcap library.
Is it possible to join/leave multicast group using libpcap?
If yes, how to do that?
Thanks

A: Sure, just construct and send the appropriate IGMP packets.

A: 1.Create dummy socket: sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
2.Bind it: rc = bind(sd, (sockaddr*) &addr, sizeof(sockaddr_in));
3.Join multicast group:
ip_mreq mreq;
mreq.imr_interface.s_addr = htonl(InterfaceIp);
mreq.imr_multiaddr.s_addr = htonl(DestIp);
if (setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
  close(sd);
  // Error handle...
}

Don't send or receive packets using dummy socket
4.open pcap using pcap_open_live()
The general idea is use regular socket in order to "tell" kernel to send IGMP join packet, and after use pcap in order to capture packets.


text:
Q: How do I make my navbar expand/extend the entire page? I have purchased the following wordpress theme: http://themeforest.net/item/healthpress-health-and-medical-wordpress-theme/full_screen_preview/3138064
I need to make the navbar extend along the entire width of page, can someone help? Here's an image to show what i'm trying to do and Here's the CSS code for the navbar.
http://i.stack.imgur.com/ZLdsF.jpg
#header .main-nav {
                    height: 21px;
                    width: 100%;
                    padding: 0px 0px 20px 0px;
                    margin-top: 90px;
                    background-color:#46a1b4;
                    background-clip: padding-box;
                    -moz-background-clip: padding-box;
                    -webkit-background-clip: padding;
                    border-radius: 3px;
                    -moz-border-radius: 3px;
                    -webkit-border-radius: 3px;
                    background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255,.1)), to(rgba(0,0,0,0))); /* Saf4+, Chrome */
                    background-image: -webkit-linear-gradient(top, rgba(255,255,255,.1), rgba(0,0,0,0)); /* Chrome 10+, Saf5.1+ */
                    background-image:    -moz-linear-gradient(top, rgba(255,255,255,.1), rgba(0,0,0,0)); /* FF3.6 */
                    background-image:     -ms-linear-gradient(top, rgba(255,255,255,.1), rgba(0,0,0,0)); /* IE10 */
                    background-image:      -o-linear-gradient(top, rgba(255,255,255,.1), rgba(0,0,0,0)); /* Opera 11.10+ */
                    background-image:         linear-gradient(top, rgba(255,255,255,.1), rgba(0,0,0,0));
}
.ie7 #header .main-nav{ z-index:9600; }
.page-template-template-home-with-sidebar-php #header .main-nav,
.page-template-template-home-php #header .main-nav{ background-clip: padding-box; -moz-background-clip: padding-box; -webkit-background-clip: padding; position: absolute; left: 0px; bottom: 0px; border-radius: 3px 3px 0px 0px; -moz-border-radius: 3px 3px 0px 0px; -webkit-border-radius: 3px 3px 0px 0px; }
#header .main-nav > ul { float: left; }
.ie7 #header .main-nav > ul { z-index:9700; }
#header .main-nav > ul > li { float: left; border-right: 1px solid #54aec2; position: relative; }
#header .main-nav > ul > li:first-child { border-top-left-radius: 3px; -moz-border-radius-topleft: 3px; -webkit-border-top-left-radius: 3px; }
#header .main-nav > ul > li:last-child { border: none; }
#header .main-nav ul li a { display: inline-block; padding: 0px 20px; font-size: 13px; line-height: 41px; text-align: center; color: #fff; text-shadow: 1px 1px 0px #20606d; }
#header .main-nav ul li:hover { background-color: #377f8f; background-clip: padding-box; -moz-background-clip: padding-box; }
#header .main-nav ul li ul { display: none; width: 220px; padding: 12px 0px; background-color: #377f8f; position: absolute; top: 41px; left: 0px; z-index: 8899; border-bottom-left-radius: 3px; -moz-border-radius-bottomleft: 3px; -webkit-border-bottom-left-radius: 3px; border-bottom-right-radius: 3px; -moz-border-radius-bottomright: 3px; -webkit-border-bottom-right-radius: 3px; }
.ie7 #header .main-nav ul li ul{ z-index:9800; }
#header .main-nav ul li ul li { width: 196px; height: 34px; padding: 0px 12px; position: relative; }
#header .main-nav ul li ul li a { display: inline-block; line-height: 34px; padding: 0px 9px;  border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; }
#header .main-nav ul li ul li:hover { background-color: #2c6774; }
#header .main-nav ul li ul li ul { top: -12px; left: 220px; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; }
.ie7 #header .main-nav ul li ul li ul { z-index:9900; }
#header .main-nav .responsive-nav { display: none; width: 100%; margin:10px auto 0px; padding:5px; border:1px solid #CCC; }

Any help will be highly appreciated.

A: This will do the trick.
#header {
width: 100%;
height: 150px;
margin: 0px auto;
position: relative;
}

A: The width of the nav bar is set to be 100%, but it is contained within the header tag which has a width of 980px. The only solution via CSS overrides would be to change the width of the header tag to be 100%, which would impact the layout of the entire top portion of your website.
I recommend putting your overrides in a child theme.
https://codex.wordpress.org/Child_Themes


text:
Q: Generate URL inside a Controller in ASP.NET MVC Is there a way to generate URL inside a controller? I want to do the following inside a controller instead of a view.
<% =Url.Action("Validate", "Home", New With {.ValidID = ID})%>

A: Just remove the "Bee-stings."
Something like:
url = Url.Action("Validate", "Home", New With {.ValidID = ID})

A: Yes, as long as your controller inherits from Controller (which it must in order to work as an MVC controller), you can use the same syntax without the <%= %>.
Dim url = Url.Action("myAction", "myController", New With { ... })

alternatively if you reference the MVCContrib DLL, you will have access to strongly typed helpers, and be able to do something like:
Dim url = Url.Action(Of myController)(function(a) a.myAction(ID))

my VB coding days are dated, so forgive me if the syntax is a bit fudged


text:
Q: How can I prepare arguments for NSTask from UI items I have a Cocoa app which user is allowed to execute shell commands (just like using Terminal) by entering commands in UI items like NSTextBox. The app allows has a few predetermined parameters which will be converted to certain characters inside the app.
The app also allows multithreads in which a few commands can be run at the same time.
The challenge I am facing now is to let the user enter the commands as it is in Terminal with all the spaces and etc. I have difficulty breaking down what user enters to be NSArray element to be the arguments to be fed to NSTask. For example, there are some paths or parameters which has spaces in between, for e.g.
/users/Application Support/testFolder/ or
'test - b'
What I am doing now is I have fixed number of NSTextBoxes and each NSTextBox allows only 1 parameter. 1 other issue is if certain command has number of arguments less than my total NSTextBoxes, I have to give "" to the argument(s) and hence, the command may not be executed correctly.
I want to make it more flexible for user to enter as it is. Then, my app is able to handle the characters and run the user-entered command using NSTask.
....
paramArray = [cmdParam componentsSeparatedByString:@","];

NSString *launchPath = [paramArray objectAtIndex:0];

if ([launchPath rangeOfString:@"\""].location == NSNotFound) {
    int nLineNo = [launchPath integerValue];
    launchPath = [self cmdReading:nLineNo uutIndex:nUut];
}
else {
    launchPath = [launchPath stringByReplacingOccurrencesOfString:@"\"" withString:@""];
}

NSString *param1 = [paramArray objectAtIndex:1];

if ([param1 rangeOfString:@"\""].location == NSNotFound) {
    if ([param1 caseInsensitiveCompare:@"UUT_NUMBER"] == NSOrderedSame) {
        param1 = [NSString stringWithFormat:@"UUT%d", nUut+1];
    }
    else if ([param1 caseInsensitiveCompare:@"GET_UUT_NUMBER"] == NSOrderedSame) {
        param1 = [NSString stringWithFormat:@"%d", nUut+1];
    }
    else if ([param1 length] == 0) {
        param1 = @"";
    }
    else {
        int nLineNo = [param1 integerValue];
        param1 = [self cmdReading:nLineNo uutIndex:nUut];
    }
}
else {
    param1 = [param1 stringByReplacingOccurrencesOfString:@"\"" withString:@""];
}

NSString *param2 = [paramArray objectAtIndex:2];

if ([param2 rangeOfString:@"\""].location == NSNotFound) {
    if ([param2 caseInsensitiveCompare:@"UUT_NUMBER"] == NSOrderedSame) {
        param2 = [NSString stringWithFormat:@"UUT%d", nUut+1];
    }
    else if ([param2 caseInsensitiveCompare:@"GET_UUT_NUMBER"] == NSOrderedSame) {
        param2 = [NSString stringWithFormat:@"%d", nUut+1];
    }
    else if ([param2 length] == 0) {
        param2 = @"";
    }
    else {
        int nLineNo = [param2 integerValue];
        param2 = [self cmdReading:nLineNo uutIndex:nUut];
 }
    }
    else {
        param2 = [param2 stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    }

    NSString *param3 = [paramArray objectAtIndex:3];

    if ([param3 rangeOfString:@"\""].location == NSNotFound) {
        if ([param3 caseInsensitiveCompare:@"UUT_NUMBER"] == NSOrderedSame) {
       param3 = [NSString stringWithFormat:@"UUT%d", nUut+1];

    }
    else if ([param3 caseInsensitiveCompare:@"GET_UUT_NUMBER"] == NSOrderedSame) {
        param3 = [NSString stringWithFormat:@"%d", nUut+1];
    }
    else if ([param3 length] == 0) {
        param3 = @"";
    }
    else {
        int nLineNo = [param3 integerValue];
        param3 = [self cmdReading:nLineNo uutIndex:nUut];
    }
}
else {
    param3 = [param3 stringByReplacingOccurrencesOfString:@"\"" withString:@""];
}

NSString *param4 = [paramArray objectAtIndex:4];

if ([param4 rangeOfString:@"\""].location == NSNotFound) {
    if ([param4 caseInsensitiveCompare:@"UUT_NUMBER"] == NSOrderedSame) {
        param4 = [NSString stringWithFormat:@"UUT%d", nUut+1];
    }
    else if ([param4 caseInsensitiveCompare:@"GET_UUT_NUMBER"] == NSOrderedSame) {
        param4 = [NSString stringWithFormat:@"%d", nUut+1];
    }
    else if ([param4 length] == 0) {
        param4 = @"";
    }
    else {
        int nLineNo = [param4 integerValue];
        param4 = [self cmdReading:nLineNo uutIndex:nUut];
    }
}
else {
    param4 = [param4 stringByReplacingOccurrencesOfString:@"\"" withString:@""];
}

NSString *param5 = [paramArray objectAtIndex:5];

if ([param5 rangeOfString:@"\""].location == NSNotFound) {
    if ([param5 caseInsensitiveCompare:@"UUT_NUMBER"] == NSOrderedSame) {
        param5 = [NSString stringWithFormat:@"UUT%d", nUut+1];
    }
    else if ([param5 caseInsensitiveCompare:@"GET_UUT_NUMBER"] == NSOrderedSame) {
        param5 = [NSString stringWithFormat:@"%d", nUut+1];
    }
    else if ([param5 length] == 0) {
        param5 = @"";
    }
    else {
        int nLineNo = [param5 integerValue];
        param5 = [self cmdReading:nLineNo uutIndex:nUut];
    }
}
else {
    param5 = [param5 stringByReplacingOccurrencesOfString:@"\"" withString:@""];
}

NSString *param6 = [paramArray objectAtIndex:6];

if ([param6 rangeOfString:@"\""].location == NSNotFound) {
    if ([param6 caseInsensitiveCompare:@"UUT_NUMBER"] == NSOrderedSame) {
        param6 = [NSString stringWithFormat:@"UUT%d", nUut+1];
    }
    else if ([param6 caseInsensitiveCompare:@"GET_UUT_NUMBER"] == NSOrderedSame) {
        param6 = [NSString stringWithFormat:@"%d", nUut+1];
    }
    else if ([param6 length] == 0) {
        param6 = @"";
    }
    else {
        int nLineNo = [param6 integerValue];
        param6 = [self cmdReading:nLineNo uutIndex:nUut];

    }
}
else {
    param6 = [param6 stringByReplacingOccurrencesOfString:@"\"" withString:@""];
}

NSString *param7 = [paramArray objectAtIndex:7];

if ([param7 rangeOfString:@"\""].location == NSNotFound) {
    if ([param7 caseInsensitiveCompare:@"UUT_NUMBER"] == NSOrderedSame) {
        param7 = [NSString stringWithFormat:@"UUT%d", nUut+1];
    }
    else if ([param7 caseInsensitiveCompare:@"GET_UUT_NUMBER"] == NSOrderedSame) {
        param7 = [NSString stringWithFormat:@"%d", nUut+1];
    }
    else if ([param7 length] == 0) {
        param7 = @"";
    }
    else {
        int nLineNo = [param7 integerValue];
        param7 = [self cmdReading:nLineNo uutIndex:nUut];
    }
}
else {
    param7 = [param7 stringByReplacingOccurrencesOfString:@"\"" withString:@""];
}

    NSLog(@"_Terminal_Command for UUT:%d, launchPath=%@", nUut+1, launchPath);
    NSLog(@"_Terminal_Command for UUT:%d, param1=%@", nUut+1, param1);
    NSLog(@"_Terminal_Command for UUT:%d, param2=%@", nUut+1, param2);
    NSLog(@"_Terminal_Command for UUT:%d, param3=%@", nUut+1, param3);
    NSLog(@"_Terminal_Command for UUT:%d, param4=%@", nUut+1, param4);
    NSLog(@"_Terminal_Command for UUT:%d, param5=%@", nUut+1, param5);
    NSLog(@"_Terminal_Command for UUT:%d, param6=%@", nUut+1, param6);
    NSLog(@"_Terminal_Command for UUT:%d, param7=%@", nUut+1, param7);

    NSTask* task = [NSTask new];

    [task setLaunchPath:launchPath];
    [task setArguments:[NSArray arrayWithObjects:param1,
                                param2, param3,
                                param4, param5,
                                param6, param7, nil]];

...