Q: Basic file IO in C I am working through the excellent The C Programming Language at the moment, and have got stuck while trying to open and read a file.  The program compiles, but seg faults on execution:
$ ./a.out
Segmentation fault

Here is the code:
#include <stdio.h>

main()
{
  FILE *fp;
  fp=fopen("/home/c-sandbox/index.html", "r");
  fprintf(fp, "Testing...\n");
  fclose(fp);
}

Note that the path points to a real file containing the string "hello, world".
Any ideas on where I am going wrong?

A: *

*Make sure fp is not NULL before trying to write to it. For example:
if(fp == NULL)
{
    fprintf(stderr, "Cannot open file\n");
    return EXIT_FAILURE; // defined in stdlib.h
}

*You need to open the file with something other than "r", which only allows file reading. Read the man page for fopen to find out which mode would work the best for you. Example:

*

*"w" - Truncate to zero length or create file for writing.

*"a" - Append; open or create file for writing at end-of-file.

A: You opened the file for reading only, and are attempting to write to it.
Use "a" if you want to append to the end of the existing file.
Edit: As others have noted, you're also not checking to see if the file was opened. fopen will return NULL if it fails and set the global variable errno to a value that indicates why it failed. You can get a human-readable explanation using strerror(errno)
if( fp == NULL ) {
    printf( "Error opening file: %s\n", strerror( errno ) );
}

A: You are opening it in readonly mode! Need to use w or a for writing/appending to the file :)
fopen("/home/c-sandbox/index.html", "w");

A: You should check that fopen does not return NULL.  I suspect it is returning NULL and either the fprintf and/or fclose calls are getting messed up.

A:  #include <stdio.h>

    main()
    {
      FILE *fp;

      fp=fopen("/home/c-sandbox/index.html", "r");
      if(!fp)
      {
         perror ("The following error occurred");
         return ;
      }

      fgets(line,len,fp);
      printf("%s",line);
      fclose(fp);

     fp=fopen("/home/c-sandbox/index.html", "a");
     if(!fp)
     {
         perror ("The following error occurred");
         return ;
     }
     fprintf(fp, "Testing...\n");
     fclose(fp)

    }

for reading "hello, world" string present in file.
after reading write to the same file "Testing..."


Q: Condensing Wide Data Based on Column Name Is there an elegant way to do what I'm trying to do in Pandas? My data looks something like:
df = pd.DataFrame({
    'alpha': [1, np.nan, np.nan, np.nan],
    'bravo': [np.nan, np.nan, np.nan, -1],
    'charlie': [np.nan, np.nan, np.nan, np.nan],
    'delta': [np.nan, 1, np.nan, np.nan],
})

print(df)

   alpha  bravo  charlie  delta
0    1.0    NaN      NaN    NaN
1    NaN    NaN      NaN    1.0
2    NaN    NaN      NaN    NaN
3    NaN   -1.0      NaN    NaN

and I want to transform that into something like:
  position  value
0    alpha      1
1    delta      1
2      NaN    NaN
3    bravo     -1

So for each row in the original data I want to find the non-NaN value and retrieve the name of the column it was found in. Then I'll store the column and value in new columns called 'position' and 'value'.
I can guarantee that each row in the original data contains exactly zero or one non-NaN values.
My only idea is to iterate over each row but I know that idea is bad and there must be a more pandorable way to do it. I'm not exactly sure how to word my problem so I'm having trouble Googling for ideas. Thanks for any advice!

A: We can use DataFrame.melt to un pivot your data, then use sort_values and drop_duplicates:
df = (
    df.melt(var_name='position')
    .sort_values('value')
    .drop_duplicates('position', ignore_index=True)
)

  position  value
0    bravo   -1.0
1    alpha    1.0
2    delta    1.0
3  charlie    NaN

Another option would be to use DataFrame.bfill over the column axis. Since you noted that:

can guarantee that each row in the original data contains exactly zero or one non-NaN values

values = df.bfill(axis=1).iloc[:, 0]
dfn = pd.DataFrame({'positions': df.columns, 'values': values})

  positions  values
0     alpha     1.0
1     bravo     1.0
2   charlie     NaN
3     delta    -1.0

A: Another way to do this. Actually, I just noticed, that it is quite similar to Erfan's first proposal:
# get the index as a column
df2= df.reset_index(drop=False)
# melt the columns keeping index as the id column
# and sort the result, so NaNs appear at the end
df3= df2.melt(id_vars=['index'])
df3.sort_values('value', ascending=True, inplace=True)
# now take the values of the first row per index
df3.groupby('index')[['variable', 'value']].agg('first')

Or shorter:
(
df.reset_index(drop=False)
.melt(id_vars=['index'])
.sort_values('value')
.groupby('index')[['variable', 'value']].agg('first')
)
The result is:
      variable  value
index
0        alpha    1.0
1        delta    1.0
2        alpha    NaN
3        bravo   -1.0


Q: PDF link in HTML opens up blank page I'm sharing links to PDF files that reside in an external server.
Here is how the links look like:
link 1
link 2

In the above sample page I made (azure domain renamed), the first link opens in Chrome's PDF viewer, the 2nd one however opens in a blank page.
What can be the reason?

A: I think I've found the solution.
When uploading a file to Azure blob, the Azure server isn't smart enough to set the content type of the file according to its extension/content, thus when downloaded by client it's misleading the browser.
The default Azure blob content type is application/octet-stream.
Check here and here for more.


Q: progressdialog bar not working im uploading files and im trying to use progressbar while its uploading
frist of all i start the upload with this code:
@Override
public void onClick(View v) {
    if(v== ivAttachment){

        //on attachment icon click
        showFileChooser();
    }
    if(v== bUpload){

        //on upload button Click
        if(selectedFilePath != null){
            dialog = new ProgressDialog(upload.this);
            dialog.setMax(100);
            dialog.setMessage("Subiendo Archivo...");
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setProgress(0);
            dialog.show();

            //dialog.show(upload.this,"","Subiendo Archivo...",true);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    //creating new thread to handle Http Operations
                    uploadFile(selectedFilePath);
                }
            }).start();

        }else{
            Toast.makeText(upload.this,"Escoge un archivo",Toast.LENGTH_SHORT).show();
        }

    }
}

then uploadFile(selectedFilePath); starts here is my code:
//android upload file to server
    public int uploadFile(final String selectedFilePath){

        int serverResponseCode = 0;
        File sourceFile = new File(selectedFilePath);
        int totalSize = (int)sourceFile.length();

        HttpURLConnection connection;
        DataOutputStream dataOutputStream;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        int bytesRead,bytesAvailable,bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File selectedFile = new File(selectedFilePath);

        String[] parts = selectedFilePath.split("/");
        final String fileName = parts[parts.length-1];

        if (!selectedFile.isFile()){
            dialog.dismiss();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvFileName.setText("Source File Doesn't Exist: " + selectedFilePath);
                }
            });
            return 0;
        }else{
            try{
                FileInputStream fileInputStream = new FileInputStream(selectedFile);
                URL url = new URL(SERVER_URL);
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);//Allow Inputs
                connection.setDoOutput(true);//Allow Outputs
                connection.setUseCaches(false);//Don't use a cached Copy
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("ENCTYPE", "multipart/form-data");
                connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                connection.setRequestProperty("uploaded_file",selectedFilePath);

                //creating new dataoutputstream
                dataOutputStream = new DataOutputStream(connection.getOutputStream());

                //writing bytes to data outputstream
                dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
                dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                        + selectedFilePath + "\"" + lineEnd);

                dataOutputStream.writeBytes(lineEnd);

                //returns no. of bytes present in fileInputStream
                bytesAvailable = fileInputStream.available();
                //selecting the buffer size as minimum of available bytes or 1 MB
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                //setting the buffer as byte array of size of bufferSize
                buffer = new byte[bufferSize];

                //reads bytes from FileInputStream(from 0th index of buffer to buffersize)
                bytesRead = fileInputStream.read(buffer,0,bufferSize);

               int totalBytesWritten = 0;

                        //loop repeats till bytesRead = -1, i.e., no bytes are left to read
                        while (bytesRead > 0) {

                            //write the bytes read from inputstream
                            dataOutputStream.write(buffer, 0, bufferSize);
                            bytesAvailable = fileInputStream.available();
                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                                totalBytesWritten += bytesRead;

                            if (dialog != null) {
                                dialog.setProgress((int)(totalBytesWritten/ totalSize * 100));
                            }

                        }

                dataOutputStream.writeBytes(lineEnd);
                dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                serverResponseCode = connection.getResponseCode();
                String serverResponseMessage = connection.getResponseMessage();

                Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);

                //response code of 200 indicates the server status OK
                if(serverResponseCode == 200){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvFileNames.setText("Sigue el link para ver tu archivo:");
                            tvFileName.setText(Html.fromHtml("" + fileName + " "));
                            tvFileName.setMovementMethod(LinkMovementMethod.getInstance());
                           // tvFileName.setTextColor(Color.BLUE);
                            //tvFileName.setText("Escoger otro archivo");
                            ivAttachment.setVisibility(View.VISIBLE);
                            vView1.setVisibility(View.GONE);
                            tvFileNames.setVisibility(View.VISIBLE);
                            ivAttachment.setImageResource(R.drawable.attach_icon);
                            android.view.ViewGroup.LayoutParams layoutParams = ivAttachment.getLayoutParams();
                            layoutParams.width = 300;
                            layoutParams.height = 300;
                            ivAttachment.setLayoutParams(layoutParams);
                            //POSISION TEXTO
                            RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
                            params.addRule(RelativeLayout.BELOW, R.id.ivAttachment);
                            params.setMargins(0, 73, 0 ,0);
                            RelativeLayout.LayoutParams params1= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
                            params1.addRule(RelativeLayout.BELOW, R.id.tv_file_names);
                            params1.setMargins(0, 123, 0 ,0);
                            tvFileNames.setLayoutParams(params);
                            tvFileName.setLayoutParams(params1);

                            Toast.makeText(getApplicationContext(),
                                    "Archivo subido correctamente!", Toast.LENGTH_LONG)
                                    .show();

                        }
                    });
                }

                //closing the input and output streams
                fileInputStream.close();
                dataOutputStream.flush();
                dataOutputStream.close();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(upload.this,"File Not Found",Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (MalformedURLException e) {
                e.printStackTrace();
                Toast.makeText(upload.this, "URL error!", Toast.LENGTH_SHORT).show();

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(upload.this, "Cannot Read/Write File!", Toast.LENGTH_SHORT).show();
            }
            dialog.dismiss();
            return serverResponseCode;
        }

    }

the problem is here:
int totalBytesWritten = 0;

                        //loop repeats till bytesRead = -1, i.e., no bytes are left to read
                        while (bytesRead > 0) {

                            //write the bytes read from inputstream
                            dataOutputStream.write(buffer, 0, bufferSize);
                            bytesAvailable = fileInputStream.available();
                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                                totalBytesWritten += bytesRead;

                            if (dialog != null) {
                                dialog.setProgress((int)(totalBytesWritten/ totalSize * 100));
                            }

exactly here:

if (dialog != null) {
                                      dialog.setProgress((int)(totalBytesWritten/ totalSize * 100));
                                  }

proggress bar is on 100% all the time

A: onCreate or in your onClick if you want you should new up a Handler
Handler mMainHandler = new Handler(Looper.prepareMainLooper());

then you can use
private void updateUI(){
     mMainHandler.post(new Runnable(){
         //touch dialog
     }
}


Q: How can i call the whole html page to a request handler JavaScript file? I have an html page with a simple form with a post method and a text area  field.
I want to call the whole of this html page to with a local variable and use http write method to return it to the browser.
This is the code snippet of the html.
<!DOCTYPE html>
<html id="upload-htm" lang="en">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload file</title>
  </head>

  <body>
    <form action="/upload" method="post">
      <textarea name="inpt-text" id="in-txt" cols="30" rows="10"></textarea>
      <button type="submit">upload file</button>
    </form>
  </body>
  <script src="./requestHandlers.js"></script>

</html>

Then i also have a requestHandler.js file. My request handler should display the response it gets to the browser.
function start(res) {
  console.log("Request handler 'start' was called");
  let body = document.getElementById('upload-htm');
  res.writeHead(200, {
    "content-type": "text/plain"
  });
  res.write(body);
  res.end();
}

function upload(res) {
  console.log("Request handler 'upload' was called");
  res.writeHead(200, {
    "content-type": "text/plain"
  });
  res.write(`Hello upload Mr. Paullaster`);
  res.end();
}
export {
  start,
  upload
};

When i run the code i get the following error from request handler start
PS C:\Users\paullaster-geek\OneDrive\Desktop\Projects\Dive node> node -r esm
index.js
Response ready
Request for /upload recieved
About to route a request for /upload
Request handler 'upload' was called
Request for /start recieved
About to route a request for /start
Request handler 'start' was called
ReferenceError: document is not defined
at Object.start (C:\Users\paullaster-geek\OneDrive\Desktop\Projects\Dive
node\requestHandlers.js:5:15)
at route (C:\Users\paullaster-geek\OneDrive\Desktop\Projects\Dive
node\router.js:4:28)
at Server.onRequest (C:\Users\paullaster-geek\OneDrive\Desktop\Projects\Dive
node\server.js:11:8)
at Server.emit (events.js:314:20)
at Server.EventEmitter.emit (domain.js:486:12)
at parserOnIncoming (_http_server.js:781:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:119:17)
PS C:\Users\paullaster-geek\OneDrive\Desktop\Projects\Dive node>

A: A website usually consists of two major portions, the server side logic (back-end) and the client side logic (front-end). Both logics usually execute separately from each other, and therefore can only communicate via network channels, and not via logic. This means they do not share variables or data as conventional program logic does.
From the code you have shared, it appears that you are attempting to execute client side logic on your server side application. The document object in JavaScript is used to access and manipulate the DOM within an HTML page. The server side application does not have access to this document object, and therefore its access is invalid. In the server side application's context, document object is undefined.
You can make this work by calling these functions via client side logic. Try registering a function call for upload and start functions against a button click. That will most likely work.

A: NodeJS has a module called files system module. file system module has different methods that can be used to server nodejs static pages. it has:
           const readStream = createReadStream('./staticfile/index.html');
           res.writeHeader(200, {"content-type"}:"text/html");
           readStream.pipe(res)

this sends the html file in chucks of data.
refer here: https://nodejs.org/api/fs.html


Q: Which http request method should I use in Laravel routes? I'm developing a rest api in Laravel 5.7. I know how to make api controllers and how to define appropriate api resource routes referring to corresponding methods in the controller like below:
Route::apiResource('platforms', 'PlatformController');

However, I'm not sure which HTTP request method should I use when I'm trying to define some other methods in my controller rather than the five restful controller methods (index, store, show, update and delete). For example, when in the controller I'm defining a function for toggling a Boolean value in database, either 'Get', 'Post' or 'put' method does works. So, which one is the best choice?

A: Here the basic route descriptions
you can know more from

https://laravel.com/docs/5.7/routing

┌────────┬─────────┬──────────────────────────────────┬────────────────────────┐
│ HTTP   │ CRUD    │ ENTIRE COLLECTION (e.g /USERS)   │ SPECIFIC ITEM          │
│ METHOD │         │                                  │ (e.g. /USERS/123)      │
├────────┼─────────┼──────────────────────────────────┼────────────────────────┤
│ POST   │ Create  │ 201 (Created), 'Location'        │ Avoid using POST       │
│        │         │ with header link to /users/{id}  │ on single resource     │
│        │         │ containing new ID.               │                        │
├────────┼─────────┼──────────────────────────────────┼────────────────────────┤
│ GET    │ Read    │ 200 (OK), list of users. Use     │ 200 (OK), single user  │
│        │         │ pagination, sorting and          │ 404 (Not Found), If ID │
│        │         │ filtering to navigate big lists. │ not found or invalid.  │
├────────┼─────────┼──────────────────────────────────┼────────────────────────┤
│ PUT    │ Update/ │ 404 (Not Found), unless you want │ 200 (OK), or 204 (No   │
│        │ Replace │ to update every resource in the  │ Content). Use 404 (Not │
│        │         │ entire collection of resource.   │ Found). If ID not      │
│        │         │                                  │ found or invalid.      │
├────────┼─────────┼──────────────────────────────────┼────────────────────────┤
│ PATCH  │ Partial │ 404 (Not Found), unless you want │ 200 (OK), or 204 (No   │
│        │ Update/ │ to modify the collection itself. │ Content). Use 404 (Not │
│        │ Modify  │                                  │ Found). If ID not      │
│        │         │                                  │ found or invalid.      │
├────────┼─────────┼──────────────────────────────────┼────────────────────────┤
│ DELETE │ Delete  │ 404 (Not Found), unless you want │ 200 (OK), 404 (Not     │
│        │         │ to delete the whole collection - │ Fpund). If ID not      │
│        │         │ use with caution.                │ found or invalid       │
└────────┴─────────┴──────────────────────────────────┴────────────────────────┘

A: Here are the basic rules to use http method,
GET : When you need to fetch or retrive information
POST : When You need to create or insert information
PUT  : When you need to update existing record
For more information you can use this link.
https://restfulapi.net/http-methods/

A: Adding to the answer by Lokesh in reference to Laravel.
"index" method uses GET REQUEST as it retrieves records from the database.
"store" method uses POST REQUEST as it stores records in the database.
"update" method uses PUT REQUEST as it updates record in the database.
"show" method uses GET REQUEST as it retrieves single record from the database.
"delete" method uses DELETE REQUEST as it retrieves single record from the database.
Therefore you would want to use POST/PUT REQUEST if you want to change the record in the database. While toggling the status, the standard option is to use PUT, as your are updating a record.


Q: How to Diff Files Directly from the Linux Kernel GIT Repository? I'd like to be able to diff files / directories directly from the Linux Kernel GIT repository without having to download full source.
Specifically, I'm interested in two potential solutions:

*

*The ability to do diff's via a web browser ( firefox )

*A GUI utility for Ubuntu that can do remote diffs.

*A tutorial how to setup option #2

Edit
As an example of what I'm looking for, I used to use CrossVC for the above tasks on a CVS repo.

A: Gitweb at kernel.org allows to view diff between arbitrary commits, see for example the following link for diff between v2.6.32-rc6 and v2.6.32-rc7:
http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commitdiff;hp=refs/tags/v2.6.32-rc6;h=refs/tags/v2.6.32-rc7
(use patch link to get plain patch that you can apply), and between arbitrary versions of file / between arbitrary versions of arbitrary files, e.g.: diff to current link in history view.
Unfortunately neither official gitweb version (distributed together with Git itself), nor the fork used by kernel.org generates links between arbitrary commits, so you would have to handcraft (create by hand) URLs to give to gitweb.  In the case of commitdiff view (action) the iparameters you need are 'h' (hash) and 'hp' (hash parent); in the case of blobdiff view they are 'hb' (hash base) and 'hpb' (hash parent base), and also 'f' (filename) and 'fp' (file parent).
Templates

*

*For diff between two arbitrary commits (equivalent of git diff A B from command line)
http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commitdiff;hp=A;h=B

*For diff between two versions of the same file (equivalent of git diff A B <filename>).
http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=blobdiff;f=<filename>;hpb=A;hp=B
Note that core gitweb (but not the fork used by kernel.org, currently) you can use path_info version, e.g.:
http://repo.or.cz/w/git.git/blobdiff/A..B:/<filename>

How to find it

*

*Find in a web interface a commit which is a merge commit, for example
https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=1c5aefb5b12a90e29866c960a57c1f8f75def617

*Find a link to diff between a commit and a second parent, for example
https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/diff/?id=1c5aefb5b12a90e29866c960a57c1f8f75def617&id2=54a217887a7b658e2650c3feff22756ab80c7339

*Replace SHA-1 of compared commits with revision names or revision identifiers you want to compare, for example to generate diff between v3.15-rc8 and v3.15-rc7
https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/diff/?id=v3.15-rc8&id2=v3.15-rc7
or to generate patch (rawdiff)
https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/rawdiff/?id=v3.15-rc8&id2=v3.15-rc7

A: The system which creates the diff (whether that might be your webserver or your local system) must have a full copy (clone) of the git repo.
So you cannot do "remote diffs".
So, if you want to avoid doing a git clone of the whole kernel, why not just point your web browser to http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=summary?

A: Since 2013, the reworked kernel.org website uses cgit to browse repositories.
As an example of cgit URL for a diff between two tags:
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/diff/?id=v3.19-rc2&id2=v3.19-rc1&dt=2

That is also why Git 2.38 (Q3 2022) modified gitweb: gitweb had legacy URL shortener that is specific to the way projects hosted on kernel.org. It used to (but no longer) work, and has been removed.
See commit 75707da (26 Jul 2022) by Julien Rouhaud (rjuju).
(Merged by Junio C Hamano -- gitster -- in commit dcdcc37, 05 Aug 2022)

gitweb: remove title shortening heuristics
Signed-off-by: Julien Rouhaud

Those heuristics are way outdated and too specific to the kernel project to be useful outside of kernel.org.
Since kernel.org doesn't use gitweb anymore and at least one project complained about incorrect behavior, entirely remove them.


Q: Converting PuTTY's svn repository to mercurial repository I'm going to manage a Korean localized version of PuTTY in mercurial.
The requirements for the mercurial repository:

*

*We should be able to keep track of the latest revisions from the PuTTY svn repository.

*No pushing is required.

My plan is to have the original trunk and branches as named branches in the mercurial repository, and to add my own branch.
I'm going to use hgsubversion for continuous pulling after initial conversion.
The problem is, the PuTTY repository (http://svn.tartarus.org/sgt/) is not in the standard layout, and more worse, contains other projects also. DVCS conversion tools work well with standard layout repositories, but not with non-standard ones.
So I have to map the directories to make it "standard" like:

*

*/putty => /trunk

*/putty-0.xx => /tags/0.xx

*/putty-branch-0.xx => /branches/0.xx

*ignore all other directories

If the trunk has every revisions required for the releases, converting only the trunk would be okay.
But unfortunately, the version 0.62 is released at the putty-branch-0.61 branch! So I could not get the latest revisions for it. :(
I'm trying to use svnsync, svnadmin dump and svndumpfilter to convert the original svn repository standard before mercurial conversion, but manual mapping the directories as I want is not possible with them. (Or maybe I don't know how to do it with them.)
Any suggestions and comments?

A: I took a look at the repository. You are correct that svndumpfilter cannot be used to rename a file throughout the history, so I wrote a small script that does the renaming in the dump file. The only tricky part was to add the creation of the tags and branches folder. To use the script, you should make a cronjob or similar that:

*

*downloads the latest Putty SVN dump file:
$ wget http://www.chiark.greenend.org.uk/~sgtatham/putty/putty-svn.dump.gz

*fixes the dump file with the script:
$ zcat putty-svn.dump.gz | fix-dump.py > fixed.dump

*loads it into a new empty repository:
$ svnadmin create putty
$ svnadmin load putty < fixed.dump

*converts the Subversion repository into a Mercurial repository:
$ hg convert file://$PWD/putty
As far as I can see, the branches and tags are created correctly.
You ask for continuous pulling (incremental conversion). Luckily, both hg convert and hgsubversion support this. You'll need to redo steps 1–3 every day before you can convert the changesets into Mercurial. This will work since the first three steps are deterministic. That means that your putty SVN repository behaves as if the Putty developers worked directly in it using the proper branch and tag names you maintain there.
The script is below:

#!/usr/bin/python

import sys, re

moves = [(r"^Node(-copyfrom|)?-path: %s" % pattern, r"Node\1-path: %s" % repl)
         for (pattern, repl) in [(r"putty-branch-(0\...)", r"branches/\2"),
                                 (r"putty-(0\...)", r"tags/\2"),
                                 (r"putty(/|\n)", r"trunk\2")]]

empty_dir_template = """\
Node-path: %s
Node-kind: dir
Node-action: add
Prop-content-length: 10
Content-length: 10

PROPS-END\n\n"""

created_dirs = False
for line in sys.stdin:
    if not created_dirs and line == "Node-path: putty\n":
        sys.stdout.write(empty_dir_template % "tags")
        sys.stdout.write(empty_dir_template % "branches")
        created_dirs = True
    for pattern, repl in moves:
        line, count = re.subn(pattern, repl, line, 1)
        if count > 0: break
    sys.stdout.write(line)

A: I have decided to keep track of ONLY the released source code, not every revision.
So the result is here: https://bitbucket.org/daybreaker/iputty/changesets .
To do this, I have followed these steps (for example):
svn ls -R svn://svn.tartarus.org/sgt/putty-0.58 > 58.txt
svn ls -R svn://svn.tartarus.org/sgt/putty-0.59 > 59.txt
svn ls -R svn://svn.tartarus.org/sgt/putty-0.60 > 60.txt
svn ls -R svn://svn.tartarus.org/sgt/putty-0.61 > 61.txt
svn ls -R svn://svn.tartarus.org/sgt/putty-0.62 > 62.txt

hg init iputty
cd iputty
svn export --force svn://svn.tartarus.org/sgt/putty-0.58 .
hg branch original
hg add
hg commit -m 'Imported PuTTY 0.58 release.'
svn export --force svn://svn.tartarus.org/sgt/putty-0.59 .
diff -U3 ../58.txt ../59.txt
hg add (added files from diff)
hg rm (removed files from diff)
hg commit -m 'Imported PuTTY 0.59 release.'
(repeat this for the remaining releases)

hg up -r(rev# of 0.60 release)
svn export --force (URL of my own modified PuTTY repository) .
hg branch default
hg commit -m 'Imported the most recent dPuTTY source code. blah blah'


Q: Getting an in-memory representation of the JPEG rendering of an Image I need to know how to get an array of bytes from a loaded image, in java. BufferedImage seems not to supply any methods that produce an array of bytes, so what do I use?

A: BufferedImage bufferedImage; //assumed that you have created it already
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage,"jpg", byteStream);
byte[] byteArray = byteStream.toByteArray();


Q: sed only replaces first leading white space match for only a particular file - dealing with CR-only line endings
Editor's note:
The title was amended later with the benefit of hindsight; there were two distinct problems:
(a) it turned out that the input file had \r-only (CR-only) line endings (classic Mac OS-style)
(b) attempts to use \t and \r in sed regexes failed, because BSD Sed (as used on OSX) doesn't support such escapes.

I'm working on an Automator program that uses Python to find-and-replace certain words in a text file. The program uses a dictionary, and there are instances in which the value used as a replacement is '' (meaning, nothing). I don't think that the program is causing this issue, but I just mention this by way of context. (The problem, I think, lies with sed, so I was reluctant to tag Python.)
Some lines in the file have leading white space that are created inadvertently after certain words at the beginning of a file are replaced by nothing. I want to get rid of them, and I think sed is the best tool for the job in this case.
Let's say this is what the text file looks like:
  Display
  Display
 BOX,

So I'm running the edited file through sed using this:
sed -e 's/^[ \t]*//g'

This is the result:
 Display
  Display
 BOX,

Only the first match is edited. Why?
By way of a test, I created a brand new plain text file like this:
 hello
 hello
 hello

Then I ran the command above on it. That actually worked as expected. Why?
Is it possible that there is some other form of space being used (a non-printable character?) that was created by the Python program? But then why would sed work at least once?
By the way, I am open to another portable solution or tool compatible with OS X for trimming leading white space from every line in a plain text file.
Edit: Here is some of the xxd output of the file (replaced most actual content with X):
0000000: 2044 6973 706c 6179 2043 616c 6962 7261   X X
0000010: 7469 6f6e 2046 6978 7475 7265 2046 4952  X X X
0000020: 4d57 4152 4520 4b49 545e 4d20 4469 7370  X X^M X
0000030: 6c61 7920 4361 6c69 6272 6174 696f 6e20  X X
0000040: 4669 7874 7572 6520 524d 6163 426f 6f6b  X X
0000050: 2041 6972 2028 3131 2d69 6e63 682c 204d   X X
0000060: 6964 2032 3031 3229 2050 4f52 5420 4b49  X X) X X
0000070: 545e 4d42 4f58 2c20 5245 434f 5645 5259  T^MBOX, X

A: tl;dr
None of the solutions below update the input file in place; the stand-alone sed commands could be adapted with -i '' to do that; the awk solutions require saving to a different file first.

*

*The OP's input appears to be a file with classic Mac OS \r-only line breaks
Thanks, @alvits.
.

*sed invariably reads such a file as a whole, which is typically undesired and gets in the way of the OP's line-leading whitespace-trimming approach.

*awk is therefore the better choice, because it allow specifying what constitutes a line break (via the so-called input record separator):

Update: Replaced the original awk command with a simpler and faster alternative, adapted from peak's solution:
awk -v RS='\r' '{ sub(/^[ \t]+/, ""); print }'

If it's acceptable to also trim trailing whitespace, if any, from each line and to normalize whitespace between words on a line to a single space each, you can simplify to:
awk -v RS='\r' '{ $1=$1; print }'

Note that the output lines will be \n-separated, as is typically desired.
For an explanation and background information, including how to preserve \r as line breaks, read on.

Note: The first part of the answer applies generally, but assumes that the input has \n-terminated lines; the OP's special case, where lines are apparently \r-only-terminated, is handled in the 2nd part.
BSD Sed, as used on OSX, only supports \n as a control-character escape sequence; thus, \t for matching tab chars. is not supported.
To still match tabs, you can splice an ANSI C-quoted string yielding an actual tab char. into your Sed script ($'\t'):
sed 's/^[ '$'\t'']*//'

In this simple case you could use an ANSI C-quoted string for the entire Sed script (sed -e $'s/^[ \t]*//'), but this can get tricky with more complex scripts, because such strings have their own escaping rules.

*

*Note that option g was removed, because it is pointless, given that the regex is anchored to the start of the input (^).

*For a summary of the differences between GNU and BSD Sed, see this answer of mine.

As @alvits points out in a comment, the input file may actually have \r instances instead of the \n instances that Sed requires to separate lines.
I.e., the file may have Pre-OSX Mac OS line terminators: an \r by itself terminates a line.
An easy way to verify that is to pass the input file to cat -et: \r instances are visualized as ^M, whereas \n instances are visualized as $ (additionally, \t instances are visualized as ^I).
If only ^M instances, but no $ instances are in the output, the implication is that lines aren't terminated with \n (also), and the entire input file is treated as a single string, which explains why only the first input "line" was processed: the ^ only matched at the very beginning of the entire string.
Since a Sed solution (without preprocessing) causes the entire file to be read as a whole, awk is the better choice:
To create \n-separated output, as is customary on Unix-like platforms:
awk -v RS='\r' '{ sub(/^[ \t]+/, ""); print }'

*

*-v RS='\r' tells Awk to split the input into records by \r instances (special variable RS contains the input record separator).

*sub(/^[ \t]+/, "") searches for the first occurrence of regex ^[ \t]+ on the input line and replaces it with "", i.e., it effectively trims a leading run of spaces and tabs from each input line. Note that sub() without an explicit 3rd argument implicitly operates on $0, the whole input line.

*print then prints the potentially modified modified input line.

*By virtue of \n being Awk's default output record separator (OFS), the output records will be \n-terminated.
If you really want to retain \r as the line separator:
awk 'BEGIN { RS=ORS="\r" } { sub(/^[ \t]+/, ""); print }'

*

*RS=ORS="\r" sets both the input and the output record separator to \r.

If it's acceptable to also trim trailing whitespace, if any, from each line and to normalize whitespace between words on a line to a single space each, you can simplify the \n-terminated variant to:
awk -v RS='\r' '{ $1=$1; print }'

*

*Not using -F (and neither setting FS, the input field separator, in the script) means that Awk splits the input record into fields by runs of whitespace (spaces, tabs, newlines).

*$1=$1 is dummy assignment whose purpose is to trigger rebuilding of the input line, which happens whenever a field variable is assigned to.
The line is rebuilt by joining the fields with OFS, the output-field separator, which defaults to a single space.
In effect, leading and trailing whitespace is thereby trimmed, and each run of line-interior whitespace is normalized to a single space.

If you do want to stick with sed1
 - even if that means reading the whole file at once:
sed $'s/^[ \t]*//; s/\r[ \t]*/\\\n/g' # note the $'...' to make \t, \r, \n work

This will output \n-terminated lines, as is customary on Unix.
If, by contrast, you want to retain \r as the line separators, use the following - but note that BSD Sed will invariably add a \n at the very end.
 sed $'s/^[ \t]*//; s/\r[ \t]*/\r/g'

[1] peak's answer originally showed a pragmatic multi-utility alternative more clearly: replace all \r instances with \n instances using tr, and pipe the result to the BSD-Sed-friendly version of the original sed command:
tr '\r' '\n' file | sed $'s/^[ \t]*//'

A: If (as seems to be the case) the input file uses \r as the "end-of-line" character, then whatever else is done, it would probably make sense to convert the '\r' to '\n' or CRLF, depending on the platform. Assuming that '\n' is acceptable, and if there is any point in saving the original file with the CR replaced by LF, you could use tr:
tr '\r' '\n' < INFILE > OUTFILE

With a bash-like shell, you could then invoke sed like so:
sed -e $'s/^[ \t]*//' OUTFILE

The tr and sed commands could of course be strung together (tr ... | sed ...) but that incurs the overhead of a pipeline.
If you have no interest in saving the original file with the CR replaced by LF, then you may wish to consider the following one-stop awk variation:
awk -v RS='[\r]' '{s=$0; sub(/^[ \t]*/,"",s); print s}'

This variation is both fast and safe as no parsing into fields is involved.
(As pointed out elsewhere, one advantage of using awk is that ORS can be used to set the output-record-separator if the default setting is unsatisfactory.)


Q: keep rows that start with certain text strings Background
I have the following df
import pandas as pd
df = pd.DataFrame({'Text' : ['\n[SPORTS FAN]\nHere',
                                   'Nothing here',
                                 '\n[BASEBALL]\nTHIS SOUNDS right',
                                 '\n[SPORTS FAN]\nLikes sports',
                                   'Nothing is here',
                                 '\n[NOT SPORTS]\nTHIS SOUNDS good',
                                 '\n[SPORTS FAN]\nReally Big big fan',
                                  '\n[BASEBALL]\nRARELY IS a fan'
                                ],

                          'P_ID': [1,2,3,4,5,6,7,8],
                          'P_Name' : ['J J SMITH',
                                      'J J SMITH',
                                      'J J SMITH',
                                      'J J SMITH',
                                      'MARY HYDER',
                                      'MARY HYDER',
                                      'MARY HYDER',
                                      'MARY HYDER']
                         })

Output
P_ID    P_Name      Text
0   1   J J SMITH   \n[SPORTS FAN]\nHere
1   2   J J SMITH   Nothing here
2   3   J J SMITH   \n[BASEBALL]\nTHIS SOUNDS right
3   4   J J SMITH   \n[SPORTS FAN]\nLikes sports
4   5   MARY HYDER  Nothing is here
5   6   MARY HYDER  \n[NOT SPORTS]\nTHIS SOUNDS good
6   7   MARY HYDER  \n[SPORTS FAN]\nReally Big big fan
7   8   MARY HYDER  \n[BASEBALL]\nRARELY IS a fan

Goal
Keep rows that start with '\n[SPORTS FAN]\ and \n[BASEBALL]\n
Desired Output
P_ID    P_Name      Text
0   1   J J SMITH   \n[SPORTS FAN]\nHere
2   3   J J SMITH   \n[BASEBALL]\nTHIS SOUNDS right
3   4   J J SMITH   \n[SPORTS FAN]\nLikes sports
6   7   MARY HYDER  \n[SPORTS FAN]\nReally Big big fan
7   8   MARY HYDER  \n[BASEBALL]\nRARELY IS a fan

Question
How do I achieve my desired output?

A: Try this:
df_new = df.loc[df['Text'].str.startswith('\n[SPORTS FAN]') | df['Text'].str.startswith('\n[BASEBALL]')]

No regex required


Q: Scala Mongo driver getting results using Future I am intending to fetch all records that match a criteria from Mongo using Scala Mongo Driver.
Using Observables, you can access the stream by creating a subscription:
val MaxBuffer: Long = 100
var docs: Queue[Document] = Queue.empty
var sub: Option[Subscription] = None

val q: Observable[Document]

def fetchMoreRecords: Unit = sub.get.request(MaxBuffer)

q.subscribe(new Observer[Document] {

  override def onSubscribe(subscription: Subscription): Unit = {
    sub = Some(subscription)
    fetchMoreRecords
  }

  override def onError(e: Throwable): Unit = fail(out, e)

  override def onComplete(): Unit = {
    println("Stream is complete")
    complete(out)
  }

  override def onNext(result: Document): Unit = {
    if (doc.size == maxBuffer) {
      fail(out, new RuntimeException("Buffer overflow"))
    } else {
      docs = docs :+ result
    }
  }

})

(this code is incomplete)
I would need a function like:
def isReady: Future[Boolean] = {}

Which completes whenever onNext was called at least once.
The bad way to do this would be:
def isReady: Future[Boolean] = {
    Future {
        def wait: Unit = {
            if (docs.nonEmpty) {
                true
            } else { wait }
        }
        wait
    }
}

What would be the best way to achieve this?

A: You want to use Promise:
 val promise = Promise[Boolean]()
 ...
 override def onNext() = {
   ...
   promise.tryComplete(Success(true))
}
override def onError(e: Throwable) =
   promise.tryComplete(Failure(e))

val future = promise.future

You should do something to handle the case when there are no result (as it is now, the future will never be satisfied ...


Q: Overload bracket access and assignment C++ I'm writing a hash table for my data structs class, and I'd like to add a little syntactic sugar to my implementation.
template <typename HashedObj, typename Object>
Object & Dictionary<HashedObj, Object>::operator[](HashedObj & key)
{
  return items.lookup(key);
}

That works fine when I do something like cout << dict["mykey"]. But how can I do assignment with the brackets? Something like:
dict["mykey"] = "something";

And no, this isn't part of my homework assignment (no pun intended), I just want to learn C++ a little better.

A: It is not clear what exactly you are asking here. The code that you presented already supports assignment. Just do it and at will work (or at least it should compile). It makes absolutely no difference which side of the assignment operator your overloaded [] is used on. It will work in exactly the same way on left-hand side (LHS) as it does on the right-hand side (RHS) of the assignment (or as an operand of <<, as in your original post). Your [] returns a reference to an Object, and then the actual assignment is handled by the assignment operator of your Object type, meaning that the [] itself is not really involved in the actual assignment.
The real question here is how you want your [] to act in certain special cases. What is going to happen if your key is not present in the table? Reference to what Object is your lookup going to return in this case?
It is impossibe to figure out from what you posted. I see it returns a reference, so returning NULL is out of question. Does it insert a new, empty Object for the given key? If so, then you don't have to do anything. Your [] is already perfectly ready to be used on the LHS of the assigment. (This is how [] in std::map works, BTW)
In case your lookup returns a reference to a special "guard" Object, you have to take special steps. You probably don't want to assign anything to a "guard" object, so you have to "disable" its assignment operator somehow and you are done. The rest should work as is.
If your lookup throws an exception in case of a non-existent key, then you have to decide whether this is what you want when the [] is used on the LHS of an assignment. If so, then you don't need to do anything. If not, then it will take some extra work...
So, again, what happens if you pass a non-existent key to lookup?
P.S. Additionally, it would normally make more sense to declare the [] (and lookup) with either const HashedObj& parameter or just HashedObj parameter. Non-const reference, as in your example, looks strange and might lead to problems in some (actually, in most) cases. I'm surprized it works for you now...

A: You need to overload that 2 times. One that will be const, which will be the data access part, and one that will return a reference, which will act as a "setter".

A: What you're looking for is functionality similar to the overloaded bracket operator in std::map.  In std::map the bracket operator performs a lookup and returns a reference to an object associated with a particular key.  If the map does not contain any object associated with the key, the operator inserts a new object into the map using the default constructor.
So, if you have std::map<K,V> mymap, then calling mymap[someKey] will either return a reference to the value associated with someKey, or else it will create a new object of type V by calling V() (the default constructor of V) and then return a reference to that new object, which allows the caller to assign a value to the object.


Q: Convert varchar column to datetime2 without affecting column data? I need to change column datatype without affecting data in that column. I have table structure below:
CREATE TABLE [dbo].[PROJECT_LOG](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [UNIT] [int] NULL,
    [NAME] [nvarchar](100) NULL,
    [STATUS] [numeric](1, 0) NULL,
    [LOG] [nvarchar](200) NULL,
    [LAST_UPDATE] [nvarchar](100) NULL
) ON [PRIMARY]
GO

Now, I have around 200 records below:

I want to change column LAST_UPDATE (current mm/dd/yyyy format) to datetime2. Can anyone help me with this?
I tried using convert query for the same as the guys suggested below and answer here.
-- Add new column.
ALTER TABLE [dbo].[PROJECT_LOG] ADD LAST_UPDATE_TIME  DATETIME;

-- Convert value.
UPDATE [dbo].[PROJECT_LOG]
   SET LAST_UPDATE_TIME = CONVERT(nvarchar,
REPLACE(LEFT(LAST_UPDATE, 11), '/', ' ') + ' ' + RIGHT(LAST_UPDATE, 8), 101);

While executing query its throwing error:

A: Changing the table
The approach:

*

*Add a column with a substitute with a correct type (date recommended instead of datetime2(7)

*Update this column with Convert( date, LAST_UPDATE, 101 )

*Drop the original column

*Rename the new column to the name of the original column

Important note: Check all the import scripts to this table to fix the functions used to set LAST_UPDATE.
Alternative

*

*Add a column with name LAST_UPDATE_DATE type date as derived column

*Derived column formula: AS Convert( date, LAST_UPDATE, 101 ) [PERSISTED]

*Keep both values as imported and as needed

Important note: If you get any other date format other than US then this formula breaks as it explicitly expects the 101 US format.
View as crazy alternative
Build a view on top of this table that does the transformation. In SQL Server 2008 there is no TRY_CAST function to fail graciously.
Use the view for downstream work.
Why date?
Type date costs 3 bytes and is perfect for date only values.
datetime2(0) costs 6 bytes, the default datetime2(7) costs 8 bytes.
References:
Cast and Convert https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15
Datetime2 https://learn.microsoft.com/en-us/sql/t-sql/data-types/datetime2-transact-sql?view=sql-server-ver15
Try_Cast https://learn.microsoft.com/en-us/sql/t-sql/functions/try-cast-transact-sql?view=sql-server-ver15

A: Since this you are using the 2008 version try_cast will be not helpful.
One safe method will be to implement the update with a loop and go through the entire table row by row with a try catch block within the loop where you can handle in case of any failure at the time of casting , in catch block you can give the query to update the value as NULL  to identify if casting failed.


Q: Web page auto dimming when hover on main menu I have a webpage running magento and it is using vmegamenu.
Now my customer wants to dim the page when someone is hovering on the main menu or the dropdown box.
Example : http://jsfiddle.net/rkLL6yd8/3/
CSS
.link {
  z-index: 700;
  list-style-type: none;
  padding: 0.5em;
  background: black;
  display: inline-block;
  cursor: pointer;
  color: white;
}

.dim {
  width: 100%;
  height: 100%;
  z-index: -6;
  display: none;
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.4);
}

body {
  background-color: orange;
}

JavaScript (jQuery)
$('.link').hover(function() {
  $('.dim').fadeIn(200);
}, function() {
  $('.dim').fadeOut(200);
});

HTML

Home

Main

Home

Home

Some text here

The website is here : www.profileauto.co.uk
I have the current files for vmegamenu
vmegamenu.phtml

<?php echo $this->__('Product Categories') ?>

                <?php $megamenu =  $this->getLayout()->createBlock('megamenu/megamenu'); ?>
                <?php //echo $megamenu->drawMegamenuHome(); ?>
                <?php echo $megamenu->drawMegamenuMain(); ?>
                <?php //echo $megamenu->drawMegamenuExtra(); ?>
                <?php //echo $megamenu->drawMegamenuLink(); ?>

And this file
vmegamenu.css
.nav-vcontainer {
  border-top: 0;
  margin-top: -88px;
  margin-bottom: 20px;
}
.catalog-category-view .main .nav-vcontainer,
.catalog-product-view .main .nav-vcontainer {
  margin-top: -58px;
}
.cms-index-index .nav-vcontainer {
  margin: -48px 0 0 ;
}
.nav-inner {
  position:relative;
}
.vmegamenu-contain { border: 1px solid #f0f0f0; border-top: 0; margin: 0 -1px;}
.nav-vcontainer:hover .vmegamenu-contain { display: block;}
.nav-vcontainer .vmegamenu-title {   }
.nav-vcontainer .vmegamenu-title h2 { color: #fff; font-size: 14px; text-transform: uppercase; padding: 15px; background: #181818; font-weight: normal; margin: 0; font-family: Montserrat; height: 48px;}
.nav-vcontainer .vmegamenu-title h2 i { margin-top: 2px; font-size: 14px; float: right;}

.nav_vmegamenu {
    position:relative;
    margin: 0 auto;
    padding: 0;
    background: #fff;
    border-top: 0;

}

.nav_vmegamenu div.megamenu .level-top { position: relative;}
.nav_vmegamenu div.megamenu .hot,
.nav_vmegamenu div.megamenu .new {
  display: none;
}

.nav_vmegamenu div.megamenu { position:relative; padding: 0; }
.nav_vmegamenu div.megamenu .level-top a {
    padding: 11px 15px;
    text-decoration: none;
    display:block;
    line-height: 30px;
    color: #555;
    border: none;
    text-transform: capitalize;
    margin: 0;
    position: relative;
    border-top: 1px solid #f0f0f0;
    font-size: 14px;
    background: url(../images/icon-menu.png) 0 0 no-repeat;
    padding-left: 45px;
}

.nav_vmegamenu div.megamenu.nav-1 .level-top a { border: 0; background-position: 15px 18px; padding-top: 10px; padding-bottom: 10px; }
.nav_vmegamenu div.megamenu.nav-2 .level-top a { background-position: 15px -36px; padding-top: 10px; padding-bottom: 10px; }
.nav_vmegamenu div.megamenu.nav-3 .level-top a { background-position: 15px -86px; }
.nav_vmegamenu div.megamenu.nav-4 .level-top a { background-position: 15px -137px; }
.nav_vmegamenu div.megamenu.nav-5 .level-top a { background-position: 15px -190px; }
.nav_vmegamenu div.megamenu.nav-6 .level-top a { background-position: 17px -242px; }
.nav_vmegamenu div.megamenu.nav-7 .level-top a { background-position: 17px -294px; }
.nav_vmegamenu div.megamenu.nav-8 .level-top a { background-position: 15px -346px; }
.nav_vmegamenu div.megamenu.nav-9 .level-top a { background-position: 15px -398px; }
.nav_vmegamenu div.megamenu.nav-10 .level-top a { background-position: 15px -450px; }

.nav_vmegamenu div.megamenu .level-top a > .fa,
.nav_vmegamenu div.megamenu .level-top span.block-title > .fa {
    position: absolute; right: 15px; top: 20px;

}

.nav_vmegamenu div.megamenu.megamenu_no_child .level-top a >.fa { display: none;}
.nav_vmegamenu div.megamenu .level-top a .fa-angle-down:before {
  content: "\f0da";
  color: #bababa;
  font-size: 12px;
}

.nav_vmegamenu div.megamenu div.dropdown {
    position: absolute;
    background-color:#fff;
    text-align:left;
    margin: 0 0 0 20px;
    opacity: 0;
    z-index: -1;
    top: 0;
    left: 100% !important;
    border: 1px solid #f0f0f0;
    /*box-shadow: 1px 1px 1px 1px #eee;*/
    border-top: 0;
    width: 935px;
}

.nav_vmegamenu .block1 {
   padding: 25px;
}
.nav_vmegamenu .block2 {

}

.nav_vmegamenu div.megamenu:hover div.dropdown {
    opacity: 1;
    margin: 0;
    z-index: 1000;
}
.nav_vmegamenu div.megamenu.active .level-top a,
.nav_vmegamenu div.megamenu.act .level-top a,
.nav_vmegamenu div.megamenu.active .level-top span.block-title,
.nav_vmegamenu div.megamenu .level-top a:hover,
.nav_vmegamenu div.megamenu .level-top span.block-title:hover,
.nav_vmegamenu #pt_menu_link ul li a.act,
.nav_vmegamenu #pt_menu_link ul li a:hover,
.nav_vmegamenu div.megamenu.act {
    background-color: #00adee;
    color: #fff;
}
.nav_vmegamenu div.megamenu .level-top a:hover .fa-angle-down:before,
.nav_vmegamenu div.megamenu.active .level-top a .fa:before,
.nav_vmegamenu div.megamenu.act .level-top a .fa:before{
  color: #fff;
}
.nav_vmegamenu div.dropdown a {
    display:block;
    line-height: 30px;
}

.nav_vmegamenu .itemMenu h4.level1,
.nav_vmegamenu .itemMenu a.level1{
    font-size: 14px;
    text-transform: uppercase;
    font-weight: bold;
    color: #555555;
    font-family: Montserrat;
}

.megamenu .itemMenu a.level2:before,
.megamenu .itemMenu a.level3:before,
.megamenu .itemMenu a.level4:before{
  content:"\f111";
  margin-right: 10px;
  color: #bababa;
  font-family: FontAwesome;
  font-size: 5px;
  position: relative;
  top: -2px;

}
.megamenu .itemMenu a:hover:before {
  content: "";
  margin: 0;
}

.megamenu .itemMenu a.level2:hover,
.megamenu .itemMenu a.level3:hover,
.megamenu .itemMenu a.level4:hover {
  padding-left: 10px;
}

.nav_vmegamenu .itemSubMenu a.itemMenuName {
    color: #555555;
    text-transform: none;
    font-weight: normal;
    font-size: 13px;
    border-top: 1px solid #ededed;
    line-height: 38px;
    text-transform: capitalize;
}
.nav_vmegamenu div.column {
    float:left;
    width:200px; /* column width */
    margin-right: 5px;
    padding-right: 5px;
}

.nav_vmegamenu div.column.last {
    border-right: 0 none;
    margin-right: 0;
    padding-right: 0;
    width: 250px;
}
.nav_vmegamenu div.itemSubMenu {
  padding-top: 5px;
  margin-bottom: 15px;
}

.nav_vmegamenu .block2{
    float: left;
}
.nav_vmegamenu div.dropdown .block1{
    overflow: hidden;
    float: left;
}
.nav_vmegamenu div.dropdown .block1 .column{
    margin-bottom: -99999px;
    padding-bottom: 99999px;
}
.nav_vmegamenu div.dropdown .blockright img{
    max-width: 100%;
}

.nav_vmegamenu div.megamenu .level-top p{
    margin: 0;
    padding: 0;
}
.nav_vmegamenu #pt_menu_link{
    padding: 0;
}
.nav_vmegamenu #pt_menu_link .level-top ul li{
    float: left;
    list-style: none;
}
.nav_vmegamenu #pt_menu_link .level-top ul li a{
    float: left;
    padding: 0 10px;
    display: block;
}
.nav_vmegamenu .clearBoth {
    clear:both;
}

I am trying to achive what this website has done.
www.johnlewis.co.uk
When you hover on the main menu all the page is dim and dark and only the main menu and drop down is visible.
Please help.


Q: Call Range.Find method with MatchCase parameter I have some Powershell code that is trying to find a particular string in a range of an Excel sheet. It uses the Find method from the excel libraries. Here is the code:
$default = [Type]::Missing
$objRange.find($Search,$default,$default,$xlLookAt::xlPart,$xlSearchOrder::xlByRows,$xlSearchDirection::xlNext, $true ,$default,$default)

What does not work is the $true value I am passing to specify MatchCase mode. I have tried True, $true, -1, "true", etc. True works on ISE command line, but the Powershell ISE editor does not like it.
What do I pass for MatchCase parameter for True, or for False?
Here is the documentation of the Range.Find method.


Q: Authentication failing for Modulr API - Python The API docs are here
The only code example is in Java, here
Every time I try to authenticate I get:
{
    "error": "Authorization field missing, malformed or invalid"
}

I have been through the auth docs many times over and still no luck.
Here is my code:
import requests
import secrets
import codecs

from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime

import hashlib
import hmac
import base64

import urllib.parse

key     = '<API_KEY>'
secret  = '<API_SECRET>'

# Getting current time
now = datetime.now()
stamp = mktime(now.timetuple())

# Formats time into this format --> Mon, 25 Jul 2016 16:36:07 GMT
formated_time = format_date_time(stamp)

# Generates a secure random string for the nonce
nonce = secrets.token_urlsafe(30)

# Combines date and nonce into a single string that will be signed
signature_string = 'date' + ':' + formated_time + '\n' + 'x-mod-nonce' + ':' + nonce

# Expected output example --> date: Mon, 25 Jul 2016 16:36:07 GMT\nx-mod-nonce: 28154b2-9c62b93cc22a-24c9e2-5536d7d

# Encodes secret and message into a format that can be signed
secret = bytes(secret, encoding='utf-8')
message = bytes(signature_string,encoding='utf-8')

# Signing process
digester = hmac.new(secret, message, hashlib.sha1)

# Converts to hex
hex_code = digester.hexdigest()

# Decodes the signed string in hex into base64
b64 = codecs.encode(codecs.decode(hex_code, 'hex'), 'base64').decode()

# Encodes the string so it is safe for URL
url_safe_code = urllib.parse.quote(b64,safe='')

# Adds the key and signed response
authorization = f'Signature keyId="{key}",algorithm="hmac-sha1",headers="date x-mod-nonce",signature="{url_safe_code}"'

account_id = 'A120BU48'

url = f'https://api-sandbox.modulrfinance.com/api-sandbox/accounts/{account_id}'

headers = {
    'Authorization': authorization, # Authorisation header
    'Date' : formated_time,         # Date header
    'x-mod-nonce': nonce,           # Addes nonce
    'accept': 'application/json',
    }

response = requests.get(url,headers=headers)

print(response.text)

I am not sure where the process is going wrong, as far as I know, the signature is being signed correctly as I added in the test data from the authentication example and I get the expected string.
If you want to try with real API keys, register for access here
The docs for the API endpoint I am trying to call is here

A: The docs you linked has a space between the colon and the values.
signature_string = 'date' + ':' + formated_time + '\n' + 'x-mod-nonce' + ':' + nonce
should be:
signature_string = 'date' + ': ' + formated_time + '\n' + 'x-mod-nonce' + ': ' + nonce
or (simpler):
signature_string = 'date: ' + formated_time + '\n' + 'x-mod-nonce: ' + nonce
Update
I registered to see what is going on. I also ran your code on the example given in the documentation and saw that the signature is not entirely correct.
In addition to the change I suggested above, a further change was necessary.
After changing the line
b64 = codecs.encode(codecs.decode(hex_code, 'hex'), 'base64').decode()

to
b64 = codecs.encode(codecs.decode(hex_code, 'hex'), 'base64').decode().strip()

the signature of the example matched.
After this I was able to connect to the API with my own keys.
Here is the complete working code:
import codecs
import hashlib
import hmac
import secrets
import urllib.parse
from datetime import datetime
from time import mktime
from wsgiref.handlers import format_date_time

import requests

key = '<key>'
secret = '<secret>'
account_id = '<account id>'
url = f'https://api-sandbox.modulrfinance.com/api-sandbox/accounts/{account_id}'

# Getting current time
now = datetime.now()
stamp = mktime(now.timetuple())

# Formats time into this format --> Mon, 25 Jul 2016 16:36:07 GMT
formatted_time = format_date_time(stamp)

# Generates a secure random string for the nonce
nonce = secrets.token_urlsafe(30)

# Combines date and nonce into a single string that will be signed
signature_string = 'date' + ': ' + formatted_time + '\n' + 'x-mod-nonce' + ': ' + nonce

# Encodes secret and message into a format that can be signed
secret = bytes(secret, encoding='utf-8')
message = bytes(signature_string, encoding='utf-8')

# Signing process
digester = hmac.new(secret, message, hashlib.sha1)

# Converts to hex
hex_code = digester.hexdigest()

# Decodes the signed string in hex into base64
b64 = codecs.encode(codecs.decode(hex_code, 'hex'), 'base64').decode().strip()

# Encodes the string so it is safe for URL
url_safe_code = urllib.parse.quote(b64, safe='')

# Adds the key and signed response
authorization = f'Signature keyId="{key}",algorithm="hmac-sha1",headers="date x-mod-nonce",signature="{url_safe_code}"'

headers = {
    'Authorization': authorization,  # Authorisation header
    'Date': formatted_time,  # Date header
    'x-mod-nonce': nonce,  # Adds nonce
    'accept': 'application/json',
}

response = requests.get(url, headers=headers)

print(response.text)


Q: Duplicate function name in Class View when defined in a namespace I'm using Visual Studio Professional 2013 Update 4.
I've defined a couple functions in my header file:
class CFileReader;
class CFileWriter;

namespace FileFixer
{
    bool makeFixedFileName ( const wchar_t* inFile , wchar_t* outFile , size_t maxLen );
    bool fixFile ( CFileReader& fileReader , CFileWriter& fileWriter );
}

And in the source file:
#include "FileReader.h"
#include "FileWriter.h"

namespace FileFixer
{
    bool makeFixedFileName ( const wchar_t* inFile , wchar_t* outFile , size_t maxLen )
    {
        // Do something here ...
        return true;
    }
    bool fixFile ( CFileReader& fileReader , CFileWriter& fileWriter )
    {
        // Do something more here ...
        return true;
    }
}

In the Class View pane the functions name are repeated, but the first name got a small white arrow behind the 3d purple box icon like this:

If I right click on both of them the menu is the same, if I double click also the behaviour is identical. I didn't find anything on the online help here. What is this for?

A: Ideally, it should hardly matter to you. But I see the arrow in my code base for the functions implemented outside the class-declaration (i.e. into implementation file). All inline methods are shown without the arrow symbol.
I am not sure why they are duplicated in your case. May be namespace implementation has something to do.
But, again - why does it matter?


Q: Invoking std::thread with pointer to freestanding function I tried to invoke std::thread perfect forwarding constructor (template< class Function, class... Args > explicit thread( Function&& f, Args&&... args );) with a pointer to function (NOT a pointer to member function), as shown in the following M(N)WE:
#include <thread>
#include <string>

static void foo(std::string query, int & x)
{
  while(true);
}

int main() {
 int i = 1;
 auto thd = std::thread(&foo, std::string("bar"), i);
 thd.join();
}

Live demo: https://godbolt.org/g/Cwi6wd
Why does the code not compile on GCC, Clang and MSVC, complaining about a missing overload of invoke (or similar names)?
A function argument is a pointer to a function, so it should be a Callable, right?
Please note: I know that using a lambda would solve the problem; I want to understand why the problem arises.

A: std::thread stores copies of the arguments it is passed. Which as Massimiliano Janes pointed out, is evaluated in the context of the caller to a temporary. For all intents and purposes, it's better to consider it as a const object.
Since x is a non-const reference, it cannot bind to the argument being fed to it by the thread.
If you want x to refer to i, you need to use std::reference_wrapper.
#include <thread>
#include <string>
#include <functional>

static void foo(std::string , int & )
{
  while(true);
}

int main() {
 int i = 1;
 auto thd = std::thread(foo, std::string("bar"), std::ref(i));
 thd.join();
}

Live Example
The utility std::ref will create it on the fly.

A: std::thread constructor performs a decay_copy on its arguments before invoking the callable perfect-forwarding the result to it; in your foo, you're trying to bind a lvalue reference (int& x) to an rvalue reference (to the temporary), hence the error; either take an int, an int const& or an int&& instead ( or pass a reference wrapper ).

A: Following on from StoryTeller's answer, a lambda may offer a clearer way to express this:
I think there are a couple of scenarios:
If we really do want to pass a reference to i in our outer scope:
 auto thd = std::thread([&i]
 {
     foo("bar", i);
 });

And if foo taking a reference just happens to be an historical accident:
 auto thd = std::thread([]() mutable
 {
     int i = 1;
     foo("bar", i);
 });

In the second form, we have localised the variable i and reduced the risk that it will be read or written to outside the thread (which would be UB).


Q: App crashes on higher versions of android I have been creating an app, built on target sdk version 15 and with minimum sdk version of 8. Every thing is running perfect when I run it on a devices running version 8. But when I try it on anything higher than version 10 it crashes with a NullPointerException.
The logcat gives me this:
10-06 19:23:12.927: E/AndroidRuntime(589): FATAL EXCEPTION: main
10-06 19:23:12.927: E/AndroidRuntime(589): java.lang.RuntimeException: Unable to start                 activity        ComponentInfo{com.fansheroid.facts.chicks/com.fansheroid.facts.chicks.MainActivity}:   java.lang.NullPointerException
10-06 19:23:12.927: E/AndroidRuntime(589):  at     android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
10-06 19:23:12.927: E/AndroidRuntime(589):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
10-06 19:23:12.927: E/AndroidRuntime(589):  at android.app.ActivityThread.access$600(ActivityThread.java:122)
10-06 19:23:12.927: E/AndroidRuntime(589):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
10-06 19:23:12.927: E/AndroidRuntime(589):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-06 19:23:12.927: E/AndroidRuntime(589):  at android.os.Looper.loop(Looper.java:137)
10-06 19:23:12.927: E/AndroidRuntime(589):  at android.app.ActivityThread.main(ActivityThread.java:4340)
10-06 19:23:12.927: E/AndroidRuntime(589):  at java.lang.reflect.Method.invokeNative(Native Method)
10-06 19:23:12.927: E/AndroidRuntime(589):  at java.lang.reflect.Method.invoke(Method.java:511)
10-06 19:23:12.927: E/AndroidRuntime(589):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-06 19:23:12.927: E/AndroidRuntime(589):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-06 19:23:12.927: E/AndroidRuntime(589):  at dalvik.system.NativeStart.main(Native Method)
10-06 19:23:12.927: E/AndroidRuntime(589): Caused by: java.lang.NullPointerException
10-06 19:23:12.927: E/AndroidRuntime(589):  at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
10-06 19:23:12.927: E/AndroidRuntime(589):  at org.json.JSONTokener.nextValue(JSONTokener.java:94)
10-06 19:23:12.927: E/AndroidRuntime(589):  at org.json.JSONObject.<init>(JSONObject.java:154)
10-06 19:23:12.927: E/AndroidRuntime(589):  at org.json.JSONObject.<init>(JSONObject.java:171)
10-06 19:23:12.927: E/AndroidRuntime(589):  at com.fansheroid.facts.chicks.MainActivity.getTumblrs(MainActivity.java:156)
10-06 19:23:12.927: E/AndroidRuntime(589):  at com.fansheroid.facts.chicks.MainActivity.onCreate(MainActivity.java:62)
10-06 19:23:12.927: E/AndroidRuntime(589):  at android.app.Activity.performCreate(Activity.java:4465)
10-06 19:23:12.927: E/AndroidRuntime(589):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
10-06 19:23:12.927: E/AndroidRuntime(589):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
10-06 19:23:12.927: E/AndroidRuntime(589):  ... 11 more

I have been trying to figure out the problem for the past two days, but it just doesn't make sense for me.
EDIT ADDED CODE
public ArrayList<Tumblr> getTumblrs() throws ClientProtocolException,
        IOException, JSONException {
    String searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=API_KEY";

    ArrayList<Tumblr> tumblrs = new ArrayList<Tumblr>();

    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(searchUrl);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    String responseBody = null;
    try {
        responseBody = client.execute(get, responseHandler);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    JSONObject jsonObject = new JSONObject(responseBody);

    JSONArray posts = jsonObject.getJSONObject("response").getJSONArray(
            "posts");
    for (int i = 0; i < posts.length(); i++) {
        JSONArray photos = posts.getJSONObject(i).getJSONArray("photos");
        for (int j = 0; j < photos.length(); j++) {
            JSONObject photo = photos.getJSONObject(j);
            String url = photo.getJSONArray("alt_sizes").getJSONObject(0)
                    .getString("url");

            Tumblr tumblr = new Tumblr(url);
            tumblrs.add(tumblr);
        }
    }
    return tumblrs;
}

Line 156:
JSONObject jsonObject = new JSONObject(responseBody);

A: Ah, look at this:
E/AndroidRuntime(589): Caused by: java.lang.NullPointerException 10-06 19:23:12.927:
E/AndroidRuntime(589): at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116) 10-06 19:23:12.927:
E/AndroidRuntime(589): at org.json.JSONTokener.nextValue(JSONTokener.java:94) 10-06 19:23:12.927:
E/AndroidRuntime(589): at org.json.JSONObject.(JSONObject.java:154) 10-06 19:23:12.927:
E/AndroidRuntime(589): at org.json.JSONObject.(JSONObject.java:171) 10-06 19:23:12.927:
E/AndroidRuntime(589): at com.fansheroid.facts.chicks.MainActivity.getTumblrs(MainActivity.java:156) 10-06 19:23:12.927:
E/AndroidRuntime(589): at com.fansheroid.facts.chicks.MainActivity.onCreate(MainActivity.java:62)

It basically says the JSON parser fails: you're probably passing NULL on line 156 of MainActivity.java. You should check the value at that line and see if your device upgrade hasn't somehow wiped out a value or failed to retrieve a value correctly.

A: try {
    responseBody = client.execute(get, responseHandler);
} catch (Exception ex) {
    ex.printStackTrace();
}

That section of code is where your response is failing. You assign null to responsebody, chances are that your call there is failing so that responsebody is still null when it hits line 156.
Try looking in your debug output for the ex.printStackTrace(); output to see what is going on.

A: Solved the problem by using HttpResponse and HttpEntity instead of ResponseHandler, and this solved the problem.


Q: Android charting library with inbuilt support to plot graph for days, weeks, months and years break down from input data Is there any charting library in Android that has built-in support to plot graph for days, weeks, months and years break down of input data.
How to develop a graph which looks like this ?

A: Looks like no library has built-in support to show data grouped by day, week, month and year, etc. So we are doing it ourselves.


Q: Byte buffer transfer via UDP Can you provide an example of a byte buffer transferred between two java classes via UDP datagram?

A: Hows' this ?

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class Server {

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(new InetSocketAddress(5000));
        byte[] message = new byte[512];
        DatagramPacket packet = new DatagramPacket(message, message.length);
        socket.receive(packet);
        System.out.println(new String(packet.getData(), packet.getOffset(), packet.getLength()));
    }
}

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class Client {

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket();
        socket.connect(new InetSocketAddress(5000));
        byte[] message = "Oh Hai!".getBytes();
        DatagramPacket packet = new DatagramPacket(message, message.length);
        socket.send(packet);
    }
}

A: @none
The DatagramSocket classes sure need a polish up, DatagramChannel is slightly better for clients, but confusing for server programming. For example:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class Client {

    public static void main(String[] args) throws IOException {
        DatagramChannel channel = DatagramChannel.open();
        ByteBuffer buffer = ByteBuffer.wrap("Oh Hai!".getBytes());
        channel.send(buffer, new InetSocketAddress("localhost", 5000));
    }
}

Bring on JSR-203 I say


Q: Query takes almost two seconds but matches only two rows - why isn't the index helping? Table:
CREATE TABLE `Alarms` (
  `AlarmId` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `DeviceId` BINARY(16) NOT NULL,
  `Code` BIGINT(20) UNSIGNED NOT NULL,
  `Ended` TINYINT(1) NOT NULL DEFAULT '0',
  `NaturalEnd` TINYINT(1) NOT NULL DEFAULT '0',
  `Pinned` TINYINT(1) NOT NULL DEFAULT '0',
  `Acknowledged` TINYINT(1) NOT NULL DEFAULT '0',
  `StartedAt` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
  `EndedAt` TIMESTAMP NULL DEFAULT NULL,
  `MarkedForDeletion` TINYINT(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`AlarmId`),
  KEY `Key1` (`Ended`,`Acknowledged`),
  KEY `Key2` (`Pinned`),
  KEY `Key3` (`DeviceId`,`Pinned`),
  KEY `Key4` (`DeviceId`,`StartedAt`,`EndedAt`),
  KEY `Key5` (`DeviceId`,`Ended`,`EndedAt`),
  KEY `Key6` (`MarkedForDeletion`),

  KEY `KeyB` (`MarkedForDeletion`,`DeviceId`,`StartedAt`,`EndedAt`,`Acknowledged`,`Pinned`)
) ENGINE=INNODB;

It currently has about three million rows in it.
Query:
SELECT
COUNT(`AlarmId`) AS `n`
FROM `Alarms`
WHERE `StartedAt` < FROM_UNIXTIME(1519101900)
AND (`EndedAt` IS NULL OR `EndedAt` > FROM_UNIXTIME(1519101900))
AND `DeviceId` = UNHEX('00030000000000000000000000000000')
AND `MarkedForDeletion` = FALSE
AND (
     (`Alarms`.`EndedAt` IS NULL AND `Alarms`.`Acknowledged` = FALSE)
  OR ( `Alarms`.`EndedAt` IS NOT NULL AND `Alarms`.`Pinned` = TRUE)
)

Query plan:
id      select_type     table   type    possible_keys   key     key_len ref     rows    Extra
1       SIMPLE  Alarms  range   Key2,Key3,Key4,Key5,Key6,KeyB   KeyB    21              1574778 Using where; Using index

Elapsed time: 1,763,222μs
In this particular case the query (correctly) doesn't even match many rows (the result is n = 2).
Taking what I learnt from working with index merges (though I still haven't got that right), I tried reorganising the conditions a bit (the original was generated by some C++, based on input conditions, hence the strange operator distribution):
SELECT COUNT(`AlarmId`) AS `n`
FROM `Alarms`
WHERE
(
    `EndedAt` IS NULL
    AND `Acknowledged` = FALSE

    AND `StartedAt` < FROM_UNIXTIME(1519101900)
    AND `MarkedForDeletion` = FALSE
    AND `DeviceId` = UNHEX('00030000000000000000000000000000')
) OR (
    `EndedAt` > FROM_UNIXTIME(1519101900)
    AND `Pinned` = TRUE

    AND `StartedAt` < FROM_UNIXTIME(1519101900)
    AND `MarkedForDeletion` = FALSE
    AND `DeviceId` = UNHEX('00030000000000000000000000000000')
);

…but the result is the same.
So why does it take so long? How can I modify it / the indexes to make it work instantly?

A: I think the problem is that I was trying to use a range condition halfway through the index.
I added a key on:
(`MarkedForDeletion`,`DeviceId`,`Acknowledged`,`Ended`,`StartedAt`)

Then rewrote the query to this:
SELECT COUNT(`AlarmId`) AS `n`
FROM `Alarms`
WHERE
(
    `Ended` = FALSE
    AND `Acknowledged` = FALSE

    AND `StartedAt` < FROM_UNIXTIME(1519101900)
    AND `MarkedForDeletion` = FALSE
    AND `DeviceId` = UNHEX('00030000000000000000000000000000')
) OR (
    `EndedAt` > FROM_UNIXTIME(1519101900)
    AND `Pinned` = TRUE

    AND `StartedAt` < FROM_UNIXTIME(1519101900)
    AND `MarkedForDeletion` = FALSE
    AND `DeviceId` = UNHEX('00030000000000000000000000000000')
);

Now I get an index merge and the query is instant.

A: *

*OR is notoriously hard to optimize.

*MySQL almost never uses two indexes in a single query.

To avoid both of those, turn OR into UNION.  Each SELECT can use its a different index.  So, build an optimal INDEX for each.
Actually, since you are only doing COUNT, you may as well evaluate two separate counts and add them.
SELECT ( SELECT  COUNT(*)
            FROM  `Alarms`
            WHERE  `EndedAt` IS NULL
              AND  `Acknowledged` = FALSE
              AND  `StartedAt` < FROM_UNIXTIME(1519101900)
              AND  `MarkedForDeletion` = FALSE
              AND  `DeviceId` = UNHEX('00030000000000000000000000000000' )
       ) +
       ( SELECT  COUNT(*)
            FROM  `Alarms`
            WHERE  `EndedAt` > FROM_UNIXTIME(1519101900)
              AND  `Pinned` = TRUE
              AND  `StartedAt` < FROM_UNIXTIME(1519101900)
              AND  `MarkedForDeletion` = FALSE
              AND  `DeviceId` = UNHEX('00030000000000000000000000000000')
       ) AS `n`;

INDEX(DeviceId, Acknowledged, MarkedForDeletion, EndedAt, StartedAt) -- for first
INDEX(DeviceId, Pinned, MarkedForDeletion, EndedAt, StartedAt) -- for second
INDEX(DeviceId, Pinned, MarkedForDeletion, StartedAt, EndedAt) -- for second

Well, that won't work if there is overlap.  So, let's go back to the UNION pattern:
SELECT  COUNT(*) AS `n`
    FROM
    (
        ( SELECT  AlarmId
            FROM  `Alarms`
            WHERE  `EndedAt` IS NULL
              AND  `Acknowledged` = FALSE
              AND  `StartedAt` < FROM_UNIXTIME(1519101900)
              AND  `MarkedForDeletion` = FALSE
              AND  `DeviceId` = UNHEX('00030000000000000000000000000000')
        )
        UNION DISTINCT
        ( SELECT  AlarmId
            FROM  `Alarms`
            WHERE  `EndedAt` > FROM_UNIXTIME(1519101900)
              AND  `Pinned` = TRUE
              AND  `StartedAt` < FROM_UNIXTIME(1519101900)
              AND  `MarkedForDeletion` = FALSE
              AND  `DeviceId` = UNHEX('00030000000000000000000000000000')
         )
    );

Again, add those indexes.
The first few columns in each INDEX can be in any order, since they are tested with = (or IS NULL).  The last one or two are "range" tests.  Only the first range will be used for filtering, but I included the other column so that the index would be "covering".
My formulations may be better than "index merge".


Q: Ajax post works on localhost, but not on nginx server I was experimenting with building a small CMS for a project. Part of it was, that when you click on the save-button your current edits will be saved.
$('.save-button').click(function() {

  var speisekarte_content = $(".speisekarte-content").html();
  console.log(speisekarte_content);
  var ajaxurl = 'save.php',
    data = {
      'content': speisekarte_content
    };
  $.post(ajaxurl, data, function(response) {
    alert("action performed successfully");
  });

});

The save.php looks like this:
<?php

$post_data = $_POST['content'];

if (function_exists('fopen')) {
    if (!empty($post_data)) {
        $filename = 'speisekarte-content.php';
        $handle = fopen($filename, "w");
        fwrite($handle, $post_data);
        fclose($handle);
        echo $file;
    }
};

?>

So it basically just adds the content that should be saved to a file called speisekarte-content.php … This worked perfectly on localhost – until I uploaded it to my nginx server and it stopped working as supposed.
This is the error log that I found in the javascript console:
POST
http://www.myurl.com/editable/save.php net::ERR_TIMED_OUT

k.cors.a.crossDomain.send @ jquery.min.js:4
n.extend.ajax @ jquery.min.js:4
n.(anonymous function) @ jquery.min.js:4
(anonymous function) @ main.js:99

The nginx error logs are the following
2015/06/22 08:43:45 [error] 6804#0: *63817 FastCGI sent in stderr: "PHP message: PHP Notice:  Undefined index: content in /var/www/myurl.com/html/editable/save.php on line 2
PHP message: PHP Warning:  fopen(autosave.php): failed to open stream: Permission denied in /var/www/myurl.com/html/editable/save.php on line 27
PHP message: PHP Warning:  fwrite() expects parameter 1 to be resource, boolean given in /var/www/myurl.com/html/editable/save.php on line 28
PHP message: PHP Warning:  fclose() expects parameter 1 to be resource, boolean given in /var/www/myurl.com/html/editable/save.php on line 29
PHP message: PHP Notice:  Undefined variable: file in /var/www/myurl.com/html/editable/save.php on line 30" while reading response header from upstream, client: 176.0.1.54, server: myurl.com, request: "POST /editable/save.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "www.myurl.com", referrer: "http://www.myurl.com/editable/"

Is this related to nginx or my code?

A: Your log say that your application don't have the right to write in his current emplacement.
Your should check the right on your file
can you post the output of a ls -al in your app's folder ?


Q: Uncaught RangeError: noUiSlider I'm trying to add few sliders on website and I got stucked. I've downloaded nouislider script directly from their website and before that, I added jQuery 1.8.0 to my website. This is what I produced:
index.html

   ...
   <link rel="stylesheet" href="Content/noUiSlider/jquery.nouislider.css" type="text/css">

   ...

   ...

   ...

website.js
(function () {
   $("#sslider").noUiSlider({
       start: 5,
       range: {
           'min': 1,
           'max': 80
       }
   });
})();

When I debug in Chrome, I' catching exactly this:

Can you help me?

A: I copied your example into a test file, and it works fine. I also can't see how the error message in your example could be generated by the current version of noUiSlider, so I'd suggest using the latest version of noUiSlider and the latest version of jQuery.
It would also be a good idea to only run this JS after the page has loaded, like this:
$(function() {
    $("#sslider").noUiSlider({
        start: 5,
        range: {
            'min': 1,
            'max': 80
        }
    });
});

A: Ok, problem solved. I have downloaded jquery.nouislider.js from NuGet (from VisualStudio 2013) and they provided me older or broken file. I thought the file was from website, but I browsed NuGet and noticed, that I have already downloaded from there.
There is no problem with code but with file. Lesson: before asking question, compare official files with those you already have installed.

A: Try to follow the official docs:
$("#slider").noUiSlider({
    start: [5],
    connect: true,
    range: {
        'min': 1,
        'max': 80
    }
});


Q: Settings Array in C++ My aim is to set up a data structure to store the settings of my application.
In PHP I would just write...
$settings = array(
    "Fullscreen" => true,
    "Width"      => 1680,
    "Height"     => 1050,
    "Title"      => "My Application",
);

Now I tried to create a similar structure in C++ but it can't handle different datatypes yet. By the way if there is a better way of storing such settings data, please let me know.
struct Setting{ string Key, Value; };

Setting Settings[] = {
    ("Fullscreen", "true"),     // it's acceptable to store the boolean as string
    ("Width", "1680"),          // it's not for integers as I want to use them later
    ("Height", 1050),           // would be nice but of course an error
    ("Title", "My Application") // strings aren't the problem with this implementation
};

How can I model a structure of an associative array with flexible datatypes?

A: An associative data structure with varying data types is exactly what a struct is...
struct SettingsType
{
    bool Fullscreen;
    int Width;
    int Height;
    std::string Title;
} Settings = { true, 1680, 1050, "My Application" };

Now, maybe you want some sort of reflection because the field names will appear in a configuration file?  Something like:
SettingsSerializer x[] = { { "Fullscreen", &SettingsType::Fullscreen },
                           { "Width",      &SettingsType::Width },
                           { "Height",     &SettingsType::Height },
                           { "Title",      &Settings::Title } };

will get you there, as long as you give SettingsSerializer an overloaded constructor with different behavior depending on the pointer-to-member type.

A: C++ is a strongly typed language. The containers hold exactly one type of object so by default what you are trying to do cannot be done with only standard C++.
On the other hand, you can use libraries like boost::variant or boost::any that provide types that can hold one of multiple (or any) type, and then use a container of that type in your application.
Rather than an array, you can use std::map to map from the name of the setting to the value:
std::map<std::string, boost::variant<bool,int,std::string> >

A: #include <map>
#include <string>

std::map<std::string,std::string> settings;

settings.insert("Fullscreen","true");
settings.insert("Width","1680");
settings.insert("Height","1050");
settings.insert("Title","My Application");

Could be one way of doing it if you want to stick with the STL.

A: One solution could be to define the ISetting interface like:
class ISetting{
public:
  virtual void save( IStream* stream ) = 0;
  virtual ~ISetting(){}
};

after that you can use a map in order to store your settings:
std::map< std::string, ISetting* > settings;

One example of the boolean setting is:
class BooleanSetting : public ISetting{
private:
  bool m_value;
public:
  BooleanSetting(bool value){
    m_value = value
  }

  void save( IStream* stream ) {
    (*stream) << m_value;
  }

  virtual ~BooleanSetting(){}
};

in the end:
settings["booleansetting"]=new BooleanSetting(true);
settings["someothersetting"]=new SomeOtherSetting("something");

A: One possible solution is to create a Settings class which can look something like
class Settings {
    public:
        Settings(std::string filename);

        bool getFullscreen() { return Fullscreen; }
        // ...etc.

    private:
        bool Fullscreen;
        int Width;
        int Height;
        std::string Title;
};

This assumes that the settings are stored in some file. The constructor can be implemented to read the settings using whatever format you choose. Of course, this has the disadvantage that you have to modify the class to add any other settings.

A: To answer your question, you could use boost::any or boost::variant to achieve what you would like.  I think variant is better to start with.
boost::variant<
    std::string,
    int,
    bool
  > SettingVariant;

std::map<std::string, SettingVariant> settings;

To not answer your question, using typeless containers isn't what I would recommend.  Strong typing gives you a way to structure code in a way that the compiler gives you errors when you do something subtly wrong.
struct ResolutionSettings {
  bool full_screen;
  size_t width;
  size_t height;
  std::string title;
};

Then just a simple free function to get the default settings.
ResolutionSettings GetDefaultResolutionSettings() {
  ResolutionSettings settings;
  settings.full_screen = true;
  settings.width = 800;
  settings.height = 600;
  settings.title = "My Application';
  return settings;
}

If you're reading settings off disk, then that is a little different problem.  I would still write strongly typed settings structs, and have your weakly typed file reader use boost::lexical cast to validate that the string conversion worked.
ResolutionSettings settings;
std::string str = "800";
size_t settings.width = boost::lexical_cast<size_t>(str);

You can wrap all the disk reading logic in another function that isn't coupled with any of the other functionality.
ResolutionSettings GetResolutionSettingsFromDisk();

I think this is the most direct and easiest to maintain (especially if you're not super comfortable in C++).


Q: How to loop in reactJS in table cell How should I loop roles for each project in a row?
I want to set roles in each cell for each project. I currently have a problem with syntax as this is my first time developing in reactJS.
render() {
            ...

            <Table
                resourceName="projects"
                columns={[
                    {
                        Header: 'Name',
                        accessor: 'name',
                    },
                    {
                        Header: 'Client',
                        accessor: 'client.name',
                    },
                    {
                        Header: 'Type',
                        accessor: 'type',
                    },
                    {
                        id: 'roles',
                        Header: 'Roles',
                        accessor: 'roles',
                        Cell: (props: { value: Array<{name: string}> }) => {
                            console.log(args);
                            return ',';
                        },
                    },
                ]}
            />
        </Box>
    );
}

A: You should do it in accessor, not in Cell.
accessor: d => d.roles.map(role => role.name).join(', ')


Q: Total number of Subsets I am getting curious about this question..
How many ways can you choose a subset from the set P = {1, 2, 3, .. n}? The subset S should meet the following condition:
When you choose x (x ∈ P, x is an element of the set P) to create S, you cannot choose a * x and b * x for S.
Constraints :
1 <= n <= 1000
2 <= a < b <= n
b % a != 0 ( b is not divisible by a)

Example :
n = 3 , a = 2, b = 3
so total subsets are 5 ,i.e, {}, {1}, {2}, {3}, {2, 3}
as if in a particular subset there is 1 so 1*2 = 2 and 1*3 cant be there.
so {1,2}, {1,3} and {1,2,3} can't be there

A: Updated
This is related to sequence A051026 : Number of primitive subsequences of {1, 2, ..., n} in OEIS, the Online Encyclopedia of Integer Sequences.
I don't think there is any easy way to calculate the terms. Even the recursive computations are not trivial, except when n is prime where:
a(n) = 2 * a(n-1) - 1

Both the problem here and "A051026" can be thought of subproblems of a generalization of the above sequence. "A051026" is the instance with (a,b,..) = (2,3,4,5...), e.g. "all the integers >= 2".

A: I believe it will be easier to calculate the complimentary- that is the number of subsets of S that are not allowed. This is the number of subsets of S for each there is at least one pair (a,b) such that a divides b. After you calculate that number M' simply subtract it from the total number of subsets of S that is 2n.
Now to calculate the number of subsets of S that are not allowed you will have to apply the inclusion-exclusion principle. The solution is not very easy to implement but I don't think there is an alternative approach.


Q: How Do I Get the Instantiated DataTemplate object for an item displayed in a ContentControl? I have a ContentControl whose content is being set in a ViewModel through binding.  I have a couple things that I would like to programatically set on the view/template that is being applied to the data object.  If I understand it right, the "Template" property is for the ContentControl, not the actual Content of the ContentControl.  How would I access the actual view obejct when WPF creates it and applies it?  For the example below, I want to make an adjustment to the vw:InfoType1View or vw:InfoType2View object when it gets instantiated.
        <ContentControl Name="mainContentArea" Content="{Binding CurrentInfo}">
            <ContentControl.Resources>
                <ResourceDictionary>
                    <DataTemplate DataType="{x:Type vm:InfoType1}">
                        <vw:InfoType1View />
                    </DataTemplate>
                </ResourceDictionary>
                <ResourceDictionary>
                    <DataTemplate DataType="{x:Type vm:InfoType2}">
                        <vw:InfoType2View />
                    </DataTemplate>
                </ResourceDictionary>
            </ContentControl.Resources>
        </ContentControl>

A: I am assuming you are using the MVVM pattern? In this case, you really shouldn't be programmatically making changes to your view!
Anyhow, you could handle the Loaded event, or the LayoutUpdated event (hard to determine which you need without more code). You can then navigate the visual tree, using my Linq-to-VisualTree for example, to navigate the elements in the view that was constructed - and make your changes.


Q: Memory Leak VBA - Arrays with Dictionaries of Dictionaries I'm running out of memory (I have 16GB) in a script I am running. Here is a little background:
I am generating an array that is ~150k rows by 8 column as the basis for my calculations.
Then, for each "row" of values (nothing is ever written to the worksheet), I am making a LOT of calculations, which I am storing in various data structures (I have 3 main structures at this point). One of these structures is composed of the following:
A Variant Array with 150k Dictionaries. Each Dictionary has ~4 Key-Item pairs. Each item in each dictionary is another dictionary, containing exactly 9 key-item pairs. All keys are Strings and all items are Doubles.
Essentially, this is the same thing as:
Dim Array(1 to 150000, 1 to 4, 1 to 9) as Double

Except I want to be able to reference the values with text strings -- hence the dictionaries.
An example would be
Value = Array(2401)("Key1")("Key2")

I wouldn't think this would be too much for VBA to handle -- we're talking 150,000 * 4 * 9 individual doubles = 5.4M doubles for each of the 3 main data structures. I don't have that much experience with programming and memory management, but sure that wouldn't consume 16GB of memory!
As such, I'm thinking there's a problem in how I'm generating these data structures that is causing a memory leak somewhere.
Essentially the loop looks like this
Dim TempDict1 as Dictionary
Dim TempDict2 as Dictionary
Dim FinalArray() as Variant
ReDim FinalArray(1 to 150000) as Variant
Dim Calculations as Double

For i = 1 to 150000
    Set TempDict = NewDictionary
    for j = 1 to 5
        Set TempDict2 = NewDictionary
        for k = 1 to 9
            Calculations = 2*2
            TempDict2.Add Key:= KeyK, Item:= Calculations
        Next k
        TempDict.Add Key:= KeyJ, Item:= TempDict2
        ' TempDict2.RemoveAll (This causes an error)
    next j
    Set FinalArray(i) = TempDict
    ' TempDict.RemoveAll (This causes an error)
Next i

What am I doing wrong here? I've tried destroying the temporary dictionaries after adding them to the parent item, but that actually gives me a type error.
UPDATE: I've tried setting the temporary dictionaries to nothing instead of removing all. This doesn't cause any errors, but it still consumes a lot of memory. With 37k iterations, it consumes 8.4GB of memory.

A: I'm not sure if this is some sort of bug or memory leak, but the fact is that this is an extremely memory-inefficient way to store data.
As such, I've edited the code to use 3 dimensional arrays with separate dictionaries to associate the indices of arrays with text strings, which is working great.
I was able to store 8 different 3D arrays (150k by 8 by 13) and 7 different 2D arrays (150k 13), both of doubles. Overhead doesn't seem to be too high. Given a size of 8 bytes per double, theoretical memory usage is 1.11GB, which isn't too bad.


Q: SwiftUI List based on @FetchedRequest and filtering computed properties crashes I have such code that has @FetchRequest loading Contacts then I have computed properties doing filter based on @State variable
 @FetchRequest var fetchRequest: FetchedResults<Contact>

    private var contacts : Array<Contact> {

        Array(fetchRequest).filter { contact in
            if self.sectionSelection == 1 {
                return contact.type == "person"
            } else if self.sectionSelection == 2 {
                return contact.type == "company"
            } else {
                 return true
            }
        }
    }

@State private var sectionSelection : Int = 0

But the List crashes with index out of range error!
 List {

            ForEach(0..<contacts.count) { i in

                ZStack {

                    NavigationLink(destination: ContactDetails(contact: contacts[i])) {