text:
Q: Get the latest file from SFTP server using Node.js I need help with finding a working solution for how to download the latest (added most recently) file from a remote SFTP server (which can be running on both UNIX and Windows machines), using a Node.js script.
Solutions I have already attempted:

*

*Using the standard list method (provided in any sftp library in Node.js), retrieve a list of all files on the server, sort them by timestamp, find the latest file's name, and then use the get SFTP method.
Problem with this solution is that the server has up to 20k files, and retrieving all their names through the standard list method is extremely slow, I need a faster solution.

*Through SSH2 library, connect to the remote server, execute a sample command (I used echo "$PATH" — response from a Windows machine would be "$PATH", while UNIX machines return their $PATH variable) and determine the server's OS. After determining the OS, I would execute another command, through SSH again, to sort through the files in particular path/location and return the name of the most recent one (e.g. for UNIX, the command would be ls -t | awk \'{printf("%s",$0);exit}\'). Having gotten the file name, I would just use the get SFTP method to download the file with name found.
Problem: this solution is  extremely error-prone, and testing it on 100s of servers is one hell of a job.

I need recommendations for any other solution, library, anything.


text:
Q: How to combine array in php to dynamically? I have code like this
$a =[
      [1,2],
      [4,6],
      [10,24]
    ];

i want a output like this
    Array
    (
      [0] => 1
      [1] => 2
      [2] => 4
      [3] => 6
      [4] => 10
      [5] => 24
    )

and i use code like this
print_r(array_merge($a[0],$a[1],$a[2]));

if a have code like this and have more data
    Array
   (
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )
    [1] => Array
        (
            [0] => 4
            [1] => 6
        )
    [2] => Array
        (
            [0] => 10
            [1] => 24
        )
       .
       .
       .
     [60] => Array
            [0] => 67
            [1] => 8
     )

writing like this is not good
print_r(array_merge($a[0],$a[1],$a[2],...,...,...,$a[58]));

how to use array_merge in dinamic in there?

A: Try:
function my_array_merge($array1, $array2) {
    foreach ($array2 as $key => $val) {
        if (is_array($val)) {
            $array1[$key] = my_array_merge($array1[$key], $array2[$key]);
        } else {
            if (is_numeric($key)) {
                $array1[] = $array2[$key];
            } else {
                $array1[$key] = $array2[$key];
            }
        }
    }
    return $array1;
}

As far as I know, the above exactly works like array_merge(), but merges  arrays inside it:
$arr1 = array(array("a"));
$arr2 = array(array("b"));

will become:
Array (
        [0] => Array (
                [0] => a
                [1] => b
        )
)

A: u can use this:
$a =[
      7,
      [1,2],
      [4,6],
      [10,24],
      [[30,40],[2,9]]
    ];

function mrg($array){
    $out = [];
    foreach($array as $b){
        if(is_array($b))
            $out = array_merge($out, mrg($b));
        else
            $out[] = $b;
    }
    return $out;
}

print_r(mrg($a));

A: $result = array_reduce($a, fn($carry, $item) => array_merge($carry, $item), []);

A: You can use the following function.
function func($array) {
    $result = array();
    foreach ($array as $key => $value) {
      if (is_array($value)) {
        $result = array_merge($result, func($value));
      }
      else {
        $result[$key] = $value;
      }
    }
    return $result;
  }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I make a directory in Java? I am trying to create a new file directory, but the function mkdir() doesn't work, neither mkdirs().
Here's my code:
...
  while (leitor.hasNext()){
      String [] plv = LerPalavras(tamMem, leitor);
      Arrays.sort(plv);
      String nomeTemp = "/temp/temp" + contador + ".txt"; // I need to create this directory
      try{
        escritor = new FileWriter(nomeTemp);
        for (int i = 0; i < tamMem; i++) {
          escritor.write(plv[i] + " ");
        }
        escritor.close();
      } catch (IOException e){
        System.out.println(e.getMessage());
      }
      contador++;
    }
...

Edit: I made the edits and now it's working!
File pastaTemp = new File("/temp/temp");
    pastaTemp.mkdirs();

    while (leitor.hasNext()){
      String [] plv = LerPalavras(tamMem, leitor);
      Arrays.sort(plv);
      File arqTemp = new File (pastaTemp, contador + ".txt");
      try{
        escritor = new FileWriter(arqTemp);
        for (int i = 0; i < tamMem; i++) {
          escritor.write(plv[i] + " ");
        }
        escritor.close();
      } catch (IOException e){
        System.out.println(e.getMessage());
      }
      contador++;
    }

A: Try doing this in two steps.  First, call File.mkdirs() to create the entire directory structure, if necessary, then create the file you pass to the FileWriter:
try {
    File folder = new File("/temp/temp");
    folder.mkdirs();
    // then create a file object at this location
    File file = new File(folder, contador + ".txt");

    escritor = new FileWriter(file);
    // the rest of your code
}
catch (Exception e) {
}


text: Q: Screen shot using C++ and MFC I have a MFC Application and a I need to build a function that captures a screen shot, but only the open dialog box, not the whole window. I'm new VS and C++ and I'm using VS 2013 in my project. Any Ideas?


text:
Q: How to fetch the last n months record(consider only the last entry per month) in MongoDB I am new to MongoDb. I need help to fetch the last n month record, there might be multiple entry per month but the query needs to return only the last entry per month.
For e.g lets say if n is 3 and userId is userId1 (that means return last 3 month record for userId1).
Sample inputs in the collection:
[
 {
   "_id": objectId("aaaaaa"),
   "userId": "userId1",
   "processedAt": "2021-06-01T12:16:49.349Z"
 },
 {
   "_id": objectId("bbbbb"),
   "userId": "userId1",
   "processedAt": "2021-10-11T12:16:49.349Z"
 },
 {
   "_id": objectId("ccccc"),
   "userId": "userId1",
   "processedAt": "2021-10-25T12:16:49.349Z"
 },
 {
   "_id": objectId("eeeee"),
   "userId": "userId1",
   "processedAt": "2021-09-12T12:16:49.349Z"
 },
 {
   "_id": objectId("fffff"),
   "userId": "userId1",
   "processedAt": "2021-09-28T12:16:49.349Z"
 },
 {
   "_id": objectId("ggggg"),
   "userId": "userId1",
   "processedAt": "2021-09-23T12:16:49.349Z"
 },
 {
   "_id": objectId("hhhhh"),
   "userId": "userId1",
   "processedAt": "2021-07-23T12:16:49.349Z"
 },
 {
   "_id": objectId("iiiii"),
   "userId": "userId2",
   "processedAt": "2021-09-29T12:16:49.349Z"
 },
 {
   "_id": objectId("jjjjj"),
   "userId": "userId1",
   "processedAt": "2022-01-29T12:16:49.349Z"
 },
 {
   "_id": objectId("kkkkk"),
   "userId": "userId1",
   "processedAt": "2022-02-29T12:16:49.349Z"
 },
]

Expected Result: Should return by userId, limit n months(fetch only the last saved entry of the month) and the ascending order of the month of processedAt:
[{
    "_id": objectId("ccccc"),
    "userId": "userId1",
    "processedAt": "2021-10-25T12:16:49.349Z"
},
{
    "_id": objectId("jjjjj"),
    "userId": "userId1",
    "processedAt": "2022-01-29T12:16:49.349Z"
  },
  {
    "_id": objectId("kkkkk"),
    "userId": "userId1",
    "processedAt": "2022-02-29T12:16:49.349Z"
  }
]

I have tried below query however which is returning all the records. I want query needs to consider only the last entry per month. I have been using mongojs driver v4.1.2
db.collection(collection_name)
                .find({ userId: userId }, { projection: { _id: 0 } })
                .sort({ processedAt: -1 })
                .limit(n)
                .toArray()

A: Starting from MongoDB 5.0,
You can use $setWindowFields to aggregate a "rank" for the "partition" / "group" (i.e. the month in your example) and only choose the document with top rank.
The ranking can be defined as processedAt: -1 as you want to keep only the latest record in the month with highest rank.
{
    "$setWindowFields": {
      "partitionBy": {
        "$dateToString": {
          "date": "$processedAt",
          "format": "%Y-%m"
        }
      },
      "sortBy": {
        "processedAt": -1
      },
      "output": {
        "rank": {
          $rank: {}
        }
      }
    }
  }

Here is the Mongo playground for your reference.
For MongoDB 3.6+,
As the sample dataset is using ISODate format, it is possible to sort and group the field by leftmost 7 characters (i.e. yyyy-MM). Keeping only the first document inside the month group should do the tricks.
{
    $sort: {
      processedAt: -1
    }
  },
  {
    "$addFields": {
      "month": {
        "$substrCP": [
          "$processedAt",
          0,
          7
        ]
      }
    }
  },
  {
    $group: {
      _id: "$month",
      last: {
        $first: "$$ROOT"
      }
    }
  }

Here is the Mongo playground.


text:
Q: Converting a MySQL database row time timezone So I have made something ridiculously complicated by accident because I don't think you can have individual timezones per database in MySQL if they're on the same account?
Basically most of my databases are for American users and use one of the American timezones, I then also run an English blog.
My issue is that the English blog has the correct BST (GMT+1) value inserted into the datetime row but it's in the database that uses the MDT timezone.
I then need to get that time for an rss feed using:
$date = date('r', $data['date']); //MDT system but $data['date'] is GMT+1

but this gives me a time in the future at the time of the blog post due to incorrect timezone.
Is there a way I can convert BST to MDT?
but it gets even more complex because some months of the year in England we use GMT (GMT+0) instead of BST (GMT+1) ... is there anyway to work out which timezone is being used in England at the time of year and do a conversion or am I just way overcomplicating this whole matter?

A: The following solution works perfectly:
$oldDate = date('l F j Y H:i:s', $link['date']);
$date = new DateTime($oldDate, new DateTimeZone('Europe/London'));
$date->setTimezone(new DateTimeZone('UTC'));
echo $date->format('r');


text:
Q: Make an email be interpreted as an event by mail clients I'm trying to send an email that will be interpreted as an event by mail clients. This is related to another question of mine.
This code pulls an event from a google calendar, and then builds a VEVENT  out of it, converts that to a .ics blob and attatches it to an email.
However when this is received by the mail client it treats it as an email with an attachment, but what I really want is for it to be treated as an event update.

When I dissect an event email it contains two .ics files (identical contents, different file names) and a .html file that contains the same as the DESCRIPTION: in the .ics.
What I'd like to know is what I need to do to tell the mail client that this is an event, and if that relates to the duplicate ics files and the html file.
function fixInvitations(){
  //get the callendar named "Appraisals"
  var cApp = CalendarApp.getCalendarsByName("Bris Appraisals")[0];
  var events = cApp.getEvents(new Date(), new Date("Dec 30 2014"));

  var e = events[5];
  var icsFile = makeICS(e);
  var mail_options={
                      body:     "Your updated appraisal etc. etc.",
                      htmlBody: "
Your updated appraisal etc. etc.
",
                      name: "Appraisals Scheduling Robot",
                      noReply: true,
                      /*replyTo: ,*/
                      subject: "Your updated appraisal",
                      to: "myworkEmail@bvn.com.au, mygoogleEmail@notionparallax.co.uk",
                      attachments:[icsFile]
                    };
  Logger.log(mail_options);
  MailApp.sendEmail(mail_options);
}

function ldapDate(d){
  //TODO: make this take Bris or syd to decide on a timezone
  var formattedDate = Utilities.formatDate(d, "GMT+11:00", "yyyyMMddHHmmss");
  Logger.log([d, formattedDate])
  return formattedDate+"Z";
}

function makeICS(event){
  var e = event;
  var attendees = [];
  var guests = e.getGuestList();

  for(g in guests){
    var guest = guests[g];
    var atendee =[
    "ATTENDEE;",  "CUTYPE=INDIVIDUAL;",  "ROLE=REQ-PARTICIPANT;",
    "PARTSTAT=NEEDS-ACTION;",  "RSVP=TRUE;",  "CN="+guest.getName()+";",
    "X-NUM-GUESTS=0:mailto:"+guest.getEmail()
      ].join("");
    attendees.push(atendee);
  }

  var vcal = ["BEGIN:VCALENDAR",
              "PRODID:-//Google Inc//Google Calendar 70.9054//EN",
              "VERSION:2.0",
              "CALSCALE:GREGORIAN",
              "METHOD:REQUEST",
              "BEGIN:VEVENT",
              "DTSTART:" + ldapDate(e.getStartTime()),
              "DTEND:"+ ldapDate(e.getEndTime()),
              "DTSTAMP:" + ldapDate(new Date(Date.now())),
              "ORGANIZER;CN=" + CalendarApp.getCalendarById(e.getOriginalCalendarId()).getName() + ":mailto:" + e.getOriginalCalendarId(),
              "UID:" + e.getId(),
              attendees.join("\n"),
              "CREATED:" + ldapDate(e.getDateCreated()),
              "DESCRIPTION:" + e.getDescription(),
              "LAST-MODIFIED:" + ldapDate(new Date(Date.now())), // although if I wasn't changing things as I issue this it'd be e.getLastUpdated()
              "LOCATION:" + e.getLocation(),
              "SEQUENCE:"+Date.now(),//this is a horrible hack, but it ensures that this change will overrule all other changes.
              "STATUS:CONFIRMED",
              "SUMMARY:" + e.getTitle(),
              "TRANSP:OPAQUE",
              "END:VEVENT",
              "END:VCALENDAR"
  ].join("\n");

  var icsFile = Utilities.newBlob(vcal, 'text/calendar', 'invite.ics');
  Logger.log(vcal);
  Logger.log(icsFile);
  return icsFile;
}

A: Try sending a meeting request to a user in notes from another notes client and checking out the fields created. This is how I did this in the past.
I have some code that will create a .ics feed so the user can add them into their Notes calendar using the "add a calendar" feature if you need it.
eg: http://camberleycricket.com/cc.nsf/calendar.ics
Neatest way as then other calendar systems can use the feed.


text:
Q: Python Grahics from Linux CLI I am anticipating the answer to be no, but I wanted to verify. If I write a Python program that was a GUI, can I launch that from a Linux CLI and still get the GUI? I am trying to build an embedded Linux system and I want to exclude everything that isn't necessary. This is a kiosk-like device, so all I need is my Python GUI.

A: Various widget toolkits (GTK+, Qt, etc.) can run on DirectFB instead of X11, which will allow you to have a GUI running on the Linux framebuffer device instead of requiring a full X server.

A: To run GUI anything on Linux you'll need an X server at a minimum.
There are curses based sorta-GUI libraries that assume an 80x24 character terminal emulator if you want to go that route, but you'll still need some kind of display.


text:
Q: Which code can assign a new value to a variable when R is running? (like input() in VBA) I am creating a function where some coefficients should be defined by users to improve the model.
I tried scan() , readline(), and others to input the value. But all of them will read the next line of my code instead of be paused and let the user input something in R Console.
Is there any code can achieve similar function like input() in VBA.
Thank you very much!


text:
Q: mpl_connect key_press_event event does not fire in Scrollable Window on Python Matplotlib I have multiple plot inside scrollable window QT5 widget as below.
class ScrollableWindow(QtWidgets.QMainWindow):
    def __init__(self, fig):
        self.qapp = QtWidgets.QApplication([])

        QtWidgets.QMainWindow.__init__(self)
        self.widget = QtWidgets.QWidget()
        self.setCentralWidget(self.widget)
        self.widget.setLayout(QtWidgets.QVBoxLayout())
        self.widget.layout().setContentsMargins(0,0,0,0)
        self.widget.layout().setSpacing(0)

        self.fig = fig
        self.canvas = FigureCanvas(self.fig)
        self.canvas.draw()
        self.scroll = QtWidgets.QScrollArea(self.widget)
        self.scroll.setWidget(self.canvas)

        self.nav = NavigationToolbar(self.canvas, self.widget)
        self.widget.layout().addWidget(self.nav)
        self.widget.layout().addWidget(self.scroll)

        self.show()
        exit(self.qapp.exec_())

I try to capture key press event with mpl_connect.
def key_selector(event):
    print('Key pressed.')

fig, axes = plt.subplots(ncols=4, nrows=5, figsize=(16,16))
for ax in axes.flatten():
    ax.plot([2,3,5,1])

fig.canvas.mpl_connect('key_press_event', key_selector)
a = ScrollableWindow(fig)

But mpl_connect 'key_press_event' does not fire. I try another e.g. 'button_press_event' and work as usual. Any advice or guidance on this would be greatly appreciated, Thanks.

A: Have a look at this matplotlib issue. Basically, you need to activate the focus of Qt onto your matplotlib canvas.
    self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
    self.canvas.setFocus()


text:
Q: How to flip a Char array with pointers in C++ the function of my program is to simply have a char array with a first and last name, and switch it so it is last name first name.
(Tom,Cruise --> Cruise,Tom). I have just started using pointers and cannot find a way to rearrange the Char array. I have tried for-loops and while loops but I don't really know how to tackle this problem. I don't necessarily need hard code. Even a suggestion would help get me moving in the right direction. I am not getting any errors. Due to requirements I am unable to modify the main function whatsoever and the function header has to be
char *LastFirstName(char *ptr).

Thanks
#include <iostream>
using namespace std;

char *LastFirstName(char *name);

int main()
{
  char name[41];
  char *ptr;
  // Force user to enter full name, if not entered, ask again
  while (true)
  {
    name[0] = '\0';
    cout << "Enter your full name: ";
    cin.getline(name, 40);
    if (name[0] == '\0')
        cout << "Name not entered. Re-enter full name.\n";
    else
        break;
  }
  cout << "Before calling function LastFirstName(), name is " << name
  <<endl;

  ptr = LastFirstName(name);
  cout << "After calling function LastFirstName(), name is " << ptr << endl;

  system("pause");
  return 0;
}

// This is where I am havinbg trouble
char *LastFirstName(char *ptr) {
  char *p;
  p = ptr;
  int len = strlen(ptr);

  return ptr;
}

A: You can use this function:
void LastFirstName(char* first_last_name)
{
    char first_name[41] = {0};
    char last_name[41]  = {0};

    // Dunno what is your separator ' ' or ','...
    char* sep_index = strchr(first_last_name, ','); // This return the first index of ','.
    *sep_index = '\0';

    strcpy(first_name, first_last_name); // Lets copy first name.
    strcpy(last_name,  first_last_name + strlen(first_last_name) + 1); // Lets copy last name.

    // Lets copy it in reverse order.
    strcpy(first_last_name, last_name);
    strcpy(first_last_name + strlen(last_name) + 1, first_name);
    first_last_name[strlen(last_name)] = ',';
}

Notice that we don't need to return char* because the function is modifying the array it received as argument, so actually name array is now reversed as requested.

A: *

*ptr = LastFirstName(name); this doesn't really do anything. I mean, after that both ptr and name point to the same area in the memory... so it's pretty pointless (got it? 'pointless'... k, won't do that again.) to do that (the LastFirstName works on the memory pointed by name, which means that after the function ends name will hold the results.

*It would be easier to ask for the name, and then last name, then just swap the addresses that the pointers are pointing to... but that would be no-fun and we wouldn't learn anything from that, would we? (I'm just saying that there's another option. Don't get me wrong)
Now let's get to the coding. Since returning pointer in this case doesn't make sense (unless you want to have 2 arrays, each with different order), so let's change the function's declaration into void LastFirstName(char *ptr).
Now we need to know where the name ends. We have to find the first occurence of a space (or any other character you want the two to be separated with), which is easily done with strchr(char*, int) function.
After that, since the name and last name doesn't need to be the same length we can't just swap their letters, it would be handy to just copy the name somewhere (another array), then override the name with the last name, copy the name right after that, and terminate with '\0'.
The code would look something like that (not tested, use with care):
void LastFirstName(char *ptr)
{
   char name[41], ptr2(ptr);
   const size_t nameLen(strchr(ptr, ' ')); // Change the space for whatever you want. btw, I used constructor here.
   strncpy(name, ptr, nameLen); // Copy the name from "ptr" to "name"
   ptr += nameLen+1; // Move pointer to the first character of the last name

   /* We could use some pre-made functions to avoid doing the for loop below
      but that's not the point in learning, is it? */
   for(size_t i(strlen(ptr) - nameLen - 1); i>0; --i) // I also used constructor here
   {
      *ptr2 = *ptr;
      ++ptr2;
      ++ptr;
   }

   *ptr2 = ' ' // Again, you can change it to whatever you want
   ++ptr2; // it's better to do it that way - compiles into faster code

   strncpy(ptr2, name, nameLen); // let's copy the name back into our array
   ptr2 += nameLen; // Move the pointer to the end and append '\0'
   *ptr2 = '\0'; /* We would have passed nameLen+1 previously (and now)
   to get the null terminator copied within the strncpy, but it's better
   that way - it helps you to understand what happens behind the
   courtain. */

   return; // unnecessary, but it's a good habit imho
}
   /**
      Since you pass a copy of pointer, and not a pointer itself, to a function,
      you don't have to worry about getting it back to the position it was before.
   */

As you can see, I also made use of the strncpy(char*, char*, size_t) function.
Oh, and size_t is just a unsigned integer, used to express size in memory. It doesn't really differ from any other unsigned integer. It's just an alias.
And a little tip at the end: use C-style arrays (char array[]), wherever you can. Since their size is known at compile time the compiler can optimise it better. Not to mention that dynamic allocation (which I believe you will learn about next, that's what we use pointers for, mostly... left? I mean, right?) is just slower.
Hope I helped.


text:
Q: Precision - Recall: Graphical Representation I'm a little bit confused with precision recall. I read some papers about recommender systems, where in one paper they have a graphical representation and in other papers they don't (they just have the values for precision/recall). What is the advantage of a graphical representation?
Am I right, that for a graph you have to do something like a step function? e.g. you have a list of values true,true,false,true,false and you begin with the first one, calculate precision recall and then draw that point into the graph. For the next point, you take the first and the second value true,true into account, calculate precision recall, draw the point... and so on. Am I right that this is similar to drawing a ROC curve?

A: The process of creating a precision-recall curve is very similar to creating a ROC curve, i.e. in both cases your predictions have to be associated with some kind of score such as a probability for each class. As for ROC curves you gradually increase the threshold on your score and each time calculate two performance measures based on the resulting confusion matrix when applying the current threshold on the score.
For ROC curves you calculate sensitivity (y-axis) and 1 - specificity (x-axis), whereas for precision-recall curve you calculate precision/sensitivity (x-axis) and recall (y-axis). As you can see both ROC curves and precision-recall curves use the sensitivity, but compare it with different value.
If the paper you were talking about only mentions a single value for precision and recall it might be that their classifier does not return continuous scores, but only the predicted class, hence you cannot construct a precision-recall curve.


text:
Q: Why is PHP saying 6469 > 1,000,000? Here's my PHP:
<?php

$a = $_FILES['profilepic']['size'];
if ($a>1000000){
    echo json_encode("larger than 1MB");
}
?>

All it's doing is grabbing the filesize of an upload and comparing it to 1,000,000. I am assuming 1,000,000 is also in bytes, hence it equals 1MB.
My issue is that a very small file, 6469 bytes, triggers the echo, meaning PHP sees 6469 > 1,000,000.
I have echoed $a directly and it returns 6469, I assume it is bytes because Windows says the file is also 6469 bytes.
What's going on? Here's the file: https://easyupload.io/9spcmh

A: Here is the problem is it actually compare
6469 > 1 // that is true in (6469 > 1,000,000?)

If you actually compare look like below not comma separator
6469 > 1000000

A: If you use gettype($a), turns out for some weird reason, $a returns an array, where the actual number 6469 is in the 0th index of the array. $a[0] >1000000 now resolves correctly, thanks all!


text:
Q: Cordova plugin PictureInPicture for ios I am finding any cordova plugin to PictureInPicture for IOS. There is one plugin only for PictureInPicture which is only developed for android and working fine but I need one for ios as well.
For android I have used the plugin https://www.npmjs.com/package/cordova-plugin-pip.
Please let me know if there is any plugin available or how I can achieve this.


text:
Q: Can a general verb 'have' be in front of a question? In the following sentence, isn't the verb 'have' a general verb? Isn't it correct to change like "Do you have any commissions for Egypt?"

"Have
  you any commissions for Egypt?"

A:
[1] Do you have any commissions for Egypt?
[2] Have you any commissions for Egypt?

No: when "have" expresses such meanings as possession or obligation it can be either a lexical verb (your 'general' verb) or an auxiliary verb.
Grammatically, in closed questions like these, lexical "have" requires the addition of the dummy auxiliary verb "do" as in [1], while auxiliary "have" in [2] does not.
Most speakers treat "have" as a lexical verb, or use the informal idiom "have got" as in "Have you got any ...", where the "have" component is an auxiliary verb.


text:
Q: how to load json from url on input field? This tutorial page loads json from a hard-coded URL on page load: https://github.com/mdn/learning-area/blob/master/javascript/oojs/json/heroes-finished.html
How can I achieve the same but dynamically by adding an input field in the page and pasting the same url into that field and have that information be loaded onto the page on leaving focus of the input field (or clicking a button?)

A: html:

    <input onblur="loadJson(event.target.value,'output')"/>

javascript:
const loadJson = (url,nodeId) =>{
  fetch (url)
  .then(result => result.json())
  .then(data => document.getElementById(nodeId).innerHTML = JSON.stringify(data))
}

try out this repl.it: https://repl.it/join/qeijjvpt-kouroshg
Hope it helps

A: The easiest way to do this is to use try...catch, otherwise your code will cause a syntax error:

//<![CDATA[
/* js/external.js */
let getRaw, doc, html, bod, nav, M, I, mobile, S, Q; // for use on other loads
addEventListener('load', ()=>{
getRaw = (url, success, fail)=>{
  const x = new XMLHttpRequest;
  x.open('GET', url);
  x.onload = ()=>{
    if(success)success(x.responseText);
  }
  x.onerror = ()=>{
    if(fail)fail('xhr failure');
  }
  x.send();
}
doc = document; html = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
  var w = within || doc;
  return w.querySelector(selector);
}
Q = (selector, within)=>{
  var w = within || doc;
  return w.querySelectorAll(selector);
}
// here's where the magic happens
const test = I('test'), butt = I('butt');
butt.onclick = ()=>{
  console.clear();
  getRaw(test.value, res=>{
    try{
      const obj = JSON.parse(res);
      console.log(obj);
    }
    catch(e){
      console.log(e.message);
    }
  }, err=>{
      console.log(err);
  });
}
}); // end load
//]]>
/* css/external.css */
*{
  box-sizing:border-box; padding:0; margin:0; font-size:0; overflow:hidden;
}
html,body,.main{
  width:100%; height:100%; background:#ccc;
}
.main{
  padding:10px; font-size:18px;
}
input{
  width:100%; height:38px; background:#fff; color:#000; font:bold 22px Tahoma, Geneva, sans-serif;  padding:5px; border:1px solid #147; border-radius:3px;
}
#butt{
  background:linear-gradient(#1b7bbb,#147); color:#fff; border:0; margin-top:7px; border-radius:5px;
}
<!DOCTYPE html>

    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
    <title>Title Here</title>
    <link type='text/css' rel='stylesheet' href='css/external.css' />

<input id='test' type='text' value='https://api.weather.gov/points/47.6062,-122.3321' /><input id='butt' type='button' value='test' />


text:
Q: Is the fastest open determined by preceeding key slots? After installing LUKS (v1) devices with openSUSE LEap 15.2, it turned out that the iteration count was set so high that it takes more than 10 seconds for a successful decryption of the master key (bug reports exist on that).
So I added a second key slot using a much smaller iteration count.
However I wonder:
AFAIK after entering a pass phrase, luksOpen will try to decrypt the key slots in sequence, not in parallel, meaning that the first key slot determines the minimum waiting time until decryption succeeds.
Is that correct?
Note: When booting, I cannot specify parameters to select a specific key slot.
So the most likely solution would be swapping key slots, right?

A: Test setup

*

*Create a file in ramdisk to hold the LUKS container:
$ cd /dev/shm
$ truncate -s 1G luksfile

*Prepare identical size keyfiles for testing:
$ dd if=/dev/urandom of=key1 bs=1M count=1
1+0 records in
1+0 records out
1048576 bytes (1,0 MB, 1,0 MiB) copied, 0,00897814 s, 117 MB/s
$ dd if=/dev/urandom of=key2 bs=1M count=1
1+0 records in
1+0 records out
1048576 bytes (1,0 MB, 1,0 MiB) copied, 0,00792946 s, 132 MB/s

*Format the file:
$ cryptsetup luksFormat --key-file key1 luksfile

WARNING!
========
This will overwrite data on luksfile irrevocably.

Are you sure? (Type uppercase yes): YES

*Add the 2nd key:
$ cryptsetup luksAddKey --key-file key1 luksfile key2

The test
for x in 1 2 3 4 5; do
time sudo cryptsetup open --key-file key1 luksfile test
sudo cryptsetup close test
done

I'm discarding results from the first 5 runs for each key to eliminate caching discrepancies.
Results for key1:
2,30s user 0,02s system 97% cpu 2,369 total
2,39s user 0,01s system 97% cpu 2,454 total
2,41s user 0,02s system 97% cpu 2,509 total
2,25s user 0,02s system 97% cpu 2,336 total
2,21s user 0,02s system 97% cpu 2,291 total

Results for key2:
4,08s user 0,02s system 98% cpu 4,146 total
4,20s user 0,02s system 98% cpu 4,267 total
4,19s user 0,01s system 98% cpu 4,255 total
4,15s user 0,01s system 98% cpu 4,209 total
4,43s user 0,02s system 98% cpu 4,520 total

Yes, keys are checked one by one. 2nd key will be affected by 1st key's slowness.
Solution

When booting, I cannot specify parameters to select a specific key slot.

Actually you can. Use the keyslot option in /etc/crypttab, 4th column. See man crypttab.


text:
Q: npm install and build of forked github repo I'm using a module for my angular app called angular-translate. However, I've had to make a few small modifications to the source code to get everything working the way I'd like, and now I want to persist those changes on npm install. A colleague suggested that I fork the repo of the source code and point to my forked repo as a dependency, which I've tried in these ways, e.g.
npm install https://github.com/myRepo/angular-translate
npm install https://github.com/myRepo/angular-translate/archive/master.tar.gz

The first gives me a directory like this with no build. Just a package.json, .npmignore, and some markdown files
-angular-translate
   .npmignore
   .nvmrc
    CHANGELOG.md
    package.json
    etc

The second npm install gives me the full repo, but again I don't get a build like when I use the command npm install angular-translate.  I've seen some dicussion of running the prepublish script, but I'm not sure how to do this when installing all the modules.  I've also tried publishing the fork as my own module to the npm registry, but again I get no build, and I'm not sure that's the right thing to do...
I apologise for my ignorance on the topic.  I don't have a huge amount of experience with npm. Would love to get some feedback on this issue.  It seems like it could be a  common enough issue when modifications need to be made to a package's source code? Maybe there's a better solution?

A: Just use the command npm install git+https://git@github.com/myRepo/angular-translate.git. Thanks.

A: TL;DR use a prepare script
and don't forget package.json#files or .npmignore
Code published to npmjs.com is often not what's in the repository for the package. It is common to "compile" JavaScript source files into versions meant for general consumption in libraries. That's what's usually published to npmjs.com.
It is so common that it's a feature of npm to automatically run a "build" step before publishing (npm publish). This was originally called prepublish. It seems that Npm thought it would be handy to also run the prepublish script on an npm install since that was the standard way to initialize a development environment.
This ended up leading to some major confusion in the community. There are very long issues on Github about this.
In the end, in an effort to not change old behavior, they decided to add two more automatic scripts: prepublishOnly and prepare.
prepublishOnly does what you expect. It does not run on npm install. Many package maintainers just blindly switched to this.
But there was also this problem that people wanted to not depend on npmjs.com to distribute versions of packages. Git repositories were the natural choice. However it's common practice to not commit "compiled" files to git. That's what prepare was added to handle...

prepare is the correct way
If you have a repository with source files but a "build" step is necessary to use it,
prepare does exactly what you want in all cases (as of npm 4).

prepare: Run both BEFORE the package is packed and published, on local npm install without any arguments, and when installing git dependencies.

You can even put your build dependencies into devDependencies and they will be installed before prepare is executed.
Here is an example of a package of mine that uses this method.

Problems with .gitignore
There is one issue with this option that gets many people.
When preparing a dependency, Npm and Yarn will keep only the files that are listed in the files section of package.json.
One might see that files defaults to all files being included and think they're done.
What is easily missed is that .npmignore mostly overrides the files directive and, if .npmignore does not exist, .gitignore is used instead.
So, if you have your built files listed in .gitignore, like a sane person, and don't do anything else, prepare will seem broken.
If you fix files to only include the built files or add an empty .npmignore, you're all set.
My recommendation
Set files (or, by  inversion, .npmignore) such that the only files actually published are those needed by users of the published package. Imho, there is no need to include uncompiled sources in published packages.

Original answer: https://stackoverflow.com/a/57503862/4612476

A: To piggyback off of @RyanZim's excellent answer, postinstall is definitely a valid option for this.
Either do one of the following:

*

*Update the package.json in your forked repo to add a postinstall element to scripts. In here, run whatever you need to get the compiled output (Preferred).

*Update your package.json, and add a postinstall that updates the necessary directory in node_modules.

If you've forked another persons repository, then it might be worth raising an issue to illustrate the issue that installing their package through GitHub does not work as it does not provide the necessary means to build the script. From there, they can either accept a PR to resolve this with a postinstall, or they can reject it and you can do #2.

A: Update for those using npm 5:

As of npm@5, prepublish scripts are deprecated.
Use prepare for build steps and prepublishOnly for upload-only.

I found adding a "prepare": "npm run build" to scripts fixed all my problems.

A: Try npm install <ghusername>/<repoName>, where <ghUsername> is your GitHub username (without the @) and <repoName> is the name of the repository. That should correctly install it. You will most likely want to use the --save or --save-dev flag with the install command to save dependency in your package.json.
If that isn't working correctly, check the contents of your .npmignore file.
Don't panic if the install command takes a long time; installing from a git repository is slower than installing from the npm registry.

Edit:
Your problem is that in your case, dist/ is not committed to the repo (since it is in the .gitignore). That is where the actual code lives. dist/ is built from the files in src/ before the package is published to the npm registry, but dist/ is never committed to the repo.
It's ugly, but in this case you will have to remove dist/ from the .gitignore and then run:
npm run build
git add .
git commit
git push

(Ensure that you have run npm install first)
You then should be able to install from github.
There might be another way to do this using a prepare script, but I'm not sure if that's possible; I've never tried it. Edit: Cameron Tacklind has written an excellent answer detailing how to do this: https://stackoverflow.com/a/57829251/7127751

A: If you are using yarn like me. Imagine that you want to use a package like this:
yarn add ghasemikasra39/gridfs-easy --save where the ghasemikasra39 is the username and gridfs-easy is the name of the repo


text:
Q: Standardized generalized hyperbolic distribution I am interested in the standardized version (mean zero, variance one) of the generalized hyperbolic and the hyperbolic distribution. I want to include this in my analysis and therefore I need the dervations and the implementations. In R, there is an implementation of the standardized generalized hyperbolic distribution.

*

*I need the used formula and how to derive it for this implementation, where can I get it?

*Where can I see, what the code is doing? So where can I get a 'look behind the scenes' to see what is implemented?

*I searched via google but I could not find any derviations of how to get a standardized version of the ghyp or hyp. Where can I find this?

*I could use the R command to also fit a standardized hyperbolic distribution if I do the following: Inser for lambda=1 (this gives hyperbolic) and then use the dsgh command along together with the optim command to get a good fit of the standardized hyperbolic distribution to my data, is this correct?
edit: OK, the answer to 2) is, that I just can load the package and enter the command without any specifications. I then get the code behind it.
edit: I also noticed the sghFIT command, where can I find the theory behind this? Because they have to use a standardized version, so they need the formula and the derivation, this is what I need.
edit: I just saw, that they also only use the dsgh command for fitting.
Ok, my last edit, all comes back to the implementation of the dsgh command, the code for this command is:
dsgh <-
function(x, zeta = 1, rho = 0, lambda = 1, log = FALSE)
{
    # A function implemented by Diethelm Wuertz

    # Description:
    #   Returns density of the sgh distribution

    # FUNCTION:

    # Parameters:
    if (length(zeta) == 3) {
       lambda = zeta[3]
       rho = zeta[2]
       zeta = zeta[1]
    }

    # Compute Density:
    param = .paramGH(zeta, rho, lambda)
    ans = dgh(x, param[1], param[2], param[3], param[4], lambda, log)

    # Return Value:
    ans
}

He computes the density with
# Compute Density:
        param = .paramGH(zeta, rho, lambda)
        ans = dgh(x, param[1], param[2], param[3], param[4], lambda, log)

but I am not getting the idea behind the code. dgh is just giving the moments of the generalized hyperbolic distribution, see here? So where is the density? How does he do the modification to get a standardized version? Where is the theory behind this? So there must be a puplished paper or so, where it is described how to get the standardized version? I cannot find this?

A: First of all, "Standardised" in the location-scale family also means: location $0$ and scale $1$, not always mean $0$ and variance $1$. They coincide in the Normal distribution, but not in general. This applies to several of your questions. So, be careful about this.

*

*dgh is just giving the moments of the generalized hyperbolic distribution, see here?

No, the standardised density is implemented in the command dgsh() as stated in your first link which is more reliable.

*

*So where is the density?

See the link in the last point. See also the manual of the fBasics package.

*

*How does he do the modification to get a standardized version? Where is the theory behind this?

See the link in the last point.

*

*So there must be a puplished paper or so, where it is described how to get the standardized version? I cannot find this?

Section 2.3.5 of the following manual
http://cran.r-project.org/web/packages/rugarch/vignettes/Introduction_to_the_rugarch_package.pdf
I found it by googling "standardized generalized hyperbolic distribution". Remember: google is your friend.


text:
Q: TypeError: expecting numeric data I am having trouble figuring out what this error means as there is not much help with this question online already.
Is it saying that my Oracle table needs to only receive numbers not letters? That can't be the case because I have my columns set to allow VarChar so that both numbers and letters will fit.
I had thought it was due to my DataFrame having NaNs in it, so I replaced all of them with 0's and I still receive this error.
Ultimately, I would like to export all this data, which I parsed from an Excel file, to my Oracle table.
Any help solving this would be appreciated.
My DataFrame:
S USTAINABLE H ARVEST S ECTOR| QUOTA LISTING JUN 11 2013 Unnamed: 1  \
0                                     AVAILABLE QUOTA                0
1                                                DATE         TRADE ID
2                                              6/4/13           130196
3                                             5/28/13           130158
4                                              6/4/13           130210
5                                             5/14/13           130079
6                                              6/4/13           130187
7                                              6/4/13           130208
8                                             6/11/13           130249
9                                              6/4/13           130204
10                                            5/28/13           130148
11                                            5/28/13           130149
12                                            5/28/13           130157
13                                            5/21/13           130105
14                                            5/21/13           130106
15                                             6/4/13           130205
16                                            6/11/13           130250
17                                             6/4/13           130206
18                                            6/11/13           130248
19                                       QUOTA TO BUY                0
20                                               DATE         TRADE ID
21                                            6/11/13           130239
22                                            5/14/13           130074
23                                            3/26/13           130006
24                                            5/14/13           130075
25                                             5/7/13           130023
26                                            5/14/13           130039
27                                                  1                0

         Unnamed: 2     Unnamed: 3  Unnamed: 4
0                 0              0           0
1   AVAILABLE STOCK         AMOUNT  SALE PRICE
2           COD GBW          10000         0.6
3           COD GBW            300         0.6
4       HADDOCK GBE   UP TO 30,000      OFFERS
5            PLAICE           1000        0.45
6        WHITE HAKE   UP TO 25,000         0.5
7        WHITE HAKE           4000         0.5
8         WINTER GB           3300        0.25
9         WINTER GB          10000        0.48
10        WINTER GB   1U0P 0T,0O00        0.25
11        WINTER GB   UP TO 10,000         0.4
12        WINTER GB           1400        0.25
13        WINTER GB          10000         0.5
14        WINTER GB          10000         0.5
15       WINTER GOM           1000        0.38
16       WINTER SNE           6500         0.4
17       WINTER SNE           3000        0.63
18   YELLOWTAIL GOM           2000        1.25
19                0              0           0
20    DESIRED STOCK         AMOUNT   BUY PRICE
21          COD GOM   UP TO 14,000         2.1
22          COD GOM          20000     INQUIRE
23          COD GBE            ANY         1.5
24      HADDOCK GOM          10000     INQUIRE
25      HADDOCK GOM    UP TO 6,000        0.75
26       WHITE HAKE  UP TO 100,000         0.3
27                0              0           0
<class 'pandas.core.frame.DataFrame'>

My code:
import os
import numpy as np
import pandas as pd
import cx_Oracle
import re
from dateutil import parser
from datetime import datetime

dsnStr = cx_Oracle.makedsn("sole.noaa.gov", "1526", "sole")
con = cx_Oracle.connect(user="user", password="password$", dsn=dsnStr)

path = 'Z:\\excel_file_to_parse'

pattern = re.compile(r'Listing(.+)', re.IGNORECASE)

for filename in os.listdir(path):
    file_path = os.path.join(path, filename)
    if os.path.isfile(file_path):
        df = pd.read_excel(file_path)
        #print("df is:", df)

        a = pattern.findall(str(df))
        print("a:", a)

        new_a = str(a)
        print("new_a:", new_a)

        #datetime_object = datetime.strptime(new_a, '%b %d %Y')
        #print("date:", datetime_object)

        print("row 1:", df.loc[0])

        df = df.fillna(0)
        print("df wihtout 0's is:", df)

cursor = con.cursor()
exported_data = [tuple(x) for x in df.values]
sql_query = ("INSERT INTO ROUGHTABLE(species, date_posted, stock_id, pounds, money, sector_name, ask)" "VALUES(:3, :1, :2, :4, :5, 'Sustainable Harvest Sector', '1')")

cursor.executemany(sql_query, exported_data)
con.commit() #commit to database

cursor.close()
con.close()

Printout of exported_data:
exported_data: [('AVAILABLE QUOTA', 0, 0, 0, 0), ('DATE', 'TRADE ID', 'AVAILABLE STOCK', 'AMOUNT', 'SALE PRICE'), ('6/4/13', 130196, 'COD GBW', 10000, 0.6), ('5/28/13', 130158, 'COD GBW', 300, 0.6), ('6/4/13', 130210, 'HADDOCK GBE', 'UP TO 30,000', 'OFFERS'), ('5/14/13', 130079, 'PLAICE', 1000, 0.45), ('6/4/13', 130187, 'WHITE HAKE', 'UP TO 25,000', 0.5), ('6/4/13', 130208, 'WHITE HAKE', 4000, 0.5), ('6/11/13', 130249, 'WINTER GB', 3300, 0.25), ('6/4/13', 130204, 'WINTER GB', 10000, 0.48), ('5/28/13', 130148, 'WINTER GB', '1U0P 0T,0O00', 0.25), ('5/28/13', 130149, 'WINTER GB', 'UP TO 10,000', 0.4), ('5/28/13', 130157, 'WINTER GB', 1400, 0.25), ('5/21/13', 130105, 'WINTER GB', 10000, 0.5), ('5/21/13', 130106, 'WINTER GB', 10000, 0.5), ('6/4/13', 130205, 'WINTER GOM', 1000, 0.38), ('6/11/13', 130250, 'WINTER SNE', 6500, 0.4), ('6/4/13', 130206, 'WINTER SNE', 3000, 0.63), ('6/11/13', 130248, 'YELLOWTAIL GOM', 2000, 1.25), ('QUOTA TO BUY', 0, 0, 0, 0), ('DATE', 'TRADE ID', 'DESIRED STOCK', 'AMOUNT', 'BUY PRICE'), ('6/11/13', 130239, 'COD GOM', 'UP TO 14,000', 2.1), ('5/14/13', 130074, 'COD GOM', 20000, 'INQUIRE'), ('3/26/13', 130006, 'COD GBE', 'ANY', 1.5), ('5/14/13', 130075, 'HADDOCK GOM', 10000, 'INQUIRE'), ('5/7/13', 130023, 'HADDOCK GOM', 'UP TO 6,000', 0.75), ('5/14/13', 130039, 'WHITE HAKE', 'UP TO 100,000', 0.3), (1, 0, 0, 0, 0)]


text:
Q: Breeze auth middleware redirect back login page itself When I request to login on breeze, user date is passing but auth middleware redirect back to login page. It has also 302 response in result.
Do you have any experience on it ?
I use Laravel 8
Breeze Package

A: After installation Breeze, I had to make changes and it's down.
The solution for my case is to install again the package.


text:
Q: Add Score in maze game written in java I am going to make a maze game in java. I have done almost but i have facing problem to add score. I have add the time spend to end the game, but it doesn;t terminate. here is my code. Please help me to print the total time.....
package Maze;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Board extends JPanel implements ActionListener
 {
     private Timer timer;
     private Map m;
     private Player p;
     private boolean win=false;
     long startTime=0;
     long message=0;

     public Board()
     {
         startTime=System.currentTimeMillis();
         m= new Map();
         p= new Player();
         addKeyListener(new Al());
         setFocusable(true);
         timer=new Timer(25, this);
         timer.start();
     }

     public void actionPerformed(ActionEvent e)
     {
         if(m.getMap(p.getTileX(), p.getTileY()).equals("f"))
         {
             win=true;
             message=(startTime+10000)-System.currentTimeMillis();
         }

        repaint();
     }
     public void paint(Graphics g)
     {
        super.paint(g);
        if(!win&&(System.currentTimeMillis()<=(startTime+10000)))
        {
         for(int y=0;y<14;y++)
         {
             for(int x=0;x<14;x++)
             {
                 if(m.getMap(x,y).equals("f"))
                     g.drawImage(m.getFinish(), x*32, y*32, null);
                 if(m.getMap(x, y).equals("w"))
                        g.drawImage(m.getWall(), x*32, y*32, null);
                if(m.getMap(x, y).equals("g"))
                        g.drawImage(m.getGrass(), x*32, y*32, null);

             }
         }
         g.drawImage(p.getPlayer(), p.getTileX()*32, p.getTileY()*32,null);
        }

            else if(win)
             {
                long end = System.currentTimeMillis();
                long time=end-startTime;
                //String str=Long.toString(time);
                JOptionPane.showMessageDialog(null, "Your Score:"+time);
                //System.exit(0);
                //g.drawImage(m.getWinn(), 32, 32, null);
                //JOptionPane.showMessageDialog(this, "Winner");
             }
        else
        {
            g.drawImage(m.getLose(), 32, 32, null);
        }

     }
     public class Al extends KeyAdapter{

         public void keyPressed(KeyEvent e){

        /*   long startTime1 = System.currentTimeMillis();
             totalTime=(startTime1-startTime)/1000;
             JOptionPane.showMessageDialog(null,totalTime); */
             int keycode= e.getKeyCode();

             if(keycode==KeyEvent.VK_UP )
             {
                 if(!m.getMap(p.getTileX(),p.getTileY()-1).equals("w"))
                 {
                     p.move( 0, -1);
                 }
             }

             if(keycode==KeyEvent.VK_DOWN )
             {
                 if(!m.getMap(p.getTileX(),p.getTileY()+1).equals("w"))
                 {
                     p.move( 0, 1);
                 }
             }
             if(keycode==KeyEvent.VK_LEFT )
             {
                 if(!m.getMap(p.getTileX()-1,p.getTileY()).equals("w"))
                 {
                     p.move( -1, 0);
                 }
             }
             if(keycode==KeyEvent.VK_RIGHT )
             {
                 if(!m.getMap(p.getTileX()+1,p.getTileY()).equals("w"))
                 {
                     p.move( 1, 0  );
                 }

             }

         }

     }
 }

and here is my confusion point
else if(win)
{
    long end = System.currentTimeMillis();
    long time=end-startTime;
    // String str=Long.toString(time);
    JOptionPane.showMessageDialog(null, "Your Score:"+time);
    // System.exit(0);
    // g.drawImage(m.getWinn(), 32, 32, null);
    //JOptionPane.showMessageDialog(this, "Winner");
}

A: I'm guessing you want the game to finish if:

*

*The player wins: win == true, or

*The time's over: System.currentTimeMillis() <= (startTime+10000)
If that's the case, your if condition.-
if (!win && (System.currentTimeMillis() <= (startTime + 10000)))

would be ok, but your else branch.-
else if(win)

would be just:
else

instead. In other words: as long as the player haven't won and there's time left, the game go on. Otherwise (regardless the player did win or not), show score.


text:
Q: "Argument not specified for parameter" using Ninject in web forms Just to re-iterate the title, this is web forms and not mvc.  Also it's using vb.net.
I have used nuget to add ninject.web to my project.  I have configured NinjectWebCommon's "RegisterServices" method as follows:
Private Shared Sub RegisterServices(kernel As IKernel)
    kernel.Bind(Of ilbdUOW)().[To](Of lbdUOW)()
End Sub

Everything compiles clean.  When I run the simple web form (.aspx page, no master page), I get the following error:
BC30455: Argument not specified for parameter '_uow' of 'Public Sub New(_uow As lbD.data.lbdUOW)'.

And it points to line 52 in the compiled code:
Line 51:         Public Sub New()
Line 52:             MyBase.New
Line 53:             Dim dependencies() As String

which (I believe) comes from the top of the .aspx page when compiled, where I have the following code for the "new" constructor:
<Inject()> _
Public Sub New(_uow As ilbdUOW)
    Uow = _uow
End Sub

(well, I say "I believe" but I know it is as if I change the "ilbdUOW" from the interface to the class of "lbdUOW" it changes the error message accordingly so that's definitely where it's coming from)
If I put a debug stop on the "uow = _uow" line in my "New" constructor and also another debug stop in the "RegisterServices" method in the NinjectWebCommon file, the debugger only stops on the "RegisterServices" debug point and never gets to hit the debug stop in the main .aspx page.
I'm now completely lost.  I am trying to get my head around what is relatively new to me and I thought I was pretty much getting there. My understanding is that the code in "RegisterServices" in NinjectWebCommon will recognise that I'm requiring an instance of my "ilbdUOW" interface when it is referenced in a constructor (such as my "new" constructor in my .aspx page) and will inject it automatically, thus making the unit of work instance available for me to access the database with.
If anyone can point me in the right direction I'd be really grateful, thanks.
Edited to add:
@mipe34
Not on the "new" constructor, no:
Public Sub New(ByVal repositoryProvider As IRepositoryProvider)
    MyBase.New()
    CreateDbContext()
    repositoryProvider.DbContext = DbContext
    _RepositoryProvider = repositoryProvider
End Sub

I have also set up the "RegisterServices" section to map those interfaces too, but it makes no difference to the error I get whether those extra mappings are in there or not, it seems to fail before I get to that point.
I have had these lines in and out of the "RegisterServices" section and it makes no difference:
    kernel.Bind(Of RepositoryFactories)().[To](Of RepositoryFactories)().InSingletonScope()
    kernel.Bind(Of IRepositoryProvider)().[To](Of RepositoryProvider)()

A: WebForm are created by ASP.NET not Ninject You can't use constructor injection on WebForms. You have to do property injection instead.


text:
Q: Evaluation Error: Error while evaluating a Function Call, Could not find class ::apt-get::update for ubuntu-bionic.example.com I'm getting the following error when running puppet on Vagrant/VirtualBox with the "ubuntu/bionic64" image:
Error: Evaluation Error: Error while evaluating a Function Call, Could not find class ::apt-get::update for ubuntu-bionic.example.com (file: /tmp/vagrant-puppet/manifests-846018e2aa141a5eb79a64b4015et6f3/default.pp, line: 2, column: 5) on node ubuntu-bionic.example.com
The SSH command responded with a non-zero exit status. Vagrant
assumes that this means the command failed. The output for this command
should be in the log above. Please read the output to determine what
went wrong.

Environment:

*

*Vagrant 2.1.1

*VirtualBox 5.2.16

*Ubuntu Bionic 64

*Puppet 5.4.0

Vagrantfile:
...
config.vm.box = "ubuntu/bionic64"
...
config.vm.provision "shell", inline: "apt-get update && apt-get install -y puppet"
config.vm.provision "puppet" do |puppet|
  puppet.module_path = "puppet/modules"
  puppet.manifests_path = "puppet/manifests"
  puppet.manifest_file  = "default.pp"
  puppet.options="--verbose --debug"
end
...

This same exact puppet configuration was working with the ubuntu/xenial64 box. The only thing that I changed was the config.vm.box line in my Vagrantfile (from config.vm.box = "ubuntu/xenial64" to config.vm.box = "ubuntu/bionic64". I've also confirmed that my module exists and I can see it on the vm in the /tmp directory.

A: I was able to fix the problem by renaming my apt-get module to apt_get.
Going from Ubuntu Xenial to Ubuntu Bionic takes Puppet from v3.8.5 to v5.4.0. Apparently, using hyphens in a module name isn't allowed (though it used to work).


text:
Q: Is overriding Objective-C framework methods ever a good idea? ObjC has a very unique way of overriding methods. Specifically, that you can override functions in OSX's own framework. Via "categories" or "Swizzling". You can even override "buried" functions only used internally.
Can someone provide me with an example where there was a good reason to do this? Something you would use in released commercial software and not just some hacked up tool for internal use?
For example, maybe you wanted to improve on some built in method, or maybe there was a bug in a framework method you wanted to fix.
Also, can you explain why this can best be done with features in ObjC, and not in C++ / Java and the like. I mean, I've heard of the ability to load a C library, but allow certain functions to be replaced, with functions of the same name that were previously loaded. How is ObjC better at modifying library behaviour than that?

A: If you're extending the question from mere swizzling to actual library modification then I can think of useful examples.
As of iOS 5, NSURLConnection provides sendAsynchronousRequest:queue:completionHandler:, which is a block (/closure) driven way to perform an asynchronous load from any resource identifiable with a URL (local or remote). It's a very useful way to be able to proceed as it makes your code cleaner and smaller than the classical delegate alternative and is much more likely to keep the related parts of your code close to one another.
That method isn't supplied in iOS 4. So what I've done in my project is that, when the application is launched (via a suitable + (void)load), I check whether the method is defined. If not I patch an implementation of it onto the class. Henceforth every other part of the program can be written to the iOS 5 specification without performing any sort of version or availability check exactly as if I was targeting iOS 5 only, except that it'll also run on iOS 4.
In Java or C++ I guess the same sort of thing would be achieved by creating your own class to issue URL connections that performs a runtime check each time it is called. That's a worse solution because it's more difficult to step back from. This way around if I decide one day to support iOS 5 only I simply delete the source file that adds my implementation of sendAsynchronousRequest:.... Nothing else changes.
As for method swizzling, the only times I see it suggested are where somebody wants to change the functionality of an existing class and doesn't have access to the code in which the class is created. So you're usually talking about trying to modify logically opaque code from the outside by making assumptions about its implementation. I wouldn't really support that as an idea on any language. I guess it gets recommended more in Objective-C because Apple are more prone to making things opaque (see, e.g. every app that wanted to show a customised camera view prior to iOS 3.1, every app that wanted to perform custom processing on camera input prior to iOS 4.0, etc), rather than because it's a good idea in Objective-C. It isn't.
EDIT: so, in further exposition — I can't post full code because I wrote it as part of my job, but I have a class named NSURLConnectionAsyncForiOS4 with an implementation of sendAsynchronousRequest:queue:completionHandler:. That implementation is actually quite trivial, just dispatching an operation to the nominated queue that does a synchronous load via the old sendSynchronousRequest:... interface and then posts the results from that on to the handler.
That class has a + (void)load, which is the class method you add to a class that will be issued immediately after that class has been loaded into memory, effectively as a global constructor for the metaclass and with all the usual caveats.
In my +load I use the Objective-C runtime directly via its C interface to check whether sendAsynchronousRequest:... is defined on NSURLConnection. If it isn't then I add my implementation to NSURLConnection, so from henceforth it is defined. This explicitly isn't swizzling — I'm not adjusting the existing implementation of anything, I'm just adding a user-supplied implementation of something if Apple's isn't available. Relevant runtime calls are objc_getClass, class_getClassMethod and class_addMethod.
In the rest of the code, whenever I want to perform an asynchronous URL connection I just write e.g.
[NSURLConnection sendAsynchronousRequest:request
    queue:[self anyBackgroundOperationQueue]
    completionHandler:
    ^(NSURLResponse *response, NSData *data, NSError *blockError)
    {
        if(blockError)
        {
            // oh dear; was it fatal?
        }

        if(data)
        {
            // hooray! You know, unless this was an HTTP request, in
            // which case I should check the response code, etc.
        }

        /* etc */
    }

So the rest of my code is just written to the iOS 5 API and neither knows nor cares that I have a shim somewhere else to provide that one microscopic part of the iOS 5 changes on iOS 4. And, as I say, when I stop supporting iOS 4 I'll just delete the shim from the project and all the rest of my code will continue not to know or to care.
I had similar code to supply an alternative partial implementation of NSJSONSerialization (which dynamically created a new class in the runtime and copied methods to it); the one adjustment you need to make is that references to NSJSONSerialization elsewhere will be resolved once at load time by the linker, which you don't really want. So I added a quick #define of NSJSONSerialization to NSClassFromString(@"NSJSONSerialization") in my precompiled header. Which is less functionally neat but a similar line of action in terms of finding a way to keep iOS 4 support for the time being while just writing the rest of the project to the iOS 5 standards.

A: There are both good and bad cases.  Since you didn't mention anything in particular these examples will be all-over-the-place.
It's perfectly normal (good idea) to override framework methods when subclassing:

*

*When subclassing NSView (from the AppKit.framework), it's expected that you override drawRect:(NSRect).  It's the mechanism used for drawing views.

*When creating a custom NSMenu, you could override insertItemWithTitle:action:keyEquivalent:atIndex: and any other methods...

The main thing when subclassing is whether or not your behaviour completes re-defines the old behaviour... or extends it (in which case your override eventually calls [super ...];)

That said, however, you should always stand clear of using (and overriding) any private API methods (those normally have an underscore prefix in their name).  This is a bad idea.
You also should not override existing methods via categories.  That's also bad.  It has undefined behaviour.

A: If you're talking about categories, you don't override methods with them (because there is no way to call original method, like calling super when subclassing), but only completely replace with your own ones, which makes the whole idea mostly pointless. Categories are only useful for safely extending functionality, and that's the only use I have even seen (and which is a very good, an excellent idea), although indeed they can be used for  dangerous things.
If you mean overriding by subclassing, that is not unique. But in Obj-C you can override everything, even private undocumented methods, not just what was declared 'overridable' like in other languages. Personally, I think it's nice, as I remember in Delphi and C++ I used to "hack" access to private and protected members to workaround an internal bug in framework. This is not a good idea, but at some moments it can be a life saver.
There is also method swizzling, but that's not standard language feature, that's a hack. Hacking undocumented internals is rarely a good idea.
And regarding "how can you explain why this can best be done with features in ObjC", the answer is simple — Obj-C is dynamic, and this freedom is common to almost all dynamic languages (Javascript, Python, Ruby, Io, a lot more). Unless artificially disabled, every dynamic language has it.
Refer to the wikipedia page on dynamic languages for longer explanation and more examples. For example, an even more miraculous things possible in Obj-C and other dynamic languages is that an object can change it's type (class) in place, without recreation.


text:
Q: How do i Turn ON/OFF the Caps lock key We can able to detect the Caps lock key is ON/OFF using Jquery.
My question is
"can we possible to Turn ON/OFF the Caps lock key using Jquery or Javascript in Keypress event".
And also using C#, How to achieve this?
Thanks in advance !!!

A: You can't change whether the caps lock key is on or off. You can however change whether your input strings are lower or upper case with Javascript based on whether the caps lock key is on or off.
for (char in inputString) {
    if(capslock) { // do your caps lock detection here
        if(char === char.toUpperCase()) { // it's upper case
            char = char.toLowerCase();
        } else {
            char = char.toUpperCase();
        }
    }
}

A: You can't do this jquery like javascript will be sandboxed inside the browser.

A: Detection only:
$('#id').keypress(function(e) {
    var s = String.fromCharCode( e.which );
    if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
        alert('caps is on');
    }
});

A: If this would be possible, then I would be able to control user's sound volume, or maybe check what he have in hard disk, I may be more curious and spy his network card traffic...I would own the world with a simple JavaScript file :)


text:
Q: How to split a unlimited & dynamically created list into column using css/jquery I am trying to start with an unordered list of dynamically created items that needs to be broken down into unlimited columns of 10 items per column depending of the amount of content.

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

I want to use jquery to split it into separate column of 10 for an unlimited amount of
columns.

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

Data

A: It doesn't make much sense to me to do this (if the DOM isn't what you want it to be, change the DOM without JS), but maybe I'm missing the bigger picture. To answer your question, you could do something like this:
// Also store list, to be able to efficiently remove it later on
var $items = $('.list > li');
var total = Math.floor($items.length / 10);

for (var i=1, i<=total; i++) {
  $items.eq(i*10).after('

');
}


text:
Q: nice sudo or sudo nice? is there any difference between running an intensive task over sudo with the following commands?:

*

*nice sudo [intensive command here]

*sudo nice [intensive command here]

BTW this is for Linux 3.x.

A: Using the 'principle of least privilege' you should only run a program with root privileges if it needs them, and then drop them again as soon as you don't need them anymore.
So yes, there is a difference, if there is an exploit for nice, an attacker could run code with the same privileges as the nice program.
Also, sudo resets your environment, so it migh thave side effects, try
$ echo 'echo $PATH' | sh
/usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/home/jens/.local/bin:/home/jens/bin:/home/jens/.local/bin
$ echo 'echo $PATH' | sudo sh
[sudo] password for jens:
/sbin:/bin:/usr/sbin:/usr/bin

So the 'nice' command you run via sudo might actually end up being a different binary.
$ which ash
~/.local/bin/ash
$ sudo which ash
[sudo] password for jens:
which: no ash in (/sbin:/bin:/usr/sbin:/usr/bin)

A: Late answer:
If your sudo access is limited to certain programs (foo and bar, for example), then you won't have authority to run sudo nice foo, but will be allowed to run nice sudo foo.

A: If you run nice sudo then the prompt for your password will also be niced, but since you'll spend far more time typing it, it really doesn't matter much.
As ThoriumBR noted, if you are lowering the priority, then the order is irrelevant, but if you want to raise the priority, then (since this must be done as root) you must use sudo nice.
Otherwise I can't imagine any real difference.

A: There's a difference, a crucial one.
If you want to decrease the process' priority, the order does not matter. On the other hand, if you want to increase it, you must put sudo before nice.
Since you are running the command as a normal user (otherwise you would not bother with sudo at all), you can only decrease the priority of your command. But if you use sudo first, you can increase it if you want.


text:
Q: Converting raw ASCII text with UTF-8 encoded characters represented by backslash escapes I collect Persian tweets running the following python code:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import tweepy
import json
import os

consumer_key ="xxxx"
consumer_secret ="xxxx"
access_key = "xxxx"
access_secret = "xxxx"

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)

save_file = open("Out.json", 'a')

t1 = u""

class CustomStreamListener(tweepy.StreamListener):
    def __init__(self, api):
        self.api = api
        super(tweepy.StreamListener, self).__init__()

        # self.list_of_tweets = []

    def on_data(self, tweet):
        print tweet
        save_file.write(str(tweet))

    def on_error(self, status_code):
        print >> sys.stderr, 'Encountered error with status code:', status_code
        return True # Don't kill the stream
        print "Stream restarted"

    def on_timeout(self):
        print >> sys.stderr, 'Timeout...'
        return True # Don't kill the stream
        print "Stream restarted"

def start_stream():
    while True:
        try:
            sapi = tweepy.streaming.Stream(auth, CustomStreamListener(api))
            sapi.filter(track=[t1])
        except:
            continue

start_stream()

It returns tweets text in raw ASCII text with UTF-8 encoded characters represented by backslash escapes. I would like to change the code in a way that directly saves the retrieved tweets in "Out.json" in UTF-8 encoded format.
{
    "created_at": "Tue Feb 07 08:04:17 +0000 2017",
    "id": 828877025049972737,
    "id_str": "828877025049972737",
    "text": "\u0644\u0637\u0641\u0627 \u0628\u0647 \u062d\u06cc\u0648\u0627\u0646\u0627\u062a \u063a\u06cc\u0631\u062e\u0627\u0646\u06af\u06cc \u063a\u0630\u0627\u00a0\u0646\u062f\u0647\u06cc\u062f https:\/\/t.co\/gFi5XCVQww https:\/\/t.co\/pQWPqbvJVF",
    "display_text_range": [0, 58],
    "source": "\u003ca href=\"http:\/\/publicize.wp.com\/\" rel=\"nofollow\"\u003eWordPress.com\u003c\/a\u003e",
    "truncated": false,
    "in_reply_to_status_id": null,
    "in_reply_to_status_id_str": null,
    "in_reply_to_user_id": null,
    "in_reply_to_user_id_str": null,
    "in_reply_to_screen_name": null,
    ...
    "lang": "fa",
    "timestamp_ms": "1486454657219"
}

A: Remove str call:
# ...

def on_data(self, tweet):
    print tweet
    save_file.write(tweet)

# ...

If it doesn't help, open your file using codecs module:
save_file = codecs.open("Out.json", 'a', encoding="utf-8")

A: The StreamListener.on_data() method is passed the raw JSON data as received from Twitter. It is this data that contains valid JSON escape sequences.
If you wanted to save UTF-8 data directly, so with the \uhhhh escape sequences replaced by the actual Unicode codepoint, you'll have to re-code the tweet. Use Saving utf-8 texts in json.dumps as UTF8, not as \u escape sequence to save the data afterwards.
Do note that writing multiple JSON objects to one file makes that file itself invalid JSON. You could produce JSON Lines output by injecting newlines (the standard json.dumps() output does not produce newlines in the generated JSON document), then read those entries one by one with this answer.
So the important sections of your code should look like:
import json

save_file = open("Out.json", 'a')

class CustomStreamListener(tweepy.StreamListener):
    # ...

    def on_data(self, tweet):
        tweet = json.loads(tweet)
        json_doc = json.dumps(tweet, ensure_ascii=False)
        save_file.write(json_doc.encode('utf8') + '\n')


text:
Q: Facing error : Cannot create symbolic link I m trying to install openSSL but its giving me error while extracting openssl-1.0.1g.tar:
Error:
D:\openssl-1.0.1g.tar_3: Cannot create symbolic link D:\openssl-1.0.1g\apps\md4.c
A required privilege is not held by the client. !

Actually I am trying to generate CSR/PEM encoded Certificate request file. So for that I need to install openSSL but its giving me this error while extracting. Can anyone guide me in a right direction.

A: Rather than extracting tarball with the source code of OpenSSL you should use installer with precompiled binaries from OpenSSL for Windows project.


text:
Q: How to loop over a matlab image without making copies? I was trying to loop over an image in MATLAB but my code is running to slow. I am fairly knew to MATLAB but I suspect that it's because it's making a copy of my randomly selected image. My code is:
function patches = sampleIMAGES()
load IMAGES;    % load images from disk
patchsize = 8;  % we'll use 8x8 patches
numpatches = 10000;
patches = zeros(patchsize*patchsize, numpatches);

size_img = size(IMAGES);
num_rows_img = size_img(1);
num_cols_img = size_img(2);
num_images = size_img(3);
for i=1:numpatches,
    %get random image
    rand_img_number = randi(num_images);
    rand_img = IMAGES(:, :, rand_img_number);
    %get random patch patchsizexpatchsize
    rand_row = randi(num_rows_img - patchsize);
    rand_col = randi(num_cols_img - patchsize);
    rand_patch = rand_img(rand_row:rand_row+patchsize-1, rand_col:rand_col+patchsize-1);
    patches(:, i) = rand_patch(:)';
end
end

How is it possible to loop over this without making a copy if MATLAB does not allow to index twice into a matrix/array?

A: Approach #1 - im2col based
numpatches = 10000; %//Number of patches
blksz = 8; %// Blocksize

[m,n,r] = size(IMAGES); %// Get sizes

%// Store blocks from IMAGES as columns, so that they could be processed in
%// a vectorized fashion later on
blks_col(blksz*blksz,(m-blksz+1)*(n-blksz+1),r)=0; %// Pre-allocate
for k1=1:r
    blks_col(:,:,k1) = im2col(IMAGES(:,:,k1),[blksz blksz],'sliding');
end
blks_col = reshape(blks_col,size(blks_col,1),[]);

%// Get rand row, column and dimension-3 indices to be used for indexing
%// into blks_col in one go
rand_row = randi(size(IMAGES,1)-blksz+1,numpatches,1);
rand_col = randi(size(IMAGES,2)-blksz+1,numpatches,1);
rand_dim3 = randi(size(IMAGES,3),numpatches,1);

%// Select the specific column from blks_col that represents the
%// [blksz x blksz] used to make a single patch in each iteration from
%// original code
num_cols_im2col = (m-blksz+1)*(n-blksz+1);
col_ind = (rand_dim3-1)*num_cols_im2col + (rand_col-1)*(m-blksz+1) + rand_row;
patches = blks_col(:,col_ind);

Example
As an example I assumed IMAGES as the 3D data obtained from reading one of the images provided in the image gallery of Image Processing Toolbox and increased the number of patches to 100000, i.e. -
IMAGES = imread('peppers.png');
numpatches = 100000;

The runtime with original code - 22.376446 seconds.
The runtime with im2col based code - 2.237993 seconds
Then, I doubled the number of patches to 200000, for which the runtime with original code literally doubled and im2col based approach's runtime stayed around that ~2.3 sec mark.
Thus, this im2col based approach would make sense when you are working with lots of patches as opposed to when working with lots of images (that are put in the third dimension of IMAGES).

Approach #2 - Indexing based
Being a purely indexing based approach, this is expected to be memory-efficient and good with performance too.
numpatches = 10000; %//Number of patches
blksz = 8; %// Blocksize
[m,n,r] = size(IMAGES); %// Get sizes

%// Get rand row, column and dimension-3 indices to be used for indexing
rand_row = randi(size(IMAGES,1)-blksz+1,numpatches,1);
rand_col = randi(size(IMAGES,2)-blksz+1,numpatches,1);
rand_dim3 = randi(size(IMAGES,3),numpatches,1);

%// Starting indices for each patch
start_ind = (rand_dim3-1)*m*n + (rand_col-1)*m + rand_row;

%// Row indices for each patch
lin_row = permute(bsxfun(@plus,start_ind,[0:blksz-1])',[1 3 2]);   %//'

%// Get linear indices based on row and col indices
lin_rowcol = reshape(bsxfun(@plus,lin_row,[0:blksz-1]*m),blksz*blksz,[]);

%// Finally get the patches
patches = IMAGES(lin_rowcol);

A: To no longer copy the images, instead of these two lines:
rand_img = IMAGES(:, :, rand_img_number);
rand_patch = rand_img(rand_row:rand_row+patchsize-1, rand_col:rand_col+patchsize-1);

combine both to one line:
rand_patch = IMAGES(rand_row:rand_row+patchsize-1, rand_col:rand_col+patchsize-1, rand_img_number);

Another way to improve the performance: Generating 100 random numbers at onece is faster than generating 1 number 100 times. Generate all numbers you need outside the loop:
rand_img_number = randi(num_images,numpatches,1);

Then use rand_img_number(i) instead of rand_img_number inside the loop. Do the same for the two other random numbers.


text:
Q: How to display the time of a Date object based on DateFormat.SHORT and locale? I am using Java 7 and I need to display the time part of a Java Date object.
I notice that DateFormat has the SHORT constant according to the page and the page has the following description:

SHORT is completely numeric, such as 12.13.52 or 3:30pm

My question is how to display only the time part (such as "3:30pm"). The following is what I have and it only shows the date part (such as 2/14/15):
DateFormat f = DateFormat.getDateInstance(DateFormat.SHORT, A_Locale_object);
SimpleDateFormat sf = (SimpleDateFormat) f;
sf.format(new Date());

A: If what you want to display is the time part, what ou need to call is getTimeInstance(), and not getDateInstance().
This is the kind of answer that you should learn to find by yourself, simply by reading the javadoc:

Use getDateInstance to get the normal date format for that country. There are other static factory methods available. Use getTimeInstance to get the time format for that country. Use getDateTimeInstance to get a date and time format.

A: So If you want to display the time part, what you can do is provide the format to SimpleDatFormat and your locale like below
SimpleDateFormat sf = new SimpleDateFormat("hh:mm a", your_locale);
And format it like you did
sd.format(new Date()));
If you want more stuff to be formatted, you can definitely add more like "YY.MM.dd hh:mm a"
You can read the SimpleDateFormat document for more info http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

A: Use getTimeInstance  instead of getDateInstance.
DateFormat f = DateFormat.getTimeInstance(DateFormat.SHORT,Locale.getDefault());

A: Time Zone
The Question and other Answers neglect the crucial issue of time zone. If not specified, the JVM's current default time zone is automatically applied.
Joda-Time
Such work is easier with the Joda-Time library.
Example using Joda-Time 2.7.
Translate the java.util.Date object to a Joda-Time DateTime object. Unlike a Date, a DateTime understands its assigned time zone. We want to adjust from the Date object's UTC zone to a desired zone such as Montréal.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ;
DateTime dateTime = new DateTime( yourDate, zone ) ;

Generate a String representation of this date-time value. A pair of characters passed to forStyle control the full, long, short etc. format of the date portion and the time portion. A hyphen suppresses display of that portion.
DateTimeFormatter formatter = DateTimeFormat.forStyle( "-S" ).withLocale( Locale.CANADA_FRENCH ) ;
String output = formatter.print( dateTime ) ;


text:
Q: ¿Cómo borrar todos los directorios que están ubicados dentro en un directorio con C#? Tengo una carpeta que se llama Archivos, en ella, varias carpetas, carpeta_1, carpeta_dos, etc, lo que deseo, es borrar todos las carpetas y archivos que se encuentran en la carpeta Archivos, sin borrar esta misma(Archivos).
Si uso esto, me borrar solo los archivos, pero no las carpetas que están dentro de Archivos
var file = Path.Combine(Server.MapPath("/Archivos/"), subdirectorio );
System.IO.File.Delete(file);

Si uso este de abajo, me dice que no encuetra la ruta:
System.IO.Directory.Delete(Server.MapPath("~/" + subdirectorio + msg.Attachments[0].Name), true);

me gustaría saber como poder hacerlo

A: Haces un foreach del directorio padre, leyendo los archivos y los directorios y los eliminas.
System.IO.DirectoryInfo di = new DirectoryInfo("Archivos");

foreach (FileInfo file in di.GetFiles())
{
    file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
    dir.Delete(true);
}


text:
Q: Cannot find module './auth.service' in Angular 7 I'm trying to use Angular Guards, to protect my pages from access without being authenticated.
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot , Router } from '@angular/router';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private authService: AuthService,
        private router: Router) { }
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        if(this.authService.isAuth) {
            return true;
        } else {
            this.router.navigate(['/login']);
        }
    }
}

the problem is that I can not import the module auth.service. it show me this error ( cannot find module './auth.service'. any suggestions ?

A: you might want to check the path that stores the AuthService. The easiest ways is to erase whatever inside the quotation mark and place a ../ then your IDE will suggest you the path to your AuthService

A: You might want to check if the file is actually there! Also, try using Webstorm or Eclipse, or any kind of IDE to see the exact problems in the code. Sometimes the IDE even fixes the errors for you!


text:
Q: Can I prevent panning Leaflet map out of the world's edge? Is there a way to limit panning out of the world's edge? On this picture, brown is the world, grey is emptiness. I want to make it impossible to pan like this.

A: Leaflet allows you to control how much the map resists being dragged out of bounds with the maxBoundsViscosity option (value: 0 to 1). Setting it to maximum disables dragging out of bounds entirely.
var map = new L.Map('map', {
  center: bounds.getCenter(),
  zoom: 5,
  layers: [osm],
  maxBounds: bounds,
  maxBoundsViscosity: 1.0
});

This feature is available in 1.0.0. The relevant pull request includes a working example:

var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
  osmAttrib = '© OpenStreetMap contributors',
  osm1 = L.tileLayer(osmUrl, {
    maxZoom: 18,
    attribution: osmAttrib
  }),
  osm2 = L.tileLayer(osmUrl, {
    maxZoom: 18,
    attribution: osmAttrib
  }),
  bounds = new L.LatLngBounds(new L.LatLng(49.5, -11.3), new L.LatLng(61.2, 2.5));

var map1 = new L.Map('map1', {
  center: bounds.getCenter(),
  zoom: 5,
  layers: [osm1],
  maxBounds: bounds,
  maxBoundsViscosity: 0.75
});

var map2 = new L.Map('map2', {
  center: bounds.getCenter(),
  zoom: 5,
  layers: [osm2],
  maxBounds: bounds,
  maxBoundsViscosity: 1.0
});

var latlngs = L.rectangle(bounds).getLatLngs();
L.polyline(latlngs[0].concat(latlngs[0][0])).addTo(map1);
L.polyline(latlngs[0].concat(latlngs[0][0])).addTo(map2);
html,
body,
#map {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.0/dist/leaflet.css" />

Left: Bouncy maxBounds. Right: Not bouncy.

A: This is how I resolved it for the world map
var map = L.map('map').setView([51.505, -0.09], 3);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(map);

var southWest = L.latLng(-89.98155760646617, -180),
northEast = L.latLng(89.99346179538875, 180);
var bounds = L.latLngBounds(southWest, northEast);

map.setMaxBounds(bounds);
map.on('drag', function() {
    map.panInsideBounds(bounds, { animate: false });
});

See working example both for version .7.0.7 http://jsfiddle.net/exqar2w4/18/ and for version 1.0.3 http://jsfiddle.net/exqar2w4/20/

A: I use react-leaflet so syntax slightly different to above, but thought it would be helpful to show some sensible bounds to use (none of the answers above do that).
import Leaflet from 'leaflet'
import { Map as LeafletMap} from 'react-leaflet'

// Set map bounds.
// Allow scroll over the international date line, so users can comfortably zoom into locations near the date line.
const corner1 = Leaflet.latLng(-90, -200)
const corner2 = Leaflet.latLng(90, 200)
const bounds = Leaflet.latLngBounds(corner1, corner2)

Which is then rendered as...
<LeafletMap
  maxBoundsViscosity={1.0}
  maxBounds={bounds}
  {...otherProps}
>


text:
Q: How can I get 「req」 in my http file by using express I am using express to invoke api ~
Everying request go through: controller -> model -> http...
controller:
const model = require('./model');

module.exports = (req, res, next) => {
    model.fn().then(data => {
        res.render... // res.send
    })
}

model:
const http = new require('./http'); // http module with get/post

const fn = () => {
    return http.get();
};

module.exports = {
    fn
}

http:
const rp = require('request-promise');

const Http = () => {...};

Http.prototype.get = ...

Http.prototype.post = ...

module.exports = Http;

Now, I want to get req in http... How can I do this in whole situation without passing param


text:
Q: How to approach Supervised Regression Problem of MR image to 256 element vector data? I want to train a neural network to predict 256 values as below:

Inputs are 3D MR images. The dataset contains 20 subjects and their corresponding coil values. Now patch operation will not be possible to augment data since coil values depend on different parts of the brain.
How the 256 real values vary in 20 subjects:

from the histogram, it can be seen that out of 256 coils nearly 170 values do not change significantly.
As a beginner, I can say it is supervised regression problem.
Can these 256 values be predicted using the neural network?
I am using ResNet architecture. More details can be shared if required.


text:
Q: 'ReduceLROnPlateau' object has no attribute '_implements_train_batch_hooks' I'm trying to implement learning rate scheduling in my convolutional neural network for which I implemented the ReduceLROnPlateau method but I encounter this error.
My list of imports
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import seaborn as sns
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
np.random.seed(0)
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import itertools
from keras.utils.np_utils import to_categorical # convert to one-hot-encoding
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D
from keras.optimizers import RMSprop
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ReduceLROnPlateau
from keras.activations import selu

The code I'm using to implement it:
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2,patience=5, min_lr=0.001)
The full error that I encounter

My code is working without the learning rate scheduler and this is the error I get whenever I try to callback this particular scheduler.
Thank you

A: Changing
from keras.callbacks import ReduceLROnPlateau to
from tensorflow.keras.callbacks import ReduceLROnPlateau
might resolve your error.
Most probably it is happening because you are mixing tensorflow and keras imports.


text:
Q: Update a table that column names are unknown I have a table but i dont know its columns (I only know it has "id (Uniqueidentifier) column").
I can get all columns in the table with the following query:
    DECLARE @columnNames NVARCHAR(4000) = ''

    SELECT @columnNames += '[' + COLUMN_NAME + '] '
    FROM INFORMATION_SCHEMA.Columns
    WHERE TABLE_NAME = 'MY_TABLE' AND COLUMN_NAME NOT IN ('id')
    ORDER BY COLUMN_NAME

Now i want to update one record with another record's data...
How can i do this?
Thanks all...

A: This is how you can build a dynamic sql
DECLARE @columnNames NVARCHAR(4000)
DECLARE @idfrom int, @idto int
DECLARE @table nvarchar(50)
SET @table = 'MY_TABLE'
SET @idfrom = 5 -- id you are copying from
SET @idto = 2   -- id you are copying to

DECLARE @sqlstring nvarchar(max)

SELECT @columnNames = coalesce(@columnNames, 'SET ') + '[' + COLUMN_NAME + ']=t2.' + '[' + COLUMN_NAME + '],'
FROM INFORMATION_SCHEMA.Columns
WHERE TABLE_NAME = @table AND COLUMN_NAME NOT IN ('id')
ORDER BY COLUMN_NAME

SET @sqlstring = 'update t1 ' +stuff(@columnNames, len(@columnNames),1,'') + '
FROM @t t1
join @t t2 on t1.id =' + cast(@idto as varchar) + '
and t2.id = ' + cast(@idfrom as varchar)

EXEC( @sqlstring )

A: I think you can create a "insert into table1 ... select .. from table2" type insert string and then execute it with sp_executesql.
DECLARE @insertColumnNames NVARCHAR(4000) = ''
DECLARE @selectColumnNames NVARCHAR(4000) = ''

SELECT @insertcolumnNames += ',' + '[' + COLUMN_NAME + '] '
FROM INFORMATION_SCHEMA.Columns
WHERE TABLE_NAME = 'TABLE_1' AND COLUMN_NAME NOT IN ('id')
ORDER BY COLUMN_NAME

SELECT @selectcolumnNames += ',' + '[' + COLUMN_NAME + '] '
FROM INFORMATION_SCHEMA.Columns
WHERE TABLE_NAME = 'TABLE_2' AND COLUMN_NAME NOT IN ('id')
ORDER BY COLUMN_NAME

sp_executesql ('insert into TABLE_1 ('+@insertcolumnNames+') select '+ @selectcolumnNames +' from TABLE_2');

I think something similar to this can work
(you will need to remove the extra , from the column strings and this is not tested at all, just an idea)


text:
Q: Is there a wifi chip on this board? I have a Sony QX10 camera, with comes with built-in wifi. I want to to connect wired ethernet to it. I was hoping I could find a wifi chip inside the camera, and solder to where the ethernet traces go into the wifi chip. Here's what the motherboard looks like, -- several chips I could not identify, and none that are obviously wifi. I've added labels on the chips that are to small to read in white.

There's also a teardown video of a similar model here: http://youtu.be/aH0_dAtKofw .
I could not find any other chips or antennas elsewhere in the camera that were obviously related to wifi. Should there be an obvious antenna somewhere?
Is it possible that wifi is integrated into the large processor IC itself?

A: Regardless of which chip is which, it is unlikely that there is an ethernet connection in there anywhere.  The processor talks to the wifi module directly rather than over ethernet.  Sony wouldn't include the ethernet chips and transformers if there's no external ethernet connection
If you need a wired ethernet connection, you will have to get yourself a wifi router or access point.  Setup the camera to use the router, then connect your ethernet cable to the router.


text:
Q: Python using Groupby and Unpivot/pivot After  I am trying to count the number of project based for each stage. I want to have the columns be for the different stages, and the rows be for each month of every year we have. Right now I have all the data in a data-frame and i want to use the group-by tool to count the number of projects per month for every status, as mentioned before. If anyone needs further explanation I can answer questions.
Before

A: I don't know if this is exactly what you are looking for, so I made it real clear and if I didn't get what you meant let me know and I can easily fix it.
I think your dataframe looks something like this:
example_DF = pd.DataFrame({"stage_1":[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
                           "stage_2":[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]})
example_DF.index.name = "month"
print(example_DF)

And if you want to get the sum of each stage over each month you just do this:
for stage in example_DF.columns:
    print("The stage is: ", status)
    for group_index, grouped_DF in example_DF.groupby([example_DF.index, stage]):
        print(grouped_DF)

but I'm confused because that is just every cell in the dataframe/you used stage and status. Let me know if I am missing something!


text:
Q: Javascript/HTML Storage Options Under File Protocol (file://) I am developing an html application that is essentially a series of pages like a book. Within this application, I would like to store several JavaScript variables across pages. Think things like pages read, bookmarks, etc. When this application is viewed over HTTP, I plan to use localStorage with fallbacks for older browsers (globalStorage, userData, etc.).
However, this completely breaks down if the files are accessed via "file://", for example if viewed off of a CD. It seems that most (if not all) localStorage solutions will not work under the file protocol. Cookies are not an option either under "file://".
Any ideas on how to persist JavaScript data across html pages when they are being viewed via "file://"?
It really only needs to be available in the current user session. I really don't want to use frames, but as of yet, I can't think of another way to accomplish this

A: A buddy of mine at work helped me out with this problem by sharing his implementation of using window.name to store data across pages of a single window/session.
A similar implementation (and discussion around the method) can be found here: http://ajaxian.com/archives/whats-in-a-windowname
Preliminary tests I've been doing on this method look very promising. I tested this, under the file protocol (loading page from desktop, a.k.a. - "file:\") on the following browsers. It worked on all of them!!

*

*IE 6

*IE 7

*IE 8

*IE 9

*FF 3.6

*FF 4

*Chrome 11

*Opera 10

*Safari 4

I have not yet done any testing as to how much data you can store here, but the internets seem to agree on a value of 2 MB.
Sources, links, more information

*

*JavaScript Programmer's Reference (Google Books)

*Cookie-less Session Variables in JavaScript - Sitepoint Article

A: On Webkit (Chromium 12.0.742.21 dev-m) localStorage over file protocol worked fine to me.
On Gecko it's reported and should be improved soon.
You can even find a workaround, but I recommend that you develop using Chrome nightly build. So you'll not lose time moving it back to localStorage in future.


text:
Q: dynamic rewrites using $1, %1, %2 etc how to make more complex and dynamic rewrites using $1, %1, %2 etc.
I'm trying to make a more dynamic rewrite (got a lot of domians pointing to the same server/site)
#   put 'www' as subdomain if none is given
RewriteCond %{HTTP_HOST}        ^([^\.]+\.[^\.]+)$ [NC]
RewriteRule ^(.*)$          http://www.%1/$1 [L,R=301]

#   rewrite subdomains
RewriteCond %{HTTP_HOST}        ^(admin|files|imap|mysql)\.[^\.]+\.[^\.]+$ [NC]
RewriteCond %{REQUEST_URI}      !^/_(admin|files|imap|mysql)/ [NC]
RewriteRule ^(.*)$          /_%1/$1 [L]

#   redirect to subdomain
RewriteCond %{HTTP_HOST}        ^www\.([^\.]+\.[^\.]+)$ [NC]
RewriteCond %{REQUEST_URI}      ^/_([^/]*)/ [NC]
RewriteRule ^(.*)$          http://%1.domain.com/ [L,R=301]

#   rewrite 'secure' subdomain
RewriteCond %{HTTP_HOST}        ^(demo|secure)\.[^\.]+\.[^\.]+$ [NC]
RewriteCond %{REQUEST_URI}      !^/_secure/ [NC]
RewriteRule ^(.*)$          /_secure/$1 [L]

but now I'm confronting a problem..
by #redirect to subdomain I can't figure out how to solve the condition and rule like the other I have made.. somehow I need to extract the domain from the first condition and then use it in the rule with %1, but how can you do that when you got another condition in between?

A: The capture data for %1 etc is used from the RewriteCond immediately above the RewriteRule.
Is there any reason your URI path evaluation/capture can't just occur in the RewriteRule?  Something like this (I think this is what you're going for?):
RewriteCond %{HTTP_HOST}        ^www\.([^\.]+\.[^\.]+)$ [NC]
RewriteRule ^/_([^/]*)/$        http://$1.%1/ [L,R=301]