Q: Replace all characters in a regex match with the same character in Vim I have a regex to replace a certain pattern with a certain string, where the string is built dynamically by repeating a certain character as many times as there are characters in the match.
For example, say I have the following substitution command:
%s/hello/-----/g

However, I would like to do something like this instead:
%s/hello/-{5}/g

where the non-existing notation -{5} would stand for the dash character repeated five times.
Is there a way to do this?
Ultimately, I'd like to achieve something like this:
%s/(hello)*/-{\=strlen(\0)}/g

which would replace any instance of a string of only hellos with the string consisting of the dash character repeated the number of times equal to the length of the matched string.

A: As an alternative to using the :substitute command (the usage of
which is already covered in @Peter’s answer), I can suggest automating
the editing commands for performing the replacement by means of
a self-referring macro.
A straightforward way of overwriting occurrences of the search pattern
with a certain character by hand would the following sequence of
Normal-mode commands.

*

*Search for the start of the next occurrence.
/\(hello\)\+

*Select matching text till the end.
v//e

*Replace selected text.
r-

*Repeat from step 1.
Thus, to automate this routine, one can run the command
:let[@/,@s]=['\(hello\)\+',"//\rv//e\rr-@s"]

and execute the contents of that s register starting from the
beginning of the buffer (or anther appropriate location) by
gg@s

A: %s/\v(hello)*/\=repeat('-',strlen(submatch(0)))/g


Q: Create menu in main layout like in action bar I want to know is it possible to create menu like this?

A: Most likely, your screenshot is of an ExpandableListView, or possibly a RecyclerView that uses a library to add expandable contents.

A: Yes, and it's called Expandable List View.


Q: Converting object to Integer equals null I am trying to convert an object from an object to an integer in java. These are the results I get with the following methods:
Object intObject = 50;
intObject: 50
intObject.toString(): 50
Integer.getInteger(intObject.toString()): null

I have no idea why I would get a null when converting the string of the object to an integer.
Here is the code that I am using:
    final Object temp = mCloudEntity.get(SaveAndLoadManager.TAG_TEST_INT);
    Log.i(TAG, "intObject: " + temp );
    Log.i(TAG, "intObject.toString(): " + temp.toString());
    Log.i(TAG, "Integer.getInteger(intObject.toString()): " + Integer.getInteger(temp.toString()));

A: You should use
// Parses the string argument as a signed decimal integer
Integer.parseInt(intObject.toString());

instead of
// Determines the integer value of the system property with the specified name.
// (Hint: Not what you want)
Integer.getInteger(...)


Q: How to SELECT with several conditions? (WHERE ... AND ... IN (...)) For example: in my database I have 3 tables: COMPANY, COUPON and COMPANY_COUPON.
COMPANY table has fields: ID and NAME, COUPON table has: ID, TITLE and TYPE, COMPANY_COUPON table has: ID of the COMPANies and ID of the COUPONs that they own.
So, in java to get all coupons of the company I use command:
SELECT coupon_id FROM company_coupon WHERE company_id = ?

And put it into Collection.
But I need something to get all coupons of the company by the type,
something like:
SELECT * FROM company_coupon WHERE company_id = 1 AND coupon_id = (SELECT * FROM coupon WHERE type = camping)

of course this one is not working, but I'm looking for something like that.
I know that i can get all coupons of the company and put them into Collection and then just delete all coupons that not equals to the specified type, but is there any way to do this process in database by SQL commands?

A: Use only one column with an IN operator
SELECT *
  FROM COMPANY_COUPON
 WHERE COMPANY_ID = 1
   AND COUPON_ID IN (SELECT COUPON_ID FROM COUPON WHERE TYPE = CAMPING)

A: I think you just want a join:
SELECT cc.COUPON_ID
FROM COMPANY_COUPON cc JOIN
     COUPON c
     ON cc.COUPON_ID = c.ID
WHERE cc.COMPANY_ID = ? AND c.TYPE = ?;

A: You might want to use WHERE IN here:
SELECT *
FROM COMPANY_COUPON
WHERE COMPANY_ID = 1 AND COUPON_ID IN (SELECT ID FROM COUPON WHERE TYPE = 'CAMPING');

You could also use EXISTS, which is probably the best way to write your logic:
SELECT cc.*
FROM COMPANY_COUPON cc
WHERE
    cc.COMPANY_ID = 1 AND
    EXISTS (SELECT 1 FROM COUPON c WHERE c.TYPE = 'CAMPING' AND c.ID = cc.COUPON_ID);

Using EXISTS might outperform doing a join between the two tables, because the database can stop as soon as it finds the very first match.


Q: Problem showing image from a database with JSF via a Servlet EDIT: The reason for this issue was due to bug unrelated to the servlet.
I'm working on a JSF2/JPA/EJB3 project that enables users to upload photos of themselves and stores them in a database. Loading images from the database is made possible with a servlet. There is however a problem; when changing the picture and posting the page, the image goes blank. The servlet doesn't seem to be called.
Web page:
<h:form>
    <h:graphicImage value="image?fileId=#{bean.currentUser.photo.id}"/>
    <3rd party file upload component (primeFaces)/>
    <h:commandButton value="post"/>
</h:form>

Servlet mapping:
<servlet>
    <servlet-name>imageServlet</servlet-name>
    <servlet-class>com.xdin.competence.jsf.util.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>imageServlet</servlet-name>
    <url-pattern>/image/*</url-pattern>
</servlet-mapping>

Servlet:
@ManagedBean
public class ImageServlet extends HttpServlet {
    private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
    @EJB private UserBean userBean;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        Long fileId = Long.parseLong(request.getParameter("fileId"));
        if (fileId == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
        }
        UserFile photo = userBean.findUserFile(fileId);
        // Init servlet response.
        response.reset();
        response.setBufferSize(DEFAULT_BUFFER_SIZE);
        response.setContentType("image/png");
        response.setHeader("Content-Length", String.valueOf(photo.getFileData().length));
        response.setHeader("Content-Disposition", "inline; filename=\"" + photo.getFilename() + "\"");

        // Prepare streams.
        BufferedInputStream input = null;
        BufferedOutputStream output = null;

        try {
            // Open streams.
            input = new BufferedInputStream(new ByteArrayInputStream(photo.getFileData()), DEFAULT_BUFFER_SIZE);
            output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

            // Write file contents to response.
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
        } finally {
            // Gently close streams.
            close(output);
            close(input);
        }
    }

    private static void close(Closeable resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                // Do your thing with the exception. Print it, log it or mail it.
                e.printStackTrace();
            }
        }
    }

My guess is that doGet in ImageServlet is only called on Get. Forcing a new GET with faces-redirect=true works, but is it possible to make the servlet work on POST aswell?

A: You seem to think that images are downloaded as part of the HTTP response containing the HTML page containing the <img> elements. This is not true. The browser obtains the HTML page, parses the HTML structure, encounters the <img> element and fires separate HTTP requests for each of them. It is always GET. The same applies to CSS/JS and other resources. Install a HTTP request debugger tool like Firebug and check the Net panel.
The actual problem is likely that the URL as definied in src attribute is wrong. You're using a context-relative path (i.e. no leading slash and no domain in the src attribute, it's fully dependent on the current request URL -the one in browser address bar). Probably the HTML page get posted to a different context/folder which caused that the image becomes unreachable from that point. Try using an absolute path or a domain-relative path.
<h:graphicImage value="#{request.contextPath}/image?fileId=#{bean.currentUser.photo.id}" />

If still in vain, then have a closer look at Firebug's analysis.


Q: I want to make an Script in python which will calculate Beneish M Score in python Table 1 – Financials (standalone)
Year                            2014              2013            2012            2011            2010
Net Sales                       8,020.35          9,754.50        8,433.48        6,447.24        4,827.47
Cost of Goods                   5,524.76          7,416.64        6,299.72        4,494.74        3,176.16
Net Receivables                 2,045.70          2,807.26        1,689.88        1,109.29        693.33
Current Assets                  4,000.61          4,894.15        4,228.61        2,747.23        2,236.16
Property, Plant and Equipment   1,848.27          2,177.22        1,948.19        1,834.23        1,552.22
Depreciation                    199.02            219.18          203.06          194.05          180.10
Total Assets                    13,994.40         13,215.16       12,186.17       10,201.72       8,480.00
SGA Expense                     588.25            495.77          451.73          347.35          338.63
Net Income                      673.95            423.05          345.39          379.69          283.40
Cash Flow from Operations       988.18            1.17            406.65          340.06          1,069.19
Current Liabilities             4,301.49          4,697.45        4,868.32        3,087.15        889.03
Long-term Debt                  1,492.06          1,503.40        1,475.46        1,534.03        3,640.02

Table 2 – Financials (consolidated)
Year                            2014        2013        2012        2011        2010
Net Sales                       26,111.94   26,003.67   21,840.29   18,187.77   15,523.34
Cost of Goods                   10,323.87   11,543.19   9,156.12    6,872.80    5,519.23
Net Receivables                 2,642.69    3,358.56    2,220.68    1,530.03    1,083.42
Current Assets                  17,581.22   17,393.72   13,317.96   10,932.59   5,528.21
Property, Plant and Equipment   17,998.98   15,444.53   12,490.63   8,847.56    6,544.69
Depreciation                    1,608.86    1,295.49    1,092.33    940.90      866.48
Total Assets                    63,034.10   57,105.27   45,157.00   39,600.52   28,988.86
SGA Expense                     1,730.27    1,625.98    1,347.43    1,231.69    1,640.42
Net Income                      1,221.80    1,183.89    1,010.15    907.97      154.56
Cash Flow from Operations       47.62       -993.70     153.47      1,263.04    4,235.99
Current Liabilities             14,515.48   15,660.07   11,881.23   9,106.74    3,206.53
Long-term Debt                  12,460.74   9,392.73    5,641.57    4,680.65    7,432.40

Here from the above table I need to calculate different Indexes:
Index 1: Days Sales in Receivables Index (DSRI) = Net Receivable [CY]/ Net Sales [CY] Divided by Net Receivable [CY-1]/ Net Sales [CY-1]
So I thought storing all the Table 1 data in dictionary like this:
Net_Sales = {2014: 8020.35, 2013:9754.50, 2012:8433.48, 2011:6447.24, 2010:4827.47}
Cost_Goods = {2014: 5524.76, 2013:7416.64, 2012:6299.72, 2011:4494.74, 2010:3176.16}
Net_Receivables = {2014:2045.70, 2013:2807.26, 2012:1689.88, 2011:1109.29, 2010:693.33}
Current_Assets = {2014:4000.61, 2013:4894.15, 2012:4228.61, 2011:2747.23, 2010:2236.16}
Property_Plant_Equipment = {2014:1848.27, 2013:2177.22, 2012:1948.19, 2011:1834.23, 2010:1552.22}
Depreciation = {2014:199.02, 2013:219.18, 2012:203.06, 2011:194.05, 2010:180.10}
Total_Assets = {2014:13994.40, 2013:13215.16, 2012:12186.17, 2011:10201.72, 2010:8480.00}
SGA_Expense = {2014:588.25, 2013:495.77, 2012:451.73, 2011:347.35, 2010:338.63}
Net_Income = {2014:673.95, 2013:423.05, 2012:345.39, 2011:379.69, 2010:283.40}
Cash_Flow_Operations = {2014:988.18, 2013:1.17, 2012:406.65, 2011:340.06, 2010:1069.19}
Current_Liabilities = {2014:4301.49, 2013:4697.45, 2012:4868.32, 2011:3087.15, 2010:889.03}
Long_Deb = {2014:1492.06, 2013:1503.40, 2012:1475.46, 2011:1534.03, 2010:3640.02}

But then again I need to make lots of dictionary for Table 2 also.
And again I need to display the output in a table like this:
#Index 1 using the formula 1.
Net Receivable [CY-1]/ Sales [CY-1]
Year                            2014    2013    2012    2011
As per Standalone Financials    0.886   1.436   1.165   1.198
As per Consolidated Financials  0.784   1.270   1.209   1.205

I calculated the 1st value using the following formula:
DSRI = (Net_Receivables[2014]/Net_Sales[2014]) / (Net_Receivables[2013]/Net_Sales[2013])

And I got the only one value. So it would be very hectic and unplanned way to do the above calculation. As I need to do lots of calculation on the above data. So can someone help me how to store these data if not in dictionary then where. And how should I plan to calculate all the required values. As I need to calculate 8 indexes and maybe in the future I can reuse it for different set of years. Thanks. Please tell me if you need more information.


Q: How to schedule a MySQL database backup in a remote Ubuntu server to a Dropbox folder in Windows PC? I have a MySQL database that I want to daily backup to my Dropbox folder on my Windows PC.
How can I do that automatically from Windows 7?

A: One of the simplest ways to backup a mysql database is by creating a dump file. And that is what mysqldump is for. Please read the documentation for mysqldump.
In its simplest syntax, you can create a dump with the following command:
mysqldump [connection parameters] database_name > dump_file.sql

where the [connection parameters] are those you need to connect your local client to the MySQL server where the database resides.
mysqldump will create a dump file: a plain text file which contains the SQL instructions needed to create and populate the tables of a database. The > character will redirect the output of mysqldump to a file (in this example, dump_file.sql). You can, of course, compress this file to make it more easy to handle.
You can move that file wherever you want.
To restore a dump file:

*

*Create an empty database (let's say restore) in the destination server

*Load the dump:
mysql [connection parameters] restore < dump_file.sql

There are, of course, some other "switches" you can use with mysqldump. I frequently use these:

*

*-d: this wil tell mysqldump to create an "empty" backup: the tables and views will be exported, but without data (useful if all you want is a database "template")

*-R: include the stored routines (procedures and functions) in the dump file

*--delayed-insert: uses insert delayed instead of insert for populating tables

*--disable-keys: Encloses the insert statements for each table between alter table ... disable keys and alter table ... enable keys; this can make inserts faster

You can include the mysqldump command and any other compression and copy / move command in a batch file.

A: My solution to extract a backup and push it onto Dropbox is as below.
A sample of Ubuntu batch file can be downloaded here.
In brief

*

*Prepare a batch script backup.sh

*Run backup.sh to create a backup version e.g. backup.sql

*Copy backup.sql to Dropbox folder

*Schedule Ubuntu/Windows task to run backup.sh task e.g. every day at night

Detail steps

*

*All about backing up and restoring an MySQL database can be found here.

Back up to compressed file
mysqldump -u [uname] -p [dbname] | gzip -9 > [backupfile.sql.gz]

*How to remote from Windows to execute the 'backup' command can be found here.

plink.exe -ssh -pw  -i "Path\to\private-key\key.ppk" -noagent username@server-ip

*How to bring the file to Dropbox can be found here

Create a app
  https://www2.dropbox.com/developers/apps
Add an app and choose Dropbox API App. Note the created app key and app secret
Install Dropbox API in Ubuntu; use app key and app secret above
$ wget https://raw.github.com/andreafabrizi/Dropbox-Uploader/master/dropbox_uploader.sh
$ chmod +x dropbox_uploader.sh

Follow the instruction to authorize access for the app e.g.
http://www2.dropbox.com/1/oauth/authorize?oauth_token=XXXXXXX

Test the app if it is working right - should be ok
$ ./dropbox_uploader.sh info

The app is created and a folder associating with it is YourDropbox\Apps\<app name>
Commands to use
List files
$ ./dropbox_uploader.sh list

Upload file
$ ./dropbox_uploader.sh upload <filename> <dropbox location>
e.g.
$ ./dropbox_uploader.sh upload backup.sql .

This will store file backup.sql to YourDropbox\Apps\<app name>\backup.sql
Done

*How to schedule a Ubuntu can be view here using crontab

Call command
sudo crontab -e

Insert a line to run backup.sh script everyday as below
0 0 * * * /home/userName/pathTo/backup.sh

Explaination:
minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday), command

Or simply we can use
@daily /home/userName/pathTo/backup.sh

Note:

*

*To mornitor crontab tasks, here is a very good guide.


Q: How can i modulo a big integer value     #include <string>
    #include <iostream>

    using namespace std;

    #include "md5.h"

    int main()
    {
        MD5 md5;

        string message = "secretU";
        char arr[message.size()];
        strcpy(arr, message.c_str());

        //encrypting the message "secretU", it will return a string of hexadecimals
        string result = md5.digestString(arr);

        //print the result of the encrypted message.
        cout << result;
        return 0;
    }

Result of the output in hexadecimals
1853c517b0e1095a341210f1a4b422e6

Once i tried to convert to Decimal, it needs 125 bit size? However, unsigned long long can only contain up to 64 bits, is there a way to store this long integer so that i can modulo it with the value i want?
Convert hexadecimals to decimal
32336430049777443053240099092194140902

A: You can do it by hand or use a library that provides big integers like https://mattmccutchen.net/bigint/

A: Take the modulo by breaking them into pieces.. say for example you want to take modulo of 37^11 mod 77 in which 37^11 gives answer 1.77917621779460E17 so to get this .. take some small number in place of 11 which gives an integer value.. break it into pieces... 37^11 mod 77 can be written as (37^4 x 37^4 x 37^3 mod 77) so solve it as.. {(37^4 mod 77)(37^4 mod 77)(37^3 mod 77)} mod 77. So, in general xy mod n = {(x mod n)(y mod n)} mod n


Q: Jhipster - production build failure I cannot generate my JHipster application war by running mvnw -Pprod. Here's the error I get in a console:
https://pastebin.com/3wLwy2x4
And my package.json dependencies:
https://pastebin.com/txnATG6M
The solution from:
Webpack failure during JHipster Prod Package
doesn't work for me, only the error changes to:
[INFO] ERROR in ./src/main/webapp/app/app.main.ts
[INFO] Module not found: Error: Can't resolve './app.module.ngfactory' in 'D:\Programy\Web\softdog2\src\main\webapp\app'
[INFO]  @ ./src/main/webapp/app/app.main.ts 2:0-62
[INFO] MergetJsonsWebpackPlugin emit starts...
[INFO] MergetJsonsWebpackPlugin emit completed...
[ERROR] error Command failed with exit code 2.
[INFO] info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
[ERROR] error Command failed with exit code 1.
[INFO] info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
[ERROR] error Command failed with exit code 1.
[INFO] info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:48 min
[INFO] Finished at: 2018-06-13T23:29:58+02:00
[INFO] Final Memory: 50M/532M

Also, I get following warnings from yarn:
[ERROR] warning " > angular-particle@1.0.4" has incorrect peer dependency "@angular/core@^4.0.0".
[ERROR] warning " > ng2-page-scroll@4.0.0-beta.12" has incorrect peer dependency "@angular/core@>=4.2.6 <5.0.0".
[ERROR] warning " > ng2-page-scroll@4.0.0-beta.12" has incorrect peer dependency "@angular/common@>=4.2.6 <5.0.0".
[ERROR] warning " > ng2-page-scroll@4.0.0-beta.12" has incorrect peer dependency "@angular/platform-browser@>=4.2.6 <5.0.0".
[ERROR] warning " > ng2-page-scroll@4.0.0-beta.12" has incorrect peer dependency "@angular/router@>=4.2.6 <5.0.0".

A: The answer to this problem is to update Angular libraries versions (in my case from 5.1.0 to 5.1.1).


Q: Image request from URL fails I have the following code:
func getImage(urlString: String, completionHandler: UIImage -> Void) -> NSURLSessionTask {

    let request = NSMutableURLRequest(URL: NSURL(fileURLWithPath: urlString)!)

    println("Executing image request: \(urlString)")

    return session.dataTaskWithRequest(request) {
        data, response, error in
        if error != nil {
            println("\tGET request failed: \(error!)")
        } else {
            println("\tGET request succeeded!")
            let response = response as NSHTTPURLResponse
            if response.statusCode == 200 {
                let image = UIImage(data: data)
                dispatch_async(dispatch_get_main_queue()) { // dispatch naar main thread (main_queue is thread# van main thread van app)
                    completionHandler(image!)
                }
            }
        }
    }
}

But when I execute it, I get the following output:
Executing image request: http://i.imgur.com/rfw7jrU.gif
GET request failed: Error Domain=NSURLErrorDomain Code=-1100
"The operation couldn’t be completed. (NSURLErrorDomain error -1100.)"
UserInfo=0x14e9b200 {NSErrorFailingURLKey=file:///http:/i.imgur.com/rfw7jrU.gif,
NSErrorFailingURLStringKey=file:///http:/i.imgur.com/rfw7jrU.gif,
NSUnderlyingError=0x14d8d600 "The operation couldn’t be completed.
(kCFErrorDomainCFNetwork error -1100.)"}

I have no idea why this happens, as my nearly identical code that gets a .json file does work. I have tested this on both my device and the simulator.
This fails on all urls, not only imgur links. It also crashes before I put it into a UIImage, so that is also not the problem.

A: From the error message one can see that your URL is a file URL:
file:///http:/i.imgur.com/rfw7jrU.gif

and error -1100 is kCFURLErrorFileDoesNotExist (see CFNetwork Error Codes Reference).
You should replace
NSURL(fileURLWithPath: urlString)

by
NSURL(string: urlString)
// Swift 3+:
URL(string: urlString)


Q: how to fix update error i want to update all row's alternativegroups with $id value.
the action getting error: coldchain can not be null.
when i search the db for pk = $a, It's coldchain value is boolen(false). and db is postgresql
how can i set $q->attributes without posting other values?
public function actionUpdate($id){

    if (isset($_POST['forms'])){

        $arr = explode(',', $_POST['forms']);

        foreach ($arr as $a){

            $q = MedicineDrugform::model()->findbypk($a);
            $q->alternativegroup = $id;
            if ($q->save()){
                echo $q->id."q saved
";
            }
            else {
                echo "
";
                print_r($q->getErrors());
            }

            die();

            $qu = MedicineDrugformUpdate::model()->findbyattributes(array('drug_form_id'=>$a));
            $quu = MedicineDrugformUpdate::model()->findbypk($qu->id);
            $quu->alternativegroup = $id;
            if ($quu->save()){
                echo $quu->id."qu saved
";
            }

        }
        die();
        $this->render('/site/messages', array('message'=>'formsaved'));

    }

    $this->render('add', array('id'=>$id));
}

A: maybe it cant find the corresponding record for
$q = MedicineDrugform::model()->findbypk($a);


Q: .Net MVC4 updating database I am struggling to update a database. All i need to do is update a column called balance
In my controller i have this
     public void updateBalance(int account, double amount)
    {
        var accounnt = db.Accounts.FirstOrDefault(u => u.AccountNumber == account);

        if (accounnt == null)
        {

        }
        else
        {
           //   update the balance column in account table
        }

    }

can some one please assist?

A: Once you have loaded your entity, you simply need to update its properties and call SaveChanges on your DbContext.
  if (accounnt == null)
    {

    }
    else
    {
       account.balance = 1000;
    }
  db.SaveChanges();


Q: Render Flash (SWF) frame as image (PDF,PNG,JPG) I would like to write a python script that takes a bunch of swf files and renders them to individual image files.
Each swf file has just one frame (text, pictures etc.) and no animations at all. I have already tried the render command from the swftools toolset (The windows version), but the resolution of the resulting image is too low.
So what I need is:
A command line tool (Windows/Linux) or a python library which renders one frame from a swf to a bitmap or better to something like a PDF (It would be cool if the text data could be retained). It would be great if the target resolution/size could be set manually.
Thanks in advance!

A: Sometimes SWFRender is stuck at very heavy files, especially when producing 300dpi+ images. In this case Gnash may help:
gnash -s<scale-image-factor> --screenshot last --screenshot-file output.png -1 -r1 input.swf

here we dump a last frame of a movie to file output.png disabling sound processing and exiting after the frame is rendered. Also we can specify the scale factor here or use
-j width -k height

to specify the exact size of resulting image.

A: You could for example build an AIR app that loads each SWF, takes the screenshot and writes it to a file.
The thing is you'll need to kick off something to do the render and, as far as i know, you can't do that without the player or some of its Open Source implementation.
I think your best bet is going AIR, the SDK is free and cross-platform. If you are used to python, the AS3 necessary should be easy enough to pick up.
HTH,
J

A: I'm sorry to answer my own question, but I found an undocumented feature of swfrender (part of the swftools) by browsing through the sources.
swfrender path/to/my.swf -X<width of output> -Y<height of output>
-o<filename of output png>

As you might have guessed the X option lets you determine the width (in pixels) of the output and Y does the same for the height. If you just set one parameter, then the other one is chosen in relation to the original height-width-ratio (pretty useful)
That does the trick for me but as Zarate offered a solution that might be even better (I'm thinking of swf to PDF conversion) he deserves the credits.
Cheers


Q: sum of table with join on joined table gives wrong total I have three tables:

*

*users_timings_log

*projects_tasks

*projects_modules

I want to calculate the total hours spent on a task with module_ id 2 for example
I use the following query for it:
SELECT SEC_TO_TIME(SUM(TIMESTAMPDIFF(SECOND, `start_date`, `end_date`)))
AS `total_hours`
FROM `users_timings_log`
INNER JOIN `projects_tasks` ON users_timings_log.type_id = projects_tasks.id
LEFT JOIN `projects_modules` ON projects_tasks.module_id = '2'
WHERE `type` = '0'

This is the structure of my users_timings_log table
+-------+---------------------+---------------------+------+---------+
|   ID  | start_date          | end_date            | type | type_id |
+-------+---------------------+---------------------+------+---------+
|   1   | 2015-09-17 09:00:00 | 2015-09-17 19:00:00 | 1    | 28      |
|   2   | 2015-09-17 07:00:00 | 2015-09-17 12:00:00 | 1    | 24      |
|   3   | 2015-09-17 08:00:00 | 2015-09-17 16:15:00 | 1    | 18      |
|   4   | 2015-09-17 10:00:00 | 2015-09-17 17:00:00 | 1    | 24      |
+-------+---------------------+---------------------+------+---------+

Here's the structure of my projects_tasks table
+-------+---------------+-----------------------------+-----------+
|   ID  | name          | description                 | module_id |
+-------+---------------+-----------------------------+-----------+
|   18  | First task    | Some useless description    | 1         |
|   24  | Second task   | Another useless description | 2         |
|   28  | Third task    | NULL                        | 3         |
+-------+---------------+-----------------------------+-----------+

Structure of projects_modules table
+-------+---------------+
|   ID  | name          |
+-------+---------------+
|   1   | Module 1      |
|   2   | Module 2      |
|   3   | Module 3      |
+-------+---------------+

What I need is the total of hours of a specific module, but for some reason It is giving me for each module the same amount of time.
I'm stuck on it. What am I doing wrong?
Thanks in advance

A: You need a GROUP BY and proper JOIN:
SELECT pt.module_id,
       SEC_TO_TIME(SUM(TIMESTAMPDIFF(SECOND, ul.`start_date`, ul.`end_date`)))
AS `total_hours`
FROM `users_timings_log` ul INNER JOIN
     `projects_tasks` pt
     ON ul.type_id = pt.id
WHERE `type` = '0'
GROUP BY pt.module_id;

If you only want one module, then add a WHERE clause for that purpose.
I also added table aliases, so the query is easier to write and to read.
I should add, the problem with your query is that it did not have proper JOIN conditions for projects_modules.  You don't seem to need that table, so removing the table is fine.  If you need columns from that table, add the appropriate JOIN conditions.


Q: With a user specified by IP address, why I can't connect to mysql server remotely? I am trying to set mysql server on an office computer to allow only for my computer at home to be able to connect to the mysql server.
I created a user on the mysql server. The user is specified by IP address(XXX.XXX.XXX.XXX) of my home computer.
Login name: myname

Limit to Hosts Matching: XXX.XXX.XXX.XXX

and also, in Administrative Roles tab, I added DBManager to this user.
and then, I tested this connection from my home computer using mysql workbench, and I got this error:
Failed to Connect to MySQL at ---.---.---.---:3306 with user myname

Host '???-???-???-???-???.abc.defg.hi.jk' is not allowed to connect to this MySQL server

---.---.---.---: IP address of the computer that has mysql server.
???-???-???-???-???.abc.defg.hi.jk: I am not sure about this. Looks like some gate way name.


Q: JMeter Network distribution in load testing How can i distribute networks while load testing in JMeter?
Suppose my load test is of 1 hr. and i have 100 users. I want to distribute network like-
              20% users - 2G speed
              40% users - 3G speed
              rest      - 4G speed.
OR, other scenario like throughout the whole test of 1hr. 20% traffic will on 2G speed, 40% traffic on 3G and rest on 4G speed.
Can anyone tell me that how to mimic this network behavior in JMeter?

A: *

*You will need to kick off 3 JMeter instances in Distributed Mode

*For 1st JMeter instance add the next lines to user.properties file to mimic 2G network:
httpclient.socket.http.cps=6400
httpclient.socket.https.cps=6400

*For 2nd JMeter instance add the next lines to user.properties file to mimic 3G network
httpclient.socket.http.cps=2688000
httpclient.socket.https.cps=2688000

*For 3rd JMeter instance add the next lines to user.properties file to mimic 4G network:
httpclient.socket.http.cps=19200000
httpclient.socket.https.cps=19200000

More information: How to Simulate Different Network Speeds in Your JMeter Load Test


Q: URL rewrite in IIS6 - Third party tools I have collected the following api/sdk/whatever which provide modules for doing url rewriting in IIS 5/6/7. Some are free-open source and some require $.
I haven't tried any of them. I would like to know if anyone is currently using or used or have any kind of experience with these tools (website listed).
UrlRewritingNet.UrlRewrite - http://www.urlrewriting.net/159/en/downloads.html

IIS Mod-Rewrite Pro ($) -http://www.iis.net/downloads/default.aspx?tabid=34&g=6&i=1469

Open Source - http://urlrewriter.net/

Helicon Tech (Full $)- http://www.isapirewrite.com/

ISAPI_ Rewrite 3.0 ($) - http://www.seoconsultants.com/windows/isapi/3/

Open Source Ionics Isapi Rewrite Filter - http://iirf.codeplex.com/

Any help would be greatly appreciated.
Thanks.
Murali

A: I have personal experience with IIRF from the codeplex site, and I liked it and found it good.

A: I use UrlRewrite from UrlRewriting.Net
Very easy to use for the simple thing I'm doing: send .pdf requests to an aspx page to generate the pdf.


Q: googleVis datatype conversion in R does not seems to work I have been working with 'googleVis' and R in order to produce a Line chart using Google charts APIs.
On Google API's tutorial I found that data conversion in Javascript is used to determine if the axes will be "continuous"(using Numeric Javascript type) and "discrete" (using String).
I believe with googleVis is the same, since datatypes are derived from R.
Problem is, in the following example (which I modified after taking it from the R demo function), the X axis values are equally spaced (hence, still discrete), despite they seem to be "Numeric"
library(googleVis)
df=data.frame(val1=c(10,13,100), val2=c(23,12,32))
Line <- gvisLineChart(df)
plot(Line)

Could someone please me help to understand this? Thank you very much!

A: Full disclosure: I love the googleVis package.
I see the same behavior you do, even after updating to the latest version of googleVis (not yet on CRAN). I don't know if this is a bug or not; the googleVis documentation for gvisLineChart mentions continuous data, but nothing I tried allows me to plot the X axis as numerical.
You can get clues as to what's happening when you change aspects of your code in generating googleVis charts and graphs if you right-click on the web page that gets displayed with the plot, and choose "View Page Source." This page is where the magic happens, and is the HTML output from the googleVis package.
The problematic line in this case is the one that reads "data.addColumn('string','val1');
In this line, the word 'string' should be 'number', and the val1 values should not be in quotes in the data section.
You can get the results you want, though, by using gvisScatterChart instead:
library(googleVis)
df=data.frame(val1=c(10,13,100), val2=c(23,12,32))
Line <- gvisScatterChart(df, options=list(lineWidth=2, pointSize=0))
plot(Line)


Q: Android NetworkOnMainThreadException when calling Url.OpenStream I get this exception  when running my code on emulator (Android 4.0.3 / API 15). While opening a stream it will throw an exception. Error-message is null.
try {
    String adress        = "xxx";
    URL url              = new URL(adress);
    InputSource source   = new InputSource(url.openStream());

} catch (Exception e) {
    (new TextView).setText("Error: "+e.getMessage());
}

URL is still working with the emulator (in browser).
I have cleaned the project.
Also Internet connection is allowed:
<uses-permission android:name="android.permission.INTERNET" />

Exception : android.os.NetworkOnMainThreadException

A: Please never run a networking operation on the main (UI) thread .
Main thread is used to:

*

*interact with user.

*render UI components.

any long operation on it may risk your app to be closed with ANR message.
Take a look at the following :

*

*Keeping your application Responsive

*NetworkOnMainThreadException
you can easily use an AsyncTask or a Thread to perform your network operations.
Here is a great tutorial about threads and background work in android: Link

A: Works for me:
Manifest.xml:
<uses-permission android:name="android.permission.INTERNET" />

.java:
private static boolean DEVELOPER_MODE = true;
...
protected void onCreate(Bundle savedInstanceState) {

     if (DEVELOPER_MODE) {
         StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                 .detectDiskReads()
                 .detectDiskWrites()
                 .detectNetwork()   // or .detectAll() for all detectable problems
                 .penaltyLog()
                 .build());
         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                 .detectLeakedSqlLiteObjects()
                 .detectLeakedClosableObjects()
                 .penaltyLog()
                 .penaltyDeath()
                 .build());
     }
...

hope it helps.
see also : http://developer.android.com/reference/android/os/StrictMode.html


Q: Reply Kafka Template - Exception handling I am using ReplyingKafkaTemplate to establish a synchronous call between two microservices.
The receiver of the event is annotated with SendTo as below:
@KafkaListener(topics = "${kafka.topic.prefix}"
        + "${kafka.topic.name}", containerFactory = "customEventKafkaListenerFactory")
@SendTo
public CustomResponseEvent onMessage(
        @Payload @Valid CustomRequestEvent event, @Header(KafkaHeaders.CORRELATION_ID) String correlationId,
        @Header(KafkaHeaders.REPLY_TOPIC) String replyTopic) {

   //Making some REST API calls to another external system here using RestTemplate
}

The REST API call can throw a 4xx or 5xx. There are multiple such calls, some to internal systems, and some to external systems. It may be a bad design, but let's not get into that.
I would like to have a global exception handler for the RestTemplate where I can catch all the exceptions, and then return a response to the original sender of the event.
I am using the same replyTopic and correlationId as received in the consumer to publish the event.
But still the receiver of the response throws No pending reply exception.

*

*Whatever approach I have above, is it possible to achieve such a central error response event publisher?

*Is there any other alternative that is best suited for this exception handling?

A: The @KafkaListener comes with the:
/**
 * Set an {@link org.springframework.kafka.listener.KafkaListenerErrorHandler} bean
 * name to invoke if the listener method throws an exception.
 * @return the error handler.
 * @since 1.3
 */
String errorHandler() default "";

That one is used to catch and process all the downstream exceptions and if it returns a result, it is sent back to the replyTopic:
public void onMessage(ConsumerRecord<K, V> record, Acknowledgment acknowledgment, Consumer<?, ?> consumer) {
    Message<?> message = toMessagingMessage(record, acknowledgment, consumer);
    logger.debug(() -> "Processing [" + message + "]");
    try {
        Object result = invokeHandler(record, acknowledgment, message, consumer);
        if (result != null) {
            handleResult(result, record, message);
        }
    }
    catch (ListenerExecutionFailedException e) { // NOSONAR ex flow control
        if (this.errorHandler != null) {
            try {
                Object result = this.errorHandler.handleError(message, e, consumer);
                if (result != null) {
                    handleResult(result, record, message);
                }
            }
            catch (Exception ex) {
                throw new ListenerExecutionFailedException(createMessagingErrorMessage(// NOSONAR stack trace loss
                        "Listener error handler threw an exception for the incoming message",
                        message.getPayload()), ex);
            }
        }
        else {
            throw e;
        }
    }

See RecordMessagingMessageListenerAdapter source code for more info.


Q: MySQL Auto increment skipping number which is deleted I want to generate Bill No From mySQL Auto Increment. I have column ID (Primary Key & Auto Increment). Now From This column ID I am generating Bill No As requested by user. Problem is If I delete some record in between then It should not skip the deleted ID when new record gets entered.
e.g. 1001,1002,1003,1004 etc In this if I delete record Id 1002 & next time If I enter any new record then How can I assign 1002 back to the new record.

A:
It should not skip the deleted ID when new record gets entered

Yes it should.  You're just relying on the system to do something that it was never designed to do and never claimed to do.
AUTOINCREMENT is not designed to generate your "Bill No".  It's designed to generate an ever-incrementing identifier and guarantee uniqueness by never re-using a value.  And it's doing exactly that.
You can manually generate your "Bill No" using whatever logic you like and store it in another column.  It would be strange to re-use values though.  Imagine if you issue a bill to someone, later delete the record, and then issue another bill to someone else with the same number.
Uniqueness is important with identifiers.

A: From a financial control point of view being able to delete and reuse invoice numbers damages your audit trail and leaves you open to risk. Also from a database integrity point of view, reusing primary keys is not allowed as it would lead to unexpected results,such as records in other tables appearing wrongly in a join. There are consequences to naturalising your primary keys (excellent discussion of natural and surrogate primary keys). The database is protecting its referential integrity by not allowing the reuse of the primary key. Indeed, as @David says in his response, part of the function of autoincrement on a primary key is to maintain the uniqueness of the key.
Now to solutions, from a financial aspect invoices should never be deleted so there is an audit trail, an incorrect invoice should have a contra through a credit note. On the database side if you must 'delete' a record and reuse the invoice number, I would suggest having a different field for the invoice number, not actually deleting, but using a field to flag active or deleted, and maintaining a separate incrementing invoice number. Although not advised, this will at least help maintain the integrity of your records.


Q: Which credentials and tooling do I use to authenticate to the HERE geofencing/fleet APIs? I have been trying to apply some geofencing to my Here map, but continually get 401 and 403 responses from the geofencing endpoints no matter what I do.
I was originally using the node module '@here/maps-api-for-javascript' but I saw indicators that it was not possible to do geofencing with that tool, and so I have switched to pulling down scripts (v3.1) from CDN and making direct REST calls to fill in any gaps as outlined in this SO post, I have created a test project using the exact code provided at that SO post with my api key, and the map does not render at all, let alone the geofencing (but the triangle and marker are rendered). In the console I see 403s for all calls to the APIs.
I have tried:

*

*JS API key from developer account

*REST API key from developer account

*platform API key from platform account

*oauth API token from platform account

*app_id and app_code params with my JS app id and JS API key

*app_id and app_code params with my REST app id and REST app key

My keys work to render my map, calculate routes, and update routehandles in my app, so I'm not sure why they are not working for these two calls - one to upload the fences, and one to check position against them.
Additionally in my app I had tried to do geofencing as outlined in this tutorial from here but when I try to access the platform.ext.getGeoFencingService (line 163 in view source at that link) I get an error that platform.ext is undefined.
Adding to my confusion, one part of the docs says that apikeys are read only, and another part of the docs says that starting with JS api v3.1 that you no longer need app_id and app_code.


Q: How to position a view in Android constraint layout outside the screen at the beginning I have a View in a Constraint Layout and I would like that at the very beginning it should be outside of the screen (and then later slowly move into the scree from right to left). Now, I kind of need something like negative bias or margins.
I had a look at this question How to achieve overlap/negative margin on Constraint Layout?. The accepted answer using android:layout_marginTop="-25dp"  does not have any effect (altough the top of the view is constrained and I use"androidx.constraintlayout:constraintlayout:2.1.3").
I tried the second most upvoted answer and used the code:
view.setTranslationX(view.getWidth() - 20);

This actually works. However, the problem is that when the Fragment is created you first see that the view is not on the left for a short period of time. This is not what I want. I would like to have the view beyond the right rim of the layout at the very very beginning such that it can later move into the layout.
Do you have any idea how I can do that? Ideally I would like to do this programmatically.
Update: Here is the code of the XML layout where a negative margin does not have any effect:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/game_test_background"
    tools:context=".MainActivity"
    android:id="@+id/constraintLayout">

    <ImageView
        android:id="@+id/imageView_RedRectange_Test"
        android:layout_width="0dp"
        android:layout_height="30dp"
        android:layout_marginTop="-1250dp"

        app:layout_constraintWidth_percent="0.25"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.048"
        app:srcCompat="@drawable/red_rectangle" />

    <Button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="0.102"
        app:layout_constraintHorizontal_bias="0.373"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.745"
        app:layout_constraintWidth_percent="0.12" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: Okay so to have a negative margin you can use translateX, translateY or TranslationZ.
in xml like so:
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:translationX="-60dp"
    android:translationY="-90dp"
    android:translationZ="-420dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

or programmatically like so:
View view = ...;
view.setTranslationX(-60);
view.setTranslationY(-90);
view.setTranslationZ(-420);

Then in order to slowly bring it in from right to left you can use the animate() method like so:
View view = ...;
view.animate().setDuration(1000).translationX(-600).start();

A: There is a problem with setting the width of the button using app:layout_constraintWidth_percent when the ImageView has a negative margin. The problem should go away if you can set a definite width to the button (instead of 0dp).
The problem should also resolve if you set app:layout_constraintWidth_percent to a value such that the text of the button shows completely on one line.
Here is a simplified layout to demonstrate this issue. The ConstraintLayout has two views that are simply constrained to the parent to appear in vertical center of the layout. These two views have no dependencies on each other. In addition, the ImageView has a top margin of -250dp, so it should appear above the layout's vertical center.
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_green_light">

    <ImageView
        android:id="@+id/redRectangle"
        android:layout_width="100dp"
        android:layout_height="30dp"
        android:layout_marginTop="-250dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/red_rectangle" />

     <Button
            android:id="@+id/button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Button"
            android:textSize="18sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintWidth_default="percent"
            app:layout_constraintWidth_percent="0.12" />

</androidx.constraintlayout.widget.ConstraintLayout>

Here is what happens then the width of the ImageView is changed from 0dp to a non-zero value of 1dp. When the width is set to 0dp, the negative margin seems to be ignored. It is only when the width is set to a non-zero value that the ImageView is correctly placed.

Changing the width of the button should have no effect on the placement of the ImageView; however, the button only appears in the proper position when the button has a non-zero width.
Here is what happens when the app:layout_constraintWidth_percent is increased so that the word "Button" is not cutoff.

Again, the placement of the ImageView should be independent of the width of the button. Instead, the button only appears in the correct position when the app:layout_constraintWidth_percent is set such that the word "Button" is not cutoff.
This is only an issue with negative margins. Positive margins work as expected.
This is a strange problem, so you may want to use one of the other solutions mentioned.
(ConstraintLayout version 2.1.3)


Q: Layout PrimeFaces I have a layout file as follows

            <ui:insert name="Middle top">

This is a Center

            </ui:insert>

            <ui:insert name="Middle center">

This is a Center

            </ui:insert>

But when I run the layout file, nothing is displayed!
I use primefaces 3.5, jsf 2.1.

A: Except center layoutUnit, other layout units must have dimensions defined via size option.
Like this:

        <h:outputText value="Top content." />

        <h:outputText value="Bottom content." />

        <h:outputText value="Left content" />

        <h:outputText value="Right Content" />

        <h:outputText value="Center Content" />

A: If you are going with a layout concept in your project, it should handle like this.
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <f:view contentType="text/html" id="fview">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <f:metadata>
            <ui:insert name="metadata" />
        </f:metadata>
        <meta  name="selectedLanguage" content="Lang" lang="#{menuBean.selectedLanguage}"/>
        <h:head>

        <h:body behavior: url(PIE/PIE.htc);">

                       //enter your code

                      //enter your code

                      //enter your code

                     //enter your code

       </h:body>
   </f:view>


Q: How to generate HTML code using Javascript and JSON? I need to create a quiz by parsing a JSON file. The checked answers must be stored in the local storage.
The JSON code:
{
    "quiz": {
        "q1": {
            "question": "Which one is correct team name in NBA?",
            "options": [
                "New York Bulls",
                "Los Angeles Kings",
                "Golden State Warriros",
                "Huston Rocket"
            ],
            "answer": "Huston Rocket"
        },
        "q2": {
            "question": "'Namaste' is a traditional greeting in which Asian language?",
            "options": [
                "Hindi",
                "Mandarin",
                "Nepalese",
                "Thai"
            ],
            "answer": "Hindi"
        },
        "q3": {
            "question": "The Spree river flows through which major European capital city?",
            "options": [
                "Berlin",
                "Paris",
                "Rome",
                "London"
            ],
            "answer": "Berlin"
        },
        "q4": {
            "question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?",
            "options": [
                "Pablo Picasso",
                "Vincent van Gogh",
                "Salvador Dalí",
                "Edgar Degas"
            ],
            "answer": "Pablo Picasso"
        }
    }
}

The code is below:

    <input type ="submit" name ="submit" value = "Submit answers" onclick = "results()">

I should get this:
enter image description here
Instead I got this, no matter how many times I rewrite the code:
enter image description here
Whay am I doing wrong?
Thank you very much for your help,
Mary.

A: You have a small error with document.createElement("node") - there is no tag node so appending other elements to that is also incorrect. The code could be simplified though as below ( the add to local storage will throw an error in the snippet though )

let data = {
  "quiz": {
    "q1": {
      "question": "Which one is correct team name in NBA?",
      "options": ["New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket"],
      "answer": "Huston Rocket"
    },
    "q2": {
      "question": "'Namaste' is a traditional greeting in which Asian language?",
      "options": ["Hindi", "Mandarin", "Nepalese", "Thai"],
      "answer": "Hindi"
    },
    "q3": {
      "question": "The Spree river flows through which major European capital city?",
      "options": ["Berlin", "Paris", "Rome", "London"],
      "answer": "Berlin"
    },
    "q4": {
      "question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?",
      "options": ["Pablo Picasso", "Vincent van Gogh", "Salvador Daly", "Edgar Degas"],
      "answer": "Pablo Picasso"
    }
  }
};

// utility prototype to shuffle an array
Array.prototype.shuffle=()=>{
  let i = this.length;
  while (i > 0) {
    let n = Math.floor(Math.random() * i);
    i--;
    let t = this[i];
    this[i] = this[n];
    this[n] = t;
  }
  return this;
};

let list = document.createElement("ul");

Object.keys(data.quiz).forEach((q, index) => {
  // the individual record
  let obj = data.quiz[q];

  // add the `li` item & set the question number as data-attribute
  let question = document.createElement("li");
      question.textContent = obj.question;
      question.dataset.question = index + 1;
      question.id = q;

  // randomise the answers
  obj.options.shuffle();

  // Process all the answers - add new radio & label
  Object.keys(obj.options).forEach(key => {
    let option = obj.options[key];
    let label = document.createElement('label');
        label.dataset.text = option;

    let cbox = document.createElement('input');
        cbox.type = 'radio';
        cbox.name = q;
        cbox.value = option;

    // add the new items
    label.appendChild(cbox);
    question.appendChild(label);
  });

  // add the question
  list.appendChild(question);
});

// add the list to the DOM
document.getElementById('container').appendChild(list);

// Process the checked radio buttons to determine score.
document.querySelector('input[type="button"]').addEventListener('click', e => {
  let score = 0;
  let keys = Object.keys(data.quiz);

  document.querySelectorAll('[type="radio"]:checked').forEach((radio, index) => {
    if( radio.value === data.quiz[ keys[index] ].answer ) score++;
  });

  console.log('%d/%d', score, keys.length);
  localStorage.setItem("answers", score);
})
#container>ul>li {
  font-weight: bold
}

#container>ul>li>label {
  display: block;
  padding: 0.1rem;
  font-weight: normal;
}

#container>ul>li>label:after {
  content: attr(data-text);
}

#container>ul>li:before {
  content: 'Question 'attr(data-question)': ';
  color: blue
}

<input type="button" value="Submit answers" />

A: You need to make minor changes to your nest loop so that the option labels are inserted in the correct location.  See the code snippet where it is marked "remove" and "add" for the changes you need to make.
As @ProfessorAbronsius noted, there isn't an html tag called "node", though that won't stop your code from working.

let data = {"quiz": {"q1": {"question": "Which one is correct team name in NBA?", "options": ["New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket"], "answer": "Huston Rocket"}, "q2": {"question": "'Namaste' is a traditional greeting in which Asian language?", "options": ["Hindi", "Mandarin", "Nepalese", "Thai"], "answer": "Hindi"}, "q3": {"question": "The Spree river flows through which major European capital city?", "options": ["Berlin", "Paris", "Rome", "London"], "answer": "Berlin"}, "q4": {"question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?", "options": ["Pablo Picasso", "Vincent van Gogh", "Salvador Daly", "Edgar Degas"], "answer": "Pablo Picasso"}}};

let list = document.createElement("ul");
for (let questionId in data["quiz"]) {
  let item = document.createElement("node");
  let question = document.createElement("strong");
  question.innerHTML = questionId + ": " + data["quiz"][questionId]["question"];
  item.appendChild(question);
  list.appendChild(item);
  let sublist = document.createElement("ul");
  item.appendChild(sublist);

  // The problem is here in this nested loop

  for (let option of data["quiz"][questionId]["options"]) {

    item = document.createElement("input");
    item.type = "radio";
    item.name = data["quiz"][questionId];
    var label = document.createElement("label");
    label.htmlFor = "options";

    // remove 1
    // label.appendChild(document.createTextNode(data["quiz"][questionId]["options"]));

    // add 1
    label.appendChild(document.createTextNode(option));

    var br = document.createElement('br');
    sublist.appendChild(item);

    // remove 2
    //document.getElementById("container").appendChild(label);
    //document.getElementById("container").appendChild(br);

    // add 2
    sublist.appendChild(label);
    sublist.appendChild(br);

  }

}
document.getElementById("container").appendChild(list);

function results() {
  var score = 0;
  if (data["quiz"][questionId]["answer"].checked) {
    score++;
  }
}

// Removed because snippets don't allow localStorage
// localStorage.setItem("answers", "score");

<input type="submit" name="submit" value="Submit answers" onclick="results()">

A: Here's the answer to your question. Please let me know if you have any issues.

<input type="submit" name="submit" value="Submit answers" onclick="results()">


Q: Three.JS - AudioAnalyser() not working with audio source as Stream type in Safari I'm developing a streaming radio in 3D using Three.JS, I'm sending music as a PeerConnection to my clients attaching a THREE.AudioAnalyser() to display 3D bars that move according to frequencies.
Sound is working great in all platforms, but THREE.AudioAnalyser() with an input source of stream type only works on Chrome, Safari is not working at all :frowning:
var listener = new THREE.AudioListener();
var audio = new THREE.Audio( listener );
audio.setMediaStreamSource( stream );
audioAnalyser = new THREE.AudioAnalyser( audio, 128 );

function loop(){
    console.log(audioAnalyser.getFrequencyData());
}

The console.log() of the loop() function should contain an Array of Integers, on Chrome is all good, Safari logs [0,0,0,0,0,0,0,0]
What could be causing this issue? It seems to work everywhere but not on Safari, and also it only seems to fail when the source is a stream.

A: Not 100% sure, but you might want to connect the output of the AnalyserNode to the destination node.  You may want to stick a GainNode with a gain of 0 in between, just in case you don't really want the audio from the AnalyserNode to be played out.


Q: Remove unused source code files using eclipse/ Flash builder 4.6 i have a project having lots of file, around 4500 file in all Project. i separated it in 40 library project.Now my problem is that it taking too much time to Compile. so i increase a memory of Flash builder. This gives me little improvement to compile. i am sure that i have too much file which is not used in my project. so now i want to remove it by plug of Flash Builder / Eclipse. Because it is too much headache process to see that "xyz.as/mxml" file is used in any other file or if it is used in Other file say "abx.as/mxml" then again i have a question that "abx.as/mxml" is useful file or used in any other file. so you have any idea or hint please give me. Thanks in advance...

A: One thing you can try is to use the size-report of your flex compilation : flex compiler options
This way you will have an idea of which classes are really used in your libraries and therefore wich ones aren't because the flex compiler only link to classes you really need in your compiled swf.
This not ideal but it can avoid a lot of manual process pain.

A: Add this param to your compiler:
-link-report output.xml

this information will help you.

A: I'm not sure if it would work for flash-builder, but for Java there is the UCDetector.


Q: 1d numpy array with enough elements not resizing as expected I just started working with numpy arrays in conjunction with panda dataframes, and I am working on a practice project, but have hit a bit of a problem. I have a panda dataframe which I pass the rows of to a function to do some work on it. The function takes in two different arrays one labeled best and worst and then creates a new vector to compare sums against. From there it will return either the current array that the pandas.apply has passed or it will return the new vector based on which sum() is the lowest. This creates a new python array which needs to be a matrix of 20x5 at the end. The function works fine, but the returned dataframe needs to be converted to a python array of size (20 x 5) for further work, which when np.array() is called, it converts it into an array of size (20,). I figured just using .reshape(20,5) would work since it has enough elements to work with, but it does not, it just fails on run. Any help is appreciated as I can't find anything that's helping me understand why this is happening.
(the error, as many could guess by reading above, is: "cannot reshape array of size 20 into shape (20,5)" )
code except from my program that shows it (can run on it's own):
import numpy as np
import pandas as pd

rng = np.random.default_rng(seed=22)
df = pd.DataFrame(rng.random((20,5)))

def new_vectors(current, best, worst):
    #convert current to numpy array
    current = current.to_numpy()

    #construct a new vector to check
    new = np.add(current, np.subtract((rng.random()*(np.subtract(best, np.absolute(current)))), ((rng.random()*(np.subtract(worst, np.absolute(current)))))))

    #get the new sum for the new and old vectors
    summed = current.sum()
    newsummed = new.sum()

    #return the smallest one
    return np.add(((newsummed < summed)*(new)), ((newsummed > summed)*(current))).flatten()

z = np.array(df.apply(new_vectors, args=(df.iloc[0].to_numpy(), df.iloc[11].to_numpy()), axis=1))
z.reshape(20,5) #I know reshape() creates a copy, just here to show it doesn't work regardless

A: You can do the reshape manually.

*

*Delete z.reshape(20,5). This is not going to work with an array of arrays.

*After applying the function, use this instead:
# Create a empty matrix with desired size
 matrix = np.zeros(shape=(20,5))
 # Iterate over z and assign each array to a row in the numpy matrix.
 for i,arr in enumerate(z):
      matrix[i] = arr

If you don't know the desired size for the matrix. Create the matrix as matrix = np.zeros(shape=df.shape).
All the code used:
import numpy as np
import pandas as pd

rng = np.random.default_rng(seed=22)
df = pd.DataFrame(rng.random((20,5)))

def new_vectors(current, best, worst):
    #convert current to numpy array
    current = current.to_numpy()

    #construct a new vector to check
    new = np.add(current, np.subtract((rng.random()*(np.subtract(best, np.absolute(current)))), ((rng.random()*(np.subtract(worst, np.absolute(current)))))))

    #get the new sum for the new and old vectors
    summed = current.sum()
    newsummed = new.sum()

    #return the smallest one
    return np.add(((newsummed < summed)*(new)), ((newsummed > summed)*(current))).flatten()

z = np.array(df.apply(new_vectors, args=(df.iloc[0].to_numpy(), df.iloc[11].to_numpy()), axis=1))

matrix = np.zeros(shape=df.shape)

for i,arr in enumerate(z):
     matrix[i] = arr

A: Your original dataframe - with reduced length for display purposes:
In [628]: df = pd.DataFrame(rng.random((4,5)))
In [629]: df
Out[629]:
          0         1         2         3         4
0  0.891169  0.134904  0.515261  0.975586  0.150426
1  0.834185  0.671914  0.072134  0.170696  0.923737
2  0.065445  0.356001  0.034787  0.257711  0.213964
3  0.790341  0.080620  0.111369  0.542423  0.199517

The next frame:
In [631]: df1=df.apply(new_vectors, args=(df.iloc[0].to_numpy(), df.iloc[3].to_numpy()), axis=1)
In [632]: df1
Out[632]:
0    [0.891168725430691, 0.13490384333565053, 0.515...
1    [0.834184861872087, 0.6719141503303373, 0.0721...
2    [0.065444520313796, 0.35600115939269394, 0.034...
3    [0.7903408924058509, 0.08061955595765169, 0.11...
dtype: object

Note that it has 1 column, that contains arrays.  Make an array from it:
In [633]: df1.to_numpy()
Out[633]:
array([array([0.89116873, 0.13490384, 0.51526113, 0.97558562, 0.15042584]),
       array([0.83418486, 0.67191415, 0.07213404, 0.17069617, 0.92373724]),
       array([0.06544452, 0.35600116, 0.03478695, 0.25771129, 0.21396367]),
       array([0.79034089, 0.08061956, 0.1113691 , 0.54242262, 0.19951741])],
      dtype=object)

That is (4,) object dtype.  That dtype is important.  Even though the elements all have 5 elements themselves, reshape does not work across that "object" boundary.  We can't reshape it to (4,5).
But we can concatenate those arrays:
In [636]: np.vstack(df1.to_numpy())
Out[636]:
array([[0.89116873, 0.13490384, 0.51526113, 0.97558562, 0.15042584],
       [0.83418486, 0.67191415, 0.07213404, 0.17069617, 0.92373724],
       [0.06544452, 0.35600116, 0.03478695, 0.25771129, 0.21396367],
       [0.79034089, 0.08061956, 0.1113691 , 0.54242262, 0.19951741]])


Q: Sort a string property that is in a List(of class) In my database project, the user should have a search function.
The search results are saved in a List(of Class_Post). This list should now be sorted alphabetically.
I would like to add that I could already have used:
sorted.Sort(Function(x, y) x.compareto(y))
But the FxCopAnalyzer complained that the sorting could differ due to regional settings, so I now want to use String.Compare (x, y, StringComparison.Ordinal).
The property to be sorted is Class_Post.Ueberschrift. The error is at line 11 (sorted.sort(comparison)): Overload resolution failed because no accessible "Sort" can be called with these arguments:
"Public Overloads Sub Sort (comparer As IComparer (Of Class_Post))": "Option Strict On" does not allow implicit conversions from "Comparison (Of String)" to "IComparer (Of Class_Post)".
Dim sorted As List(Of Class_Post) = Ergebnisse.ToList()

        Select Case Suchmoeglichkeit
            Case Sortiermoeglichkeiten.Alphabetisch ' alphabetical (a String)

                Dim comparison As Comparison(Of String) =
                        Function(x, y)
                            Dim rslt As Integer = x.Length.CompareTo(y.Length)
                            Return rslt
                        End Function
                sorted.Sort(comparison)

            Case Sortiermoeglichkeiten.Erstellzeit 'Creation Time (a Date)
                sorted.Sort(Function(x, y) x.Erstelldatum_dieses_Posts.CompareTo(y.Erstelldatum_dieses_Posts))
            Case Else
                Exit Select
        End Select

        Return sorted

A: You don't want a Comparison(Of String) but a Comparison(Of Class_Post) and you want to compare the Ueberschrift.
Case Sortiermoeglichkeiten.Alphabetisch ' alphabetical (a String)
        Dim comparison As Comparison(Of Class_Post) =
                Function(x, y)
                    Dim rslt As Integer = StringComparer.Ordinal.Compare(x.Ueberschrift, y.Ueberschrift)
                    Return rslt
                End Function
        sorted.Sort(comparison)

A ListOf(Of Class_Post) can just be sorted with a Comparison(Of Class_Post).
Another approach which is easier to read and to maintain is LINQ:
Select Case Suchmoeglichkeit
    Case Sortiermoeglichkeiten.Alphabetisch ' alphabetical (a String)
        Return Ergebnisse.OrderBy(Function(x) x.Ueberschrift).ToList()
    Case Sortiermoeglichkeiten.Erstellzeit 'Creation Time (a Date)
        Return Ergebnisse.OrderBy(Function(x) x.Erstelldatum_dieses_Posts).ToList()
    Case Else
        Exit Select
End Select


Q: Algorithm for Background subtraction I am trying to implement a simple background subtraction method for the detection of moving objects in a particular scene. The objective is to kind of segment out a particular motion out of a video to use it in another video.
The algorithm i am following is:
1. Take the first 25frames from the video and average them to get a background model.
2. Find the standard deviation of those 25frames and store the values in another image.
3. Now i am calculating the absolute difference between each frame and average background model pixel wise.
The output i am getting is kind of a transparent motion being highlighted in white (the absolute differencing is resulting in the transparency i think). I want to know whether my approach is right or not considering that i will be doing a segmentation upon this output as next step? And also i am getting no idea as to how to use the standard deviation image. Any help will be appreciated.
Please let me know if this is not the type of question that i should post in stack overflow. In that case any reference or links to other sites will be helpful.

A: You should take a look at that blog. http://mateuszstankiewicz.eu/?p=189
You will find a start of Answer. Moreover I think there is a specific module for video analysis in Opencv.

A: You said it looks like transparent.
This is what you saw right?→ See YouTube Video - Background Subtraction (approximate median)

The reason is you use the median value of all frames to create the background.
What you saw in white in your video is the difference of your foreground(average image) and your background. Actually, median filtered background subtraction method is simple, but it's not a robust method.
You can try another background subtraction method like Gaussian Mixture Models(GMMs), Codebook, SOBS-Self-organization background subtraction and ViBe background subtraction method.
See YouTube Video - Background Subtraction using Gaussian Mixture Models (GMMs)

A: Try these papers:

*

*Improved adaptive Gaussian mixture model for background subtraction

*Efficient Adaptive Density Estimapion per Image Pixel for the Task of Background Subtraction


Q: Configure all Devise controllers to use a different layout? I have a Rails app which application layout is used to render an AngularJS app.  However, I would like that all the Devise controllers use another layout. I don't need Angular in there.
How can I tell Devise to use a different layout for all its controllers?

A: You probably should review this entry: How To: Create custom layouts.
More or less, you can set it via ApplicationController:
class ApplicationController < ActionController::Base
  layout :layout_by_resource

  protected

  def layout_by_resource
    if devise_controller?
      "layout_name_for_devise"
    else
      "application"
    end
  end
end

Or via configuration (config/application.rb):
config.to_prepare do
  Devise::SessionsController.layout "devise"
  Devise::RegistrationsController.layout proc{ |controller| user_signed_in? ? "application" : "devise" }
  Devise::ConfirmationsController.layout "devise"
  Devise::UnlocksController.layout "devise"
  Devise::PasswordsController.layout "devise"
end


Q: Image data transfer on drag and draw on canvas I am uploading an image from PC. Then I read the file with file reader and display image by creating an img tag. Then I drag the image from the img tag into the canvas and draw it onto canvas. I'm using dragstart and onDrop events. I use datatransfer.setdata() and  datatransfer.getdata() for the functionality. But on drop, the image drawn on canvas is not as original. It is a zoomed version. I don't know why is this happening!
Here is my code:
<!DOCTYPE HTML>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Drag Demo</title>
<link href="copy.css" rel="stylesheet" type="text/css" />

<canvas id = "canvas" style = "position:relative;width:1000px;height:1000px;top:0px;left:200px; border:2px  solid black;" ondrop="dropIt(event);" ondragover="event.preventDefault();"> </canvas>

    <input type="file" id="fileElem" accept="image/*" style="display:none" >

Select some files

A: With canvas there are 2 'size' settings:
Through CSS you'll set the DISPLAY size, so to set the PHYSICAL size of the canvas, you MUST use its attributes. So NO CSS/Style.
Think about it this way: you create a IMAGE with physical size: (let's say) 400px*400px.
Then just as a normal image (jpg,png,gif) that has a physical size, you can still choose to change the DISPLAYED size and thus aspect-ratio: like 800px*600px. Even % is normally supported.
Hope this explains clearly WHY this happened and why your solution in your comment is also the correct solution!!


Q: Argument 2 passed to Controller method must be in instance of Request, none given I'm trying to pass 2 dates from one view to another, in my controller, but I get the following error:
Argument 2 passed to App\Http\Controllers\GuestController::reservationToGuest() must be an instance of Illuminate\Http\Request, none given
This is my first view (the view having the date):
<form action="{{ route('create_guest') }}">
    {{ csrf_field() }}
    <input type="hidden" value="2016-08-26" name="dateOne">
    <input type="hidden" value="2016-08-28" name="dateTwo">
    <button class="btn btn-block btn-success">Proceed To Check In</button>
</form>

(dateOne and dateTwo are the dates which I want in the second view)
routes.php
Route::get('/guest_page/create/{idreservation?}',[
    'uses' => 'GuestController@reservationToGuest',
    'as' => 'create_guest'
]);

reservationToGuest in GuestController
public function reservationToGuest($idreservation = null, Request $request){
    if($idreservation === null){
        return view('guest_page_create', ['idreservation' => 0, 'page_title' => 'Guest Check In', 'check_in_date' => $request['dateOne']]);

    } else{ //else clause works just fine and the dates from the database are inserted into the view
        $details = DB::table('reservation')
            ->where('idreservation', $idreservation)
            ->get();

        return view('guest_page_create', ['idreservation' => $idreservation, 'details' => $details, 'page_title' => 'Guest Check In']);
    }
}

And in view 'guest_page_create'
<label for="datemask">Check In Date</label>
<input type="date" class="form-control" id="datemask" name="datemask" value="{{ $check_in_date }}">

A: You shouldn't pass optional parameters before required ones. Try this:
public function reservationToGuest(Request $request, $idreservation = null)
{
    // ...
}


Q: iOS 14 large titles not working properly when navigating between views Large titles disappear after navigating back and forth within the app. The large title is enabled but when navigating back, it becomes small again. This only happened when updating to iOS 14.


Q: Controlled database insert I have created a script that uses PDO database functions to pull in data from an external feed and insert it into a database, which some days could amount to hundreds of entries.. the page hangs until it's done and there is no real control over it, if there is an error I don't know about it until the page has loaded.
Is there a way to have a controlled insert, so that it will insert X amount, then pause a few seconds and then continue on until it is complete?
During its insert it also executes other queries so it can get quite heavy.
I'm not quite sure what I am looking so have struggled to find help on Google.

A: I would recommend you to use background tasks for that. Pausing your PHP script will not help you in speeding up page loading. Apache (or nginx or any other web-server) sends whole HTTP packet back to browser only when PHP script is completed.
You can use some functions related to output stream and if web-server supports chunked transfer then you can see progress while your page is loading. But for this purpose many developers use AJAX-queries. One query for one chunk of data. And store position of chunk in a session.
But as I wrote at first the better way would be using background tasks and workers. There are many ways of implementation this approach. You can use some specialized services like RabbitMQ, Gearman or something like that. And you can just write your own console application that you will start and check by cron-task.


Q: Node.js get actual memory usage as a percent I have used "os" http://nodejs.org/api/os.html#os_os To attempt to calculate some system stats for use in an app.
However I notice that it cannot actually calculate the memory properly, because it leaves out the cache and buffers witch is needed to properly calculate a single readable percentage. Without it the memory will almost always be 90%+ with most high performance servers (based on my testing).
I would need to calculate it like so:
(CURRENT_MEMORY-CACHED_MEMORY-BUFFER_MEMORY)*100/TOTAL_MEMORY
This should get me a more accurate % of memory being used by the system. But the os module and most other node.js modules I have seen only get me total and current memory.
Is there any way to do this in node.js? I can use Linux but I do not know the ins and outs of the system to know where to look to figure this out on my own (file to read to get this information, like top/htop).

A: Based on Determining free memory on Linux, Free memory = free + buffers + cache.
Following example includes values derived from node os methods for comparison (which are useless)
var spawn = require("child_process").spawn;
var prc = spawn("free", []);
var os = require("os");

prc.stdout.setEncoding("utf8");
prc.stdout.on("data", function (data) {
    var lines = data.toString().split(/\n/g),
        line = lines[1].split(/\s+/),
        total = parseInt(line[1], 10),
        free = parseInt(line[3], 10),
        buffers = parseInt(line[5], 10),
        cached = parseInt(line[6], 10),
        actualFree = free + buffers + cached,
        memory = {
            total: total,
            used: parseInt(line[2], 10),
            free: free,
            shared: parseInt(line[4], 10),
            buffers: buffers,
            cached: cached,
            actualFree: actualFree,
            percentUsed: parseFloat(((1 - (actualFree / total)) * 100).toFixed(2)),
            comparePercentUsed: ((1 - (os.freemem() / os.totalmem())) * 100).toFixed(2)
        };
    console.log("memory", memory);
});

prc.on("error", function (error) {
    console.log("[ERROR] Free memory process", error);
});

Thanks to leorex.
Check for process.platform === "linux"

A: From reading the documentation, I am afraid that you do not have any native solution. However, you can always call 'free' from command line directly. I put together the following code based on
Is it possible to execute an external program from within node.js?
var spawn = require('child_process').spawn;
var prc = spawn('free',  []);

prc.stdout.setEncoding('utf8');
prc.stdout.on('data', function (data) {
  var str = data.toString()
  var lines = str.split(/\n/g);
  for(var i = 0; i < lines.length; i++) {
     lines[i] = lines[i].split(/\s+/);
  }
  console.log('your real memory usage is', lines[2][3]);
});

prc.on('close', function (code) {
    console.log('process exit code ' + code);
});


Q: Serving express static files not working with bundle from webpack :( so I have a node/express app that serves back a bundle.js bundled by webpack.
I've been banging my head at this issue for close to 4 nights and I don't know anymore.
I'm getting the Uncaught SyntaxError: Unexpected token < error as the express static middleware is not catching the request and treating it.
webpack.config.js:
output: {
   path: BUILD_DIR,
   filename: 'bundle.js',
   // https://github.com/webpack/webpack-dev-middleware/issues/205
   // DO NOT leave publicPath out -- it'll cause errors if we do
   publicPath: '/',
},

express middleware:
var serveStatic = require('serve-static')
app.use(serveStatic(
   path.join(__dirname, 'statics'),
))
app.use('/dist', express.static('dist'));
app.use('/statics', express.static('statics'));\

index.html:
    <script src="bundle.js" type="text/javascript"></script>


Q: javascript -I can't understand, why are the first two functions returning 'undefined' but the third one returns the desired value?
Addy(int c) : function to add all the digits of the number and repeat the sum only if it is a single digit. Else, repeat the process
  till it is a single number.

first function :
function addy(c) {
  c = parseInt(c);
  console.log('Recieved Number '+c);
  var sum;
  var nas = c.toString().split(''); // nas --> Number As String.
  console.log('Digits present in Number: '+nas);
  for (var i = 0; i < nas.length; i++) {
    sum = sum + parseInt(nas[i]);
  }
  console.log('Sum is: '+sum);
  if(sum < 9) {
    console.log(typeof sum);
    console.log('value of sum is: '+ sum);
    return sum;
  }
  console.log('Value Still not single digit.');
  addy(sum);
}

Algorithm(that I used in the first function.):

*

*Convert the given number to string.

*Get all the digits present in the numbers by using the split method on the string that has just been created from the number.

*Loop through all the digits, and add to sum.

*If the sum is single digit, then return and if it is not then repeat the process till the sum is single digit.
Second function :
  function addy(c){
     var s=0;
     while(c!==0)
     {
       s = s + parseInt(c%10);

       c = parseInt(c/10);
     }
     if(s>9)
     {
       s = addy(s);
     }
     else if(s<9)
     {
       return s;
     }
   }

Third function :
 (which actually works and is identical to the second function)
   function addy(num)
   {
    var sum = 0;

    while (num > 0)
   {
      sum += parseInt(num % 10);

      num = parseInt(num / 10);
   }
   if (sum > 9)
   {
      sum = addy(sum);
   }
     return sum;
   }

I want to know the reason why the first two functions are returning "undefined" instead of returning a single digit number.

A: First of all, your third function is not identical to your second function.
First function
Fixed code:

function addy(c) {
  c = parseInt(c);
  var sum = 0; // <------- THIS LINE
  var nas = c.toString().split('');
  for (var i = 0; i < nas.length; i++) {
    sum = sum + parseInt(nas[i]);
  }
  if(sum < 9) {
    return sum;
  }
  addy(sum);
}
console.log(addy(123));

Your original code has a line:
var sum;  // sum is undefined

Therefore, when the execution reaches this line:
sum = sum + parseInt(nas[i]);

sum will become NaN because that translate to:
undefined = undefined + parseInt(nas[i]);

To make it work, you simply need to initialise the value of sum:
var sum = 0;   // Give sum a default value;

Second function
Fixed code:

function addy(c){
  var s=0;
  while(c!==0)
  {
   s = s + parseInt(c%10);
   c = parseInt(c/10);
  }
  if(s>9)
  {
   s = addy(s);
   return s;     // <----- THIS LINE
  }
  else
  {
   return s;
  }
}
console.log(addy(1234));

In original code:
if(s>9)
{
  s = addy(s);
}
else
{
  return s;
}

Nothing is being returned if s > 9. Therefore you get undefined.
To make it work, you simply need to add a return line:
if (s > 9){
    s = addy(s);
    return s;    // <--- THIS LINE
} else {
    return s;
}


Q: JavaScript regular expression to remove comma in number comma number "12,56,7abc,fgh" ===> "12567abc,fgh"
"1,245abc,1a" ===> "1245abc,1a"
"1,2,3,4,5abc" ===> "12345abc"

How to remove comma in (number),(number) format?
For the test
const array = ["12,56,7abc,fgh", "1,245abc,1a", "1,2,3,4,5abc"]
const answer = ["12567abc,fgh", "1245abc,1a", "12345abc"]

function formatter(string){
   // here
   return // string.replace('', '') ??
}

array.map((el, i) => {
   const formatted = formatter(el)
   if(answer[i] === formatted){
      console.log('Success. formatted: ', formatted)
   } else {
     console.log('Failed. formatted: ', formatted)
   }
})

A: str.replace(/(?<=\d),(?=\d)/g, '')

(?<=\d): lookbehind - a digit
(?=\d) : lookahead - a digit


Q: Initialize multiple jQuery sliders programatically, each with a different onChange function I'll try and keep this straightforward. I am using jQuery sliders and trying to initialize them all at once using an array:
sliders.push(new slider('paletteControl','pSlider',0,255,100,sliderChange()));

function slider (context, id, min, max, defaultvalue, changeFunc) {
    this.context = context;
    this.id = id;
    this.min = min;
    this.max = max;
    this.defaultvalue = defaultvalue;
    this.changeFunc = changeFunc;

}
Where context is the ID of its intended parent div and changeFunc is the function I want it to call on change.
My Init function loops through this array and appends the markup according to the context, and then tries to init each jquery slider like so:
$(id).slider({
      range: "min",
      min: sliders[i].min,
      max: sliders[i].max,
      value: sliders[i].defaultvalue,
      create: function() {
        handle.text( $( this ).slider( "value" ) );
      },
      change: function() {
          sliders[i].changeFunc();
      }
 });

The min, max, and value inits work fine, presumably since they happen exactly once, during the init, but the change function fails pretty miserably, again presumably because it's simply trying to look up sliders[i] on each change (i being a long dead iterator by that point).
My question is - how can I programatically init a bunch of jquery sliders, each with a different onChange function? Without doing them manually, that is.
EDIT: Got some great help from Ramon de Paula Marques below, though in the end I had to do it a different way altogether because I was unable to pass a value to the function. What I ended up doing, for better or worse, was creating a wrapper function that simply looked up the proper change function once called based on the id of the slider that called it.
function parcelSliderFunction(caller, value)
{
   for (var x = 0; x < sliders.length; x++)
    {
        if(sliders[x].id == caller) {
            sliders[x].callback(value);
            return;
        }
    }

    console.log("id " + caller + " not found, you done screwed up.");
    return;

}

I should probably use a dictionary for this.

A: First you have to remove parentheses of the function as parameter, in this line
sliders.push(new slider('paletteControl','pSlider',0,255,100,sliderChange()));

It becomes
sliders.push(new slider('paletteControl','pSlider',0,255,100,sliderChange));

Then you get the change function like this (without parentheses)
$(id).slider({
      range: "min",
      min: sliders[i].min,
      max: sliders[i].max,
      value: sliders[i].defaultvalue,
      create: function() {
        handle.text( $( this ).slider( "value" ) );
      },
      change: sliders[i].changeFunc
 });

OR
$(id).slider({
      range: "min",
      min: sliders[i].min,
      max: sliders[i].max,
      value: sliders[i].defaultvalue,
      create: function() {
        handle.text( $( this ).slider( "value" ) );
      }
 });

$( id ).on( "slidechange", function( event, ui ) {} );

A: You may call the changeFunc using window[value.changeFunc] as shown below
function newSlider(context, id, min, max, defaultvalue, changeFunc) {
    this.context = context;
    this.id = id;
    this.min = min;
    this.max = max;
    this.defaultvalue = defaultvalue;
    this.changeFunc = changeFunc;
}

function func1() {
    $('#output').append("func1
");
}

function func2() {
    $('#output').append("func2
");
}

function func3() {
    $('#output').append("func3
");
}

var sliders = [];
sliders.push(new newSlider('paletteControl', 'pSlider1', 0, 255, 100, "func1"));
sliders.push(new newSlider('paletteControl', 'pSlider2', 0, 255, 200, "func2"));
sliders.push(new newSlider('paletteControl', 'pSlider3', 0, 255, 70, "func3"));

$.each(sliders, function(index, value) {
    $("#" + value.id).slider({
        range: "min",
        min: value.min,
        max: value.max,
        value: value.defaultvalue,
        change: window[value.changeFunc]
    });
});

Working code: https://plnkr.co/edit/nwjOrnwoI7NU3MY8jXYl?p=preview