text:
Q: convert byte array into image(png) I have a byte[] which is returned by fetching data from some table. I want to convert this byte array into png image.
Note: I do not have byte array from an image as in similar examples elsewhere.
 byte[] bytes = modelDashboardService.exportMyQueuePNG("pp83900","1");

InputStream in = new ByteArrayInputStream(bytes);

BufferedImage bImageFromConvert = ImageIO.read(in);//ImageIO.read(url);//

if(bImageFromConvert != null){
  ImageIO.write(bImageFromConvert, "png", new File(
  "D:/test1.png"));

}
My byte[] is not null but my BufferedImage is null .

please help.
Byte[] is :
[37, 80, 68, 70, 45, 49, 46, 55, 10, 37, -30, -29, -49, -45, 10, 51, 32, 48, 32, 111, 98, 106, 10, 60, 60, 47, 76, 101, 110, 103, 116, 104, 32, 52, 57, 50, 47, 70, 105, 108, 116, 101, 114, 47, 70, 108, 97, 116, 101, 68, 101, 99, 111, 100, 101, 62, 62, 115, 116, 114, 101, 97, 109, 10, 120, -100, -115, -107, 65, 111, -29, 32, 16, -123, -17, -2, 21, 115, -20, 30, 66, -127, 1, -116, -113, -39, -124, -83, -68, 90, -59, -87, 67, -38, -12, -76, 90, -75, 77, -91, 85, -93, -86, -67, -12, -17, -17, 24, -127, 55, -119, 113, -99, 67, 34, -20, -9, -15, 24, 63, 6, -101, -125, -128, -103, 0, 14, -70, -46, -12, -1, 120, 40, -34, -117, -17, -66, -96, 107, -91, -63, 63, -47, 96, -90, 120, 55, 112, -66, -72, 37, -115, 51, 11, -35, 79, -64, -57, 75, 97, 21, -109, -96, -71, 6, -93, -104, -48, 64, -32, -57, 115, -79, 63, 101, -124, -78, 12, 117, -96, 80, 50, 110, 71, 40, -53, -103, -62, 64, 9, 73, 19, -14, 20, 114, -53, 74, -100, 90, 17, 75, -55, 108, 53, 69, 41, 44, 25, 87, 83, -108, -26, -126, -119, 73, 47, 109, 52, -61, 73, 47, 35, 43, -90, 39, -95, 10, -103, -55, 81, 93, -8, 18, 126, -46, -122, -36, -48, 12, 13, -97, -7, -12, 55, 81, 28, -119, -67, -105, -13, 121, 39, 121, 36, -24, 94, -50, 39, -100, -28, -111, 104, -109, 60, -110, 105, 47, -25, -61, 76, 114, 62, -59, 94, -51, -57, -73, -95, -8, -88, -85, -69, 62, -25, -108, -77, 53, 93, 114, 40, -64, 31, -118, -21, 31, -126, 34, 0, -65, 47, -82, -36, -50, 45, -74, -66, -2, -26, -1, -98, -111, 84, 45, -111, 87, -51, 10, -4, -61, -38, 117, 58, -99, -122, 35, 63, -95, 121, 8, 123, -32, 88, 47, 51, -80, -107, 33, -6, 1, -68, 104, 86, -66, 109, 126, -63, 124, -31, -21, -69, -38, 63, 12, -89, -94, -32, 97, 91, 6, 83, 55, 126, -34, -6, -29, -70, 19, 25, 43, 95, -50, 125, -90, 108, 44, 85, -40, -58, -127, -35, 114, -21, 78, -52, 34, -9, -91, -103, -62, 42, 108, -6, -40, 99, 29, 27, 38, 54, 26, -34, -76, -51, 118, -3, -69, -55, 17, -68, 12, -60, -3, -54, -75, -61, 37, 53, -57, -48, 72, -105, 44, -103, -40, -72, -92, -37, -47, 78, 55, 57, 79, 83, -122, -18, -69, -56, 51, -78, -47, -77, 117, 119, -75, -69, 119, 57, 34, 62, 70, 102, 61, -125, -126, -27, 58, 39, -77, 92, 68, -113, 67, -53, -8, 85, 58, 28, -128, -117, 12, 35, 27, 29, -87, -119, -4, 118, 19, 45, -33, 51, 47, 28, -28, -35, 113, 58, 20, 88, -123, -63, -21, -1, -9, 65, 21, -107, 82, -97, 41, -15, 6, 41, -74, 87, 110, 79, -21, 53, -52, 32, 72, 115, 86, -18, -6, -49, -53, 51, -55, 111, -5, 84, 15, -92, 25, -99, -91, 84, -12, -91, -126, -21, -35, 94, -64, -14, 13, 78, 12, -93, 76, 110, -40, -35, -96, 47, -41, 44, 13, -56, -26, 31, 113, 64, 107, -53, 10, 101, 110, 100, 115, 116, 114, 101, 97, 109, 10, 101, 110, 100, 111, 98, 106, 10, 53, 32, 48, 32, 111, 98, 106, 10, 60, 60, 47, 80, 97, 114, 101, 110, 116, 32, 52, 32, 48, 32, 82, 47, 67, 111, 110, 116, 101, 110, 116, 115, 32, 51, 32, 48, 32, 82, 47, 84, 121, 112, 101, 47, 80, 97, 103, 101, 47, 82, 101, 115, 111, 117, 114, 99, 101, 115, 60, 60, 47, 88, 79, 98, 106, 101, 99, 116, 60, 60, 47, 88, 102, 49, 32, 49, 32, 48, 32, 82, 62, 62, 47, 70, 111, 110, 116, 60, 60, 47, 70, 49, 32, 50, 32, 48, 32, 82, 62, 62, 62, 62, 47, 77, 101, 100, 105, 97, 66, 111, 120, 91, 48, 32, 48, 32, 53, 57, 53, 32, 56, 52, 50, 93, 47, 82, 111, 116, 97, 116, 101, 32, 57, 48, 62, 62, 10, 101, 110, 100, 111, 98, 106, 10, 50, 32, 48, 32, 111, 98, 106, 10, 60, 60, 47, 66, 97, 115, 101, 70, 111, 110, 116, 47, 72, 101, 108, 118, 101, 116, 105, 99, 97, 47, 84, 121, 112, 101, 47, 70, 111, 110, 116, 47, 69, 110, 99, 111, 100, 105, 110, 103, 47, 87, 105, 110, 65, 110, 115, 105, 69, 110, 99, 111, 100, 105, 110, 103, 47, 83, 117, 98, 116, 121, 112, 101, 47, 84, 121, 112, 101, 49, 62, 62, 10, 101, 110, 100, 111, 98, 106, 10, 49, 32, 48, 32, 111, 98, 106, 10, 60, 60, 47, 84, 121, 112, 101, 47, 88, 79, 98, 106, 101, 99, 116, 47, 82, 101, 115, 111, 117, 114, 99, 101, 115, 60, 60, 47, 70, 111, 110, 116, 60, 60, 47, 70, 49, 32, 50, 32, 48, 32, 82, 62, 62, 62, 62, 47, 83, 117, 98, 116, 121, 112, 101, 47, 70, 111, 114, 109, 47, 66, 66, 111, 120, 91, 48, 32, 48, 32, 51, 48, 32, 49, 54, 93, 47, 77, 97, 116, 114, 105, 120, 32, 91, 49, 32, 48, 32, 48, 32, 49, 32, 48, 32, 48, 93, 47, 76, 101, 110, 103, 116, 104, 32, 52, 52, 47, 70, 111, 114, 109, 84, 121, 112, 101, 32, 49, 47, 70, 105, 108, 116, 101, 114, 47, 70, 108, 97, 116, 101, 68, 101, 99, 111, 100, 101, 62, 62, 115, 116, 114, 101, 97, 109, 10, 120, -100, 43, -28, 114, 10, -31, 50, 84, 48, 0, 66, 67, 5, 35, 32, 12, -55, -27, -46, 119, 51, 84, 48, 4, -78, -46, -72, 52, 12, 53, 67, -78, -72, 92, 67, -72, 2, -71, 0, -88, 92, 8, 34, 10, 101, 110, 100, 115, 116, 114, 101, 97, 109, 10, 101, 110, 100, 111, 98, 106, 10, 52, 32, 48, 32, 111, 98, 106, 10, 60, 60, 47, 84, 121, 112, 101, 47, 80, 97, 103, 101, 115, 47, 67, 111, 117, 110, 116, 32, 49, 47, 75, 105, 100, 115, 91, 53, 32, 48, 32, 82, 93, 62, 62, 10, 101, 110, 100, 111, 98, 106, 10, 54, 32, 48, 32, 111, 98, 106, 10, 60, 60, 47, 84, 121, 112, 101, 47, 67, 97, 116, 97, 108, 111, 103, 47, 80, 97, 103, 101, 115, 32, 52, 32, 48, 32, 82, 62, 62, 10, 101, 110, 100, 111, 98, 106, 10, 55, 32, 48, 32, 111, 98, 106, 10, 60, 60, 47, 80, 114, 111, 100, 117, 99, 101, 114, 40, 105, 84, 101, 120, 116, -82, 32, 53, 46, 53, 46, 53, 32, -87, 50, 48, 48, 48, 45, 50, 48, 49, 52, 32, 105, 84, 101, 120, 116, 32, 71, 114, 111, 117, 112, 32, 78, 86, 32, 92, 40, 65, 71, 80, 76, 45, 118, 101, 114, 115, 105, 111, 110, 92, 41, 41, 47, 77, 111, 100, 68, 97, 116, 101, 40, 68, 58, 50, 48, 49, 54, 48, 51, 50, 51, 49, 54, 51, 54, 53, 55, 43, 48, 53, 39, 51, 48, 39, 41, 47, 67, 114, 101, 97, 116, 105, 111, 110, 68, 97, 116, 101, 40, 68, 58, 50, 48, 49, 54, 48, 51, 50, 51, 49, 54, 51, 54, 53, 55, 43, 48, 53, 39, 51, 48, 39, 41, 62, 62, 10, 101, 110, 100, 111, 98, 106, 10, 120, 114, 101, 102, 10, 48, 32, 56, 10, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 32, 54, 53, 53, 51, 53, 32, 102, 32, 10, 48, 48, 48, 48, 48, 48, 48, 56, 48, 54, 32, 48, 48, 48, 48, 48, 32, 110, 32, 10, 48, 48, 48, 48, 48, 48, 48, 55, 49, 56, 32, 48, 48, 48, 48, 48, 32, 110, 32, 10, 48, 48, 48, 48, 48, 48, 48, 48, 49, 53, 32, 48, 48, 48, 48, 48, 32, 110, 32, 10, 48, 48, 48, 48, 48, 48, 49, 48, 50, 50, 32, 48, 48, 48, 48, 48, 32, 110, 32, 10, 48, 48, 48, 48, 48, 48, 48, 53, 55, 52, 32, 48, 48, 48, 48, 48, 32, 110, 32, 10, 48, 48, 48, 48, 48, 48, 49, 48, 55, 51, 32, 48, 48, 48, 48, 48, 32, 110, 32, 10, 48, 48, 48, 48, 48, 48, 49, 49, 49, 56, 32, 48, 48, 48, 48, 48, 32, 110, 32, 10, 116, 114, 97, 105, 108, 101, 114, 10, 60, 60, 47, 82, 111, 111, 116, 32, 54, 32, 48, 32, 82, 47, 73, 68, 32, 91, 60, 98, 101, 55, 48, 97, 57, 52, 52, 57, 97, 102, 57, 50, 56, 55, 97, 54, 48, 100, 99, 53, 98, 57, 97, 48, 57, 48, 101, 49, 50, 49, 54, 62, 60, 98, 101, 55, 48, 97, 57, 52, 52, 57, 97, 102, 57, 50, 56, 55, 97, 54, 48, 100, 99, 53, 98, 57, 97, 48, 57, 48, 101, 49, 50, 49, 54, 62, 93, 47, 73, 110, 102, 111, 32, 55, 32, 48, 32, 82, 47, 83, 105, 122, 101, 32, 56, 62, 62, 10, 37, 105, 84, 101, 120, 116, 45, 53, 46, 53, 46, 53, 10, 115, 116, 97, 114, 116, 120, 114, 101, 102, 10, 49, 50, 55, 53, 10, 37, 37, 69, 79, 70, 10]

A: Try out below code:
 private void saveImage(String path, final byte[] bytes) throws IOException {
        final File file = new File(path);
        final FileOutputStream fileOut = new FileOutputStream(file );
        fileOut.write(bytes);
        fileOut.flush();
        fileOut.close();
    }

A: According to the documentation of ImageIO.read(InputStream input):

Returns a BufferedImage as the result of decoding a supplied InputStream with an ImageReader chosen automatically from among those currently registered. The InputStream is wrapped in an ImageInputStream. If no registered ImageReader claims to be able to read the resulting stream, null is returned.

My best guess is that the byte array you're retrieving from the table is not from a (valid) image.

A: use it:
File file = new File(getFilesDir()+"/file.png");
FileOutputStream fos = new FileOutputStream(file);

//write your byteArray here
fos.write(byteArray);
fos.flush();
fos.close();

see this link


text:
Q: Rails: Cache multiple result sets during a session I have a Rails app that searches a static set of documents, and I need to figure out the best way to cache result sets.  I can't just use the native ActiveRecord caching.
My situation:
I'm using the will_paginate gem, and at the moment, the query is running every time the user changes pages.  Some queries are too complex for this to be responsive, so I need to cache the results, at least during an individual session.  Also, the user may have multiple tabs open, running separate queries simultaneously.  The document set is static; the size of the set is on the order of tens of thousands of documents.
Why straight-forward ActiveRecord caching won't work:
The user can search the contents of the documents, or search based on metadata restrictions (like a date range), or both.  The metadata for each document is stored in an ActiveRecord, so those criteria are applied with an ActiveRecord query.
But if they add a search term for the document content, I run that search using a separate FastCGI application, because I'm doing some specialized search logic.  So, I pass the term & the winnowed-down document list to the FastCGI application, which responds with the final result list.  Then I do another ActiveRecord query: where("id IN (?)',returnedIds)
By the way, it's these FastCGI searches that are sometimes complex enough to be unresponsive.
My thoughts:
There's the obvious-to-a-newbie approach: I can use the metadata restrictions plus the search term as a key; they're already stored in a hash.  They'd be paired up with the returnedIds array.  And this guide at RubyOnRails.org mentions the cache stores that are available.  But it's not clear to me which store is best, and I'm also assuming there's a gem that's better for this.
I found the gem memcached, but it's not clear to me whether it would work for caching the results of my FastCGI request.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get tab-completion in SublimeREPL: PowerShell? The default PowerShell is not convinient to copy/paste command output. SublimeREPL solves this problem very well; however, there's no tab-completion. This made PowerShell hard to use. Is there a way to get the tab-completion?

A: Keyboard shortcuts can differ, based on your configuration and OS.
Have you tried Alt+/?


text:
Q: Netlify Typescript express lambda I'm creating an typescript express api and I want to export it
What's the es6 equivalent for
app.use(bodyParser);
app.post('/updatestate', (req, res) => {
const newValue = updateDatabase(res.body);
  res.json(newValue);
});
module.exports.handler = serverless(app);

in the .ts lambda file?
And if the function is deployed in http://localhost:9999/.netlify/functions/abc,
the request should me made in http://localhost:9999/.netlify/functions/abc/updatestate
to update the database?
I want to use this express app to be called in a shopify webhook


text:
Q: How is this function integrated? I'm looking for some clarification on why each strip has area $(2T - |u|)du$ in the excerpt below, I'm not sure how the change of variables is done.

A: Let us deal with the case $"du>0"$. I guess it's just big triangle minus small triangle. Fix $u$. In the picture, the big triangle is the area underneath $u=t-t'$ which is
\begin{align}
\frac{1}{2}(2T-u)^2
\end{align}
since when we set $t'=-T$ the corresponding $t$ value is $t = u-T$. Likewise, we see that the small triangle is the area underneath $u+du= t-t'$ which is
\begin{align}
\frac{1}{2}(2T-u-du)^2.
\end{align}
Thus, the area of the strip is
\begin{align}
\frac{1}{2}[(2T-u)^2-(2T-u-du)^2] = \frac{1}{2}(4T-2u-du)du  = \frac{1}{2}(4T-2u)du + \text{lower order term}.
\end{align}


text:
Q: How to provide customized vibration on specific incoming calls The program functions like this: the user has a list of phone numbers, for which the cellphone could vibrate upon an incoming call only when no other system-wide application would provide vibration (such as in mute mode).  I know that this is somehow against the rules, for that an application should respect the users' settings, but the application is limited to some certain users with this need.  I have tried two ways but neither of them are satisfying:

*

*Listen to the telephony state and directly trigger the vibration service with my own pattern (with Vibrator.vibrate()).  This method is effective with no incoming calls yet randomly effective when the phone is in CALL_STATE_RINGING state and I guess it's because of the conflict with the system-wide application that actually handles the vibration upon incoming call.

*Judge whether the cellphone is vibrating upon an incoming call (with AudioManager.shouldVibrate()), and decide whether to change the vibrate settings (with AudioManager.setRingerMode() and AudioManager.setVibrateSetting()).  If the vibrate settings are changed by my application, they are to be restored once the cellphone is back to CALL_STATE_IDLE state.  This method, however, is still not functioning sometimes, without any sign of the reason.
I hope that someone could give some advice on this issue.  Comments on these two ways or other suggest are welcome.

A: You need to play with two settings in order for your phone to vibrate. The first one is the sound mode which needs to be set by using AufioManager:
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(targetSoundMode);

The second part is not properly documented and I believe this is the missing part of your code:
String VIBRATE_IN_SILENT_SETTING_NAME = "vibrate_in_silent";
Settings.System.putInt(getContentResolver(), VIBRATE_IN_SILENT_SETTING_NAME, 1);

use 1 to turn vibrate on and 0 to turn vibrate off.
to fully understand how you should work with vibrate settings and mode take a look at the following link:
http://hi-android.info/src/com/android/settings/SoundSettings.java.html


text:
Q: How can i write the JSON data shown in my Linux terminal to a JSON file using Python Guys so what this script does is: reads a file which is not proper JSON format and writes it to a proper JSON format but on my terminal. i want it to directly write the read data to a JSON file. i need it to look exactly how it looks like in my Terminal window.
Please show me an example of some sort, i really appreciate the help.----->
My terminal window with values in correct JSON format
import json
from pprint import pprint

data = []
with open(r"latency.json") as fp:
    while True:
        l= fp.readline()
        if not l:
            break

        j = json.loads( l )
        data.append( j )
pprint( data )

A: import json
import yaml

FILE_PATH = ''

with open(f'{FILE_PATH}.json', 'r') as fileRead:
     TEMP = fileRead.readlines()

for line in TEMP:
    DATA = yaml.load(line.strip(), yaml.SafeLoader)
    print(json.dumps(DATA))


text:
Q: how to align kable and ggplot in one row (side by side) in r markdown? I am trying to knit an r markdown file to pdf, but I can't align ggplot and kable in one row.
I have tried following ways:

*

*cat("\twocolumn")

*kable_styling(position = "float_right")

Below is a minimal, reproducible example
---
title: "Untitled"
output: pdf_document
classoption: landscape
---

\newpage

```{r cars, echo=FALSE, fig.width=3, fig.height=3, results="asis", message=FALSE}
library(dplyr)
library(knitr)
library(kableExtra)
library(ggplot2)

dt <- split(mtcars, f = mtcars[, "cyl"]) %>% lapply(., function(x) x[1:5, 1:4])

for (i in seq_along(dt)) {

  print(
    kable(dt[[i]]) %>% kable_styling("striped") %>% add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2))
  )

  print(
    ggplot(data = dt[[i]], aes(x = mpg, y = cyl, group = 1)) +
    geom_line(aes(y = disp), linetype = "solid", colour = "#000000")
  )

  cat("\\pagebreak")
}
```

A: Here is a possibility using the multicol latex package and two custom latex commands to circumvent the multicol latex code from being changed during the knit process:
---
title: "Untitled"
header-includes:
  - \usepackage{multicol}
  - \newcommand{\btwocol}{\begin{multicols}{2}}
  - \newcommand{\etwocol}{\end{multicols}}
output: pdf_document
classoption: landscape
---

\newpage

\btwocol

```{r cars, echo=FALSE, fig.width=3, fig.height=3, results="asis", message=FALSE}
library(dplyr)
library(knitr)
suppressWarnings(library(kableExtra))
library(ggplot2)

dt <- split(mtcars, f = mtcars[, "cyl"]) %>%
  lapply(., function(x) x[1:5, 1:4])

for (i in seq_along(dt)) {
  print(
    kable(dt[[i]]) %>%
      kable_styling("striped") %>%
      add_header_above(c(" " = 1,
                         "Group 1" = 2,
                         "Group 2" = 2))
  )

  cat("\\columnbreak")

  print(
    ggplot(data = dt[[i]], aes(x = mpg, y = cyl, group = 1)) +
      geom_line(aes(y = disp), linetype = "solid", colour = "#000000")
  )

  cat("\\pagebreak")
}
```

\etwocol

Note that I had to suppress warnings from kableExtra because the warning about being built under R v3.6.1 when I am using R v3.6.0 was enough to prevent the first page from rendering correctly.
And this produces:


text:
Q: Split a string contain dash and minus sign I have to split a string which contain dash character and minus sign.
I tried to split based on the unicode character (https://en.wikipedia.org/wiki/Hyphen#Unicode), still it considering minus sign same as dash character. How van I solve it?
Expected output
(coun)
(US)
-1
Actual output
(coun)
(US)
// actually blank line will print here but SO editor squeezing the blank line
1
 public static void main(String[] args)  {
        char dash = '\u002D';
        int i = -1;
       String a = "(country)" + dash + "(US)" + dash + i;
        Pattern p = Pattern.compile("\u002D", Pattern.LITERAL);
        String[] m = p.split(a);
        for (String s : m) {
            System.out.println(s);
        }
    }

I guess some conversion happens during the string concatenation but not sure.
 Any suggestion to solve this issue is welcome

A: The operation dash + i is evaluated as numeric addition.
I think your string should be
String a = "(country)" + dash + "(US)" + dash + "" + i;
to produce the output you described.

A: @anubhava was partially right, I was using the wrong unicode.
I should have used "\u2010". Now everything working as expected.
  public static void main(String[] args)  {
        char dash = '\u2010';
        int i = -1;
        char dashesd = '-';
        String a = "(coun)"+dash+"(US)"+dash+i;
        System.out.println(a);
        Pattern p = Pattern.compile("\u2010", Pattern.LITERAL);
       String [] m=  p.split(a);
        for (String s : m) {
            System.out.println(s);
        }


text:
Q: Liverpool has decreased By defeating Everton, Liverpool has decreased the difference to two points behind leading Manchester City. – Manchester City has now two points more than Liverpool.
I would like to ask whether the passage in bold sounds naturally in English. I am not sure how to express that in the PL Manchester City is now leading with 38 points and the second Liverpool has 36 points.

A:
Manchester City has now two points more than Liverpool.

Is fine.

Liverpool has decreased the difference to two points behind leading Manchester City.

Is Okay.  I'd use "reduced" instead of "decreased".  In addition, I'd use an appositive: "the leaders, Manchester City". And I'd think about whether I wanted to treat the teams as singular "Liverpool has..." or as plural groups "Liverpool have"  (this latter form is more common in Brit Eng than in US Eng)
As noted in comments:

Liverpool have narrowed the gap to two points behind the leaders, Man City

Is one more alternative. There are many others: "... closed to ..."; "Liverpool now need only one win to overtake Man City..."


text:
Q: How to generete charts according to the user selection using Modern UI (Metro) Charts? I'm using Modern UI (Metro) Charts in my projects. You can find the library here http://modernuicharts.codeplex.com/
I have a combobox in my GUI and it contains types of charts. What I need to do is when user selects a chart type, I want to generate that chart. I can do it manually by just editing the xaml code which generates graph. But how can I do it according to user selection? Need help as soon as possible..

A: Here you have a working exemple :
MainWindow XAML :
<Window>
    <StackPanel>
        <ComboBox Width="100" ItemsSource="{Binding ChartTypes, Mode=TwoWay}"  SelectedItem="{Binding SimpleStringProperty, Mode=TwoWay}" Text="Select Option"></ComboBox>
        <Frame NavigationUIVisibility="Hidden" x:Name="FrameTest" Source="{Binding SelectedPageChart, Mode=TwoWay}">
        </Frame>
    </StackPanel>
</Window>

MainWindow ViewModel:
public class MainViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<string> ChartTypes { get; set; }

        public MainViewModel()
        {
            ChartTypes = new ObservableCollection<string>();
            ChartTypes.Add("Pie");
            ChartTypes.Add("Doughnut");

        }

        private string _simpleStringProperty;
        public string SimpleStringProperty
        {
            get { return _simpleStringProperty; }
            set
            {
                _simpleStringProperty = value;
                if (value.Equals("Pie"))
                {
                    SelectedPageChart = new Uri("PageTest.xaml", UriKind.Relative);
                }
                if (value.Equals("Doughnut"))
                {
                    SelectedPageChart = new Uri("PageTest2.xaml", UriKind.Relative);
                }
                OnPropertyChanged("SimpleStringProperty");

            }
        }

        private Uri _selectedPageChart;
        public Uri SelectedPageChart
        {
            get { return _selectedPageChart; }
            set
            {
                _selectedPageChart = value;
                OnPropertyChanged("SelectedPageChart");
            }
        }
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

PageTest XAML :
<Page x:Class="WpfApplication1.PageTest"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:metroChart="clr-namespace:De.TorstenMandelkow.MetroChart;assembly=De.TorstenMandelkow.MetroChart" mc:Ignorable="d"
      d:DesignHeight="300" d:DesignWidth="300"
    Title="PageTest">
<Grid>

    <metroChart:PieChart
    Style="{StaticResource MinimalChartStyle}"
    ChartTitle="Minimal Pie Chart"
    SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay}" >
        <metroChart:PieChart.Series>
            <metroChart:ChartSeries
            SeriesTitle="Errors"
            DisplayMember="Category"
            ValueMember="Number"
            ItemsSource="{Binding Path=Errors}" />
        </metroChart:PieChart.Series>
    </metroChart:PieChart>

</Grid>

PageTest2 XAML:
  <Page x:Class="WpfApplication1.PageTest2"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:metroChart="clr-namespace:De.TorstenMandelkow.MetroChart;assembly=De.TorstenMandelkow.MetroChart"
      mc:Ignorable="d"
      d:DesignHeight="300" d:DesignWidth="300"
    Title="PageTest2">

    <Grid>
        <metroChart:DoughnutChart
        Style="{StaticResource MinimalChartStyle}"
        ChartTitle="Minimal Pie Chart"
        ChartSubTitle="Chart with fixed width and height"
        SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay}" >
            <metroChart:PieChart.Series>
                <metroChart:ChartSeries
                SeriesTitle="Errors"
                DisplayMember="Category"
                ValueMember="Number"
                ItemsSource="{Binding Path=Errors}" />
            </metroChart:PieChart.Series>
        </metroChart:DoughnutChart>
    </Grid>
</Page>

Pages have same viewmodel in order to display same chart:
 public class ChartViewModel
        {
                public ObservableCollection<TestClass> Errors { get; private set; }
                public ChartViewModel()
            {
                Errors = new ObservableCollection<TestClass>();
                Errors.Add(new TestClass() { Category = "Globalization", Number= 75 });
                Errors.Add(new TestClass() { Category = "Features", Number = 2 });
                Errors.Add(new TestClass() { Category = "ContentTypes", Number = 12 });
                Errors.Add(new TestClass() { Category = "Correctness", Number = 83 });
                Errors.Add(new TestClass() { Category = "Best Practices", Number = 29 });
            }

            private object selectedItem = null;
            public object SelectedItem
            {
                get
                {
                    return selectedItem;
                }
                set
                {
                    selectedItem = value;
                }
            }
        }

What I've done here is to use a frame to load dinamically pages containing desired charts. Hope it helps!


text:
Q: Time crystals: fake or revolution? This article about time crystals just appeared on the PRL website.
Viewpoint: Crystals of Time (http://physics.aps.org/articles/v5/116)
The authors (including famous Frank Wilczek) claim that some systems in their ground state are time periodic and this is related to some spontaneous breaking of some "time" symmetry. From my point of view such systems were known before this claim (persistent currents, bright solitons among them)...So I want to know what is special about these new "crystals of time"?

A: A flaw in Wilczek's argument has been pointed out in PRL 110, 118901 (2013). In short, the rotating soliton exhibited by Wilczek is not the correct ground state of the system. The true ground state can be shown to be stationary, irrespective of the flux. Impossibility of a quantum system with time-crystal-like ground-state has been further addressed in PRL 111, 040702 (2013), EPL 103, 57008 (20013), and arXiv:1410.2143.


text:
Q: Add multiple objects to an array just getting back into coding after a long break, and picking up Objective C.
I want to add multiple objects to an array.  I can do it explicitly (as below) but I'm sure there must a smarter, iterative way to do it.
NSMutableArray *a =[NSMutableArray array];

Class A *c1 = [[Class A alloc]init];
[c1 setVAlueX:5];
[c1 setValueY:3];
[a addobject:c1];

Class A *c2 = [[Class A alloc]init];
[c2 setVAlueX:5];
[c2 setValueY:3];
[a addobject:c2];

Class A *c3 = [[Class A alloc]init];
[c3 setVAlueX:5];
[c3 setValueY:3];
[a addobject:c3];

etc

A: This is nice and short:
NSArray *a = @[[A aWithX:5 Y:3], [A aWithX:5 Y:3], [A aWithX:5 Y:3]];

You'll have to implement a convenience constructor in class A:
+ (instancetype)aWithX:(int)x Y:(int)y
{
    A *a = [[self alloc] init];
    [a setValueX:x];
    [a setValueY:y];
}

A: Try this
NSMutableArray *a =[[NSMutableArray alloc] init];
NSMutableArray *b =[[NSMutableArray alloc] init];
NSMutableArray *c =[[NSMutableArray alloc] init];
NSMutableDictionary *dictA = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dictB = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dictC = [[NSMutableDictionary alloc] init];

Class A *c1 = [[Class A alloc]init];
[dictA setObject:[NSString stringWithFormat:@"5"] forKey:@"ID1"];
[dictA setObject:[NSString stringWithFormat:@"3"] forKey:@"ID1"];
//[c1 setVAlueX:5];
//[c1 setValueY:3];
[a addobject: dictA];

Class A *c2 = [[Class A alloc]init];
[dictB setObject:[NSString stringWithFormat:@"5"] forKey:@"ID1"];
[dictB setObject:[NSString stringWithFormat:@"3"] forKey:@"ID1"];
//[c2 setVAlueX:5];
//[c2 setValueY:3];
[a addobject: dictB];

Class A *c3 = [[Class A alloc]init];
[dictC setObject:[NSString stringWithFormat:@"5"] forKey:@"ID1"];
[dictC setObject:[NSString stringWithFormat:@"3"] forKey:@"ID1"];
//[c3 setVAlueX:5];
//[c3 setValueY:3];
[a addobject: dictC];


text:
Q: How to split my screen into three parts with different text content in React native I am working on a React native project, In this I have one doubt can someone please tell me how To split the screen into three parts with different content using react native.
This is what I tried so someone please tell me how to achieve another two parts
This is App.js
import React from 'react';
import {View, Text, StyleSheet} from 'react-native';

const App = props => {
  return (
    <View
      style={[
        {flex: 1, flexDirection: 'row'},
        {justifyContent: 'space-around'},
        styles.container,
      ]}>
      <Text>Mark</Text>
      <Text style={[{backgroundColor: 'green'}]}>Tom</Text>
      <Text style={[{backgroundColor: 'red'}]}>Williams</Text>
      <Text>Sara</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    marginTop: 10,
    padding: 10,
    color: '#ff0000',
  },
});

export default App;

A: You can have components inside components just like the above code, You just have to Wrap it inside another parent view, you can add any number of views like that.
Something like below, Also i put your styles in a proper way to make it clear.
const App = props => {
  return (
   <View>

     <View style={styles.container}>
      <Text>Mark</Text>
      <Text style={{backgroundColor: 'green'}}>Tom</Text>
      <Text style={{backgroundColor: 'red'}}>Williams</Text>
      <Text>Sara</Text>
    </View>

     <View style={styles.container}>
      <Text>Mark</Text>
      <Text style={{backgroundColor: 'green'}}>Tom</Text>
      <Text style={{backgroundColor: 'red'}}>Williams</Text>
      <Text>Sara</Text>
    </View>

     <View style={styles.container}>
      <Text>Mark</Text>
      <Text style={{backgroundColor: 'green'}}>Tom</Text>
      <Text style={{backgroundColor: 'red'}}>Williams</Text>
      <Text>Sara</Text>
    </View>

   </View>
  );
};

const styles = StyleSheet.create({
  container: {
    marginTop: 10,
    padding: 10,
    color: '#ff0000',
    justifyContent: 'space-around',
    flex:1
  },
});


text:
Q: Registry key as username and password I have a small requirement, currently we are migrating an application from .net 2.0 to .net 4.6.2 framework. Here the problem is application login details such as username and password are given through registry key. Now we are unable to use the same registry key file.
When we tried to run the application, its showing the below error.

Any help?

A: This may help you.
Get the values from registry and then check if they are same as username and password provided by user.
Note: Some of your values may differ
Dim username = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Foresight\identity\ASPNET_SETREG", "username", Nothing))
Dim password = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Foresight\identity\ASPNET_SETREG", "password", Nothing))


text:
Q: Prove that if $5|n^3$ then $5|n$. I have this very basic number theory type proof that is causing me some headaches and I know it is probably very simple.
I want to prove that if $5|n^3$ then $5|n$.
I have a condition that I am imposing here, one cannot use GCD function.
It is quite obvious to me that $5|n$, due to the fact that $n^3$ is $n*n*n$, and when dividing by $5$, its obvious that it must divide into one of the duplicate '$n$' here.
I am not sure if this can be done via a contrapositive proof or proof by contradiction. It seems to me that it can be done via a direct proof.
So if someone can help with a proof of this, would really appreciate it.

A: Yes, From Euclid's Lemma if $p$ is a prime number and $p$ divides $a.b$ , $a,b$ positive integers then $p|a$ or $p|b$.
Here $p = 5 | n^3$ or $p | n$ or $p|n^2$.
If $p|n$ we are done!
For the other case of $p|n^2$ then $p|n$ or $p|n$ so we are done again :)!

A: Based on the level of your question, I suppose you don't know a lot of facts about prime numbers. So this one is most easily handled by contrapositive. Suppose $5 \nmid n$, meaning that $n = 5k + j$ for some integers $k$ and $j$, with $j \in \{1, 2, 3, 4\}$ (why can I assume this??).
Then work through four cases, computing $n^3$. For example,
$$(5k + 1)^3 = 125 k^3 + 75k^2 + 15k + 1 = 5(25k^3 + 15k^2 + 3k) + 1$$
is not divisible by $5$.

A: $5$ is a prime number and $n^3=n\cdot n\cdot n$.
Thus, $n$ is divided by $5$.
If $n$ is not divided by $5$ then $n=p_1^{\alpha_1}p_2^{\alpha_2}...p_k^{\alpha_k},$ where $\alpha_i\in\mathbb N\cup\{0\}$,  $p_i$ are primes and $p_i\neq5$.
Thus, $n^3=p_1^{3\alpha_1}p_2^{3\alpha_2}...p_k^{3\alpha_k}$ is not divisible by $5$, which is a contradiction.

A: if $5|n^3$ and 5 doesn't divide n then we must have $5|n^2$
$$\frac {n³}{5}= n\left(\frac {n^2}{5}\right)$$
if $5|n^2$ and 5 doesn't divide n then we must have $5|n$
$$\frac {n^2}{5}= n\left(\frac {n}{5}\right)$$
Contradiction...
So if $5|n^3$ then $5|n$


text:
Q: Why is a guitar neck called a "neck"? Is there explanation for why a guitar neck is called a "neck"? I can understand why a guitar body is called a "body" but not the neck.

A: The "neck" of a guitar is a body metaphor.
The guitar has a "body" "neck" and "head" -- the thinner "neck" connects the smaller "head" to the larger "body," as in the human body and many animals. A guitar is like a flamingo, or a giraffe -- or a person.
In general see this definition neck:

"A narrow connecting or end part of something" (Oxford Dictionaries).

Thus:

*

*the neck of a bottle

*the neck of a waterway

*a neck of land with ocean on either side

*"our neck of the woods," an idiom for "neighborhood"/"area" that emphasizes isolation, like a community along a long stretch (neck) of forest path.

*the neck of a guitar or other instrument

Most stringed instruments have "necks" because of the design of the fretboard. Examples of exceptions include the piano and the harpsichord. Since they have necks as a family of objects, even very short and stocky stringed instruments (such as the hurdy-gurdy) can often be described as having a neck.

A: The top of the guitar is called the headstock, so logically the thing that connects the body to the head would be the neck.

A human neck is short, but necks can be long.

A: Anything that is thin compared to regions it is attached to can be called a neck. The term is used a lot in materials science and various engineering disciplines.   In fact, you call it necking when pulling on something makes it thin out as it stretches.  If the "thin connector" meaning is too much of a stretch (pun intended) from the anatomical meaning for you, just think of it as a word that has two meanings.

A: In all likelihood the origin is not English.  I can't find any references but I expect that when the first stringed instruments were created the long part that sticks out of the "body" was called the "neck" in the local language.
The word "guitar" itself derives from the Sanskrit "tar" (e.g. "sitar") and so I expect the other parts of the guitar (or similar stringed instruments) derive from Sanskrit -- or other languages like Arabic, since the lute comes from the Moorish "oud".  Over time these names may have either been translated into English, or the original word used because there was no English equivalent.
Or possibly just made up based on what they look like.  Interestingly the equivalent to guitar neck in Spanish is mástil, which means "mast" in English.
Given that the parts of the lute are similarly named, though, my guess is that the parts of the guitar in English derive from the lute, since that's a much older instrument.


text:
Q: Comparison of different types of integral transforms I was wondering

*

*why we have both Laplace transform
and Fourier transform, instead of
just one?

*why we have both generating function
and Z transform, instead of just
one?

In other words,  in each group,

*

*in what cases one transform is better
than the other?

*in what cases the two
transforms can be equally useful?

Since both transforms seem able to be converted to each other by change of variable, I am curious how people pick which tool/transform over the other to solve their problems。
Thanks and regards!

A: Let me give a very high brow example, partially inspired by Terry Tao's recent blog post.
In Euclidean spaces, the Fourier transform has the nice property that it interchanges derivation with multiplication by coordinate weights. As such it is very well suited to the analysis of differential equations. Formally speaking, by taking the Fourier transform, a differential equation can be converted to an algebraic equation. And similarly integral/algebraic inequalities can be then used to establish differential inequalities for solutions.
Another way to look at this is through the lens of spectral theory of linear operators. In many cases the Fourier transform allows one to vastly simplify the spectral analysis by reducing it to algebraic statements.
Now what if we want to do something similar on a manifold? Suppose we have a compact, closed Riemannian manifold, technically speaking we can decompose any square-integrable function $f$ using the eigenfunction decomposition relative to the Laplace-Beltrami operator corresponding to the Riemannian metric. In practice, this is not very ideal because this requires us knowing what the eigenvalues of the Laplacian are (something not easy to compute) and also what the eigenfunctions of the Laplacian are (something even harder to compute explicitly). (Basically, to decompose an arbitrary vector in an inner product space using some orthonormal basis, the usual thing to do is to describe the coefficients by studying the inner product of the arbitrary vector against the basis vectors; this is, in some sense, an informal description of the Fourier transform/series.) In Euclidean space, we know what the "eigenfunctions" are: they are just $e^{i\xi\cdot x}$, so the Fourier transform is effective. On manifolds, we don't usually know what the eigenfunctions are, and so it is a bit harder to use the Fourier transform "as it is".
However, we can massage the Laplace transform to get something more computable, yet sufficiently similar to a frequency decomposition to be useful.
A very rough description goes something like this: given $(M,g)$ a closed Riemannian manifold, with $\triangle$ its associated Laplacian. Given a smooth function $f:M\to\mathbb{R}$ and a non-negative smooth function $h:[0,\infty) \to [0,\infty)$, we define the $h$-frequency-weight of $f$ to be
$$ \mathcal{F}[f;h] = \int_0^\infty h(t) e^{t\triangle}f ~dt $$
Notice that it can be formally written as the operator $\int_0^\infty h(t) e^{t\triangle}dt = \mathcal{L}h(-\triangle)$ acting on $f$, where $\mathcal{L}h$ denotes the Laplace transform of $h$.  $e^{t\triangle}$ should, of course, be interpreted in the sense of the heat-kernel. By appropriate choices of $h$, we can make it such that $\mathcal{F}[f;h]$ behaves like a frequency localised version of $f$, kind of like the plane wave $\hat{f}(k)e^{ikx}$ in the Fourier transform.
(If you want to read more about this, you will want to consult Stein, Topics in harmonic analysis related to Littlewood-Paley theory.)

A: Unilateral Z transform and ordinary generating functions are equivalent (just take $x=1/z$). I guess the reason that some people (especially in engineering) prefer the Z transform is that the formulas look more like what they already know about the Laplace transform.

A: Yes, as the questioner notes, Fourier transform and Laplace transform are basically "the same", except in different coordinates. There is at least one further point,  that the Laplace transform set-up puts "the point at minus infinity" at 0, rather than at infinity (as does Fourier), giving a handle on behavior there, boundary values and such. In effect, Laplace tolerates functions that don't decay much at minus-infinity, by throwing in exponentials to make integrals converge. That is, it's not just the object itself (in this case, the real line, or, by exponentiating, the positive reals), but a compactification of it, to be able to talk sensibly about behavior at the boundary, e.g., at "infinity".
In fact similarly, I've always interpreted Z-transform stuff as being "basically the same as" Fourier series: the discrete double-sided list of numbers I'd interpret as Fourier coefficients of a function on a circle, that is, a periodic function. This viewpoint does explain a certain number of things about Z-transforms, but it does also neglect the refinements (which I don't know much about, except their existence) that are parallel to the distinction mentioned above between Fourier and Laplace transforms.
Even apart from boundary-value subtleties, I think the point is that there is a widely-applicable "spirit" about integral transforms (that often convert differential operators into multiplication operators), but the details "matter", in the first place, and, second, can be exploited by people who know what they're doing. Hard to give a broad prescription of the latter, I fear.


text:
Q: Using excel folder as a database for my windows form, I'm not able to reach the data I'm pretty new to programming and right now I'm trying to write a invoice maker application for the company I'm working. This is something I'm trying to implement in order to make my tasks easy.
So, there is an excel folder with item numbers and their respective net and gross weights, like this;

MTS 0001 / 24 / 26
MTS 0002 / 24 / 26
MTS 0003 / 28 / 30
MTS 0008 / 34 / 36

This info is contained in myworkbook.xlsx, Sheet2, so I've implemented a function within Sheet2.cs, like this;
public bool FindNetWeight(string item, out int weight)
    {
        for (int i = 0; i < 250; i++)
        {
            if (Cells[1, i])
            {
                return int.TryParse(Cells[3, i], out weight);
            }
        }
        weight = 0;
        return false;
    }

Now, in my Form.cs, which is cs for my windows form, I'm trying to use FindNetWeight, it shows me that I need a String argument and an integer out, but it does not let me use the function and gives me the following error;

An object reference is required for the nonstatic field, method, or property

What could be the problem here? Hopefully my description is clear enough to follow and I've gave every necessary information.

A: It looks like you are calling a non static function from a static one.
You can either make your FindNetWeight static, or create a new Instance of Sheet2.
The simple way is to make it static, so:
        public static bool FindNetWeight(string item, out int weight)
        {
         //yourcode
        }

Or, create a new instance of Sheet2:
Sheet2 mySheet = new Sheet2();
mySheet.FindNetWeight(blabla)


text:
Q: Issues on Rails 7 stylesheets I wanna know why Rails doesn't create the .css files in app/assets/stylesheets when I generate, for example, a new scaffold. The only file in app/assets/stylesheets is application.css
my file

A: Looks like it was removed here: https://github.com/rails/rails/pull/43110
Explanation in the pull request:

Modern web applications are more likely than not to use a CSS framework like Tailwind, Bootstrap, or Bulma. Rails shouldn't be generating per-model stylesheets as though we were still writing everything by hand.
Also, Sass has chosen to focus exclusively on dart-sass, which requires all manner of dependencies that Rails won't adopt by default. So decrease our reliance on Sass, and move it to being an optional extra.


text:
Q: Fill remaining height of parent after sibling hits min height Title sounds pretty tricky I guess, the thing that I want to achieve is to simply fill exactly remaining height of parent element, here's what I've got, HTML:

CSS:
#container{
    height:100%;
    width:100%;
}
#row1{
    min-height:30px;
    height:10%;
}
#row2{
    height:90%;
}

When #row1 hits min-height and stops shrinking #row2 starts getting extra height, how do I make it calculate height correctly without use of javascript (not that I can't code in it, it's just that half of my layout is made in this example and javascript would cause a lot of performance decrease).

A: You can try using calc().
jsFiddle
#row2 {
  max-height: calc(100% - 30px);
  height: 90%;
}

A: Solution with flexes:

#container{
    display: flex;
    flex-direction: column;
    height:100vh;
    width:100vw;
}

#row1{
    min-height:30px;
    height:10%;
    background:red;
}

#row2{
    flex: 1 0 auto;
    background:green;
}

row1

row2


text:
Q: Middleware Email duplicate controls bad code modeling I need to add a node.js express middleware for Emails duplicates controls, and a short and easy looking code.
This is my middleware.js file :
// -----------------------------------      MIDDLEWARE FUNCTIONS -------------------------------------------
module.exports = {
    /*
     * CHECKING FOR DUPLICATE EMAIL
     * @params
     * @return NEXT()
     * @error  Status 403s
     */
    async duplicate_email(db, req, res, next) {
        let availableEmail = await db.collection("users").findOne({ 'email': req.body.email })
        if (!availableEmail) {
            console.log(" FORBIDDEN  ")
            res.status(403).send({ errorCode: "403" })
            return
        } else {
            next() // continue the process
        }
    }
}

And this is my Register web service, in another file called usersCrud.js , I'm struggling since 3 days to make it work but no way :
/*
* Register anonymous user
* @params JSON OBJECT : {}
* @return 200
* @error  400
*/
app.post("/registerUser", middleware.duplicate_email(), function(req, res) {

    try {
        var user = new User({
            _id: null,
            prenom: req.body.prenom,
            nom: req.body.nom,
            email: req.body.email,
            password: bcrypt.hashSync(req.body.password, 10),
            role: "user",
            permissions: middleware.create_permissions("user"),
            filenames: [],
            groups: [],
            last_update: new Date(),
            img: "",
            birthday: "",
            age: "",
            job: "",
            mentra: "",
        });
        db.collection("users").insertOne(user);
        console.log("Added one user");
        res.sendStatus(200);
    } catch (e) {
        console.log(e);
        res.sendStatus(400);
    }

});

This is the error :
Error: Route.post() requires a callback function but got a [object Promise]

I have tried tons of things, like adding the db parameter, use a return function, removing all parameters, but I can' t make it work. The code would be really simplier if that thing could work like this, but I don't know if it is possible.
Maybe it is easy to solve for you .

A: Have you tried to do something like this?
app.post("/registerUser", await middleware.duplicate_email(), function(req, res)

It has to be included in the async function of course to be able to use the await keyword. As the error says, the callback is expected, but you provided a not resolved Promise.
Another thing that may work is:
app.post("/registerUser", async () => {
    const result = await middleware.duplicate_email();
    return result;
}, function(req, res) {
   // stuff
}

A: The error message tells you what's wrong, since you invoke middleware.duplicate_email() in your app.post and thus returns a promise. You need to pass the function without invoking it or define it as a factory function that returns the middleware and takes the db object as a parameter. I'd go with the second approach, which would look something like:
module.exports = {
    duplicate_email(db) {
        return async (req, res, next) => {
            let availableEmail = await db.collection("users").findOne({'email': req.body.email})
            if (!availableEmail) {
                console.log(" FORBIDDEN  ")
                res.status(403).send({errorCode: "403"})
                return
            } else {
                next() // continue the process
            }
        }
    }
}

You can then use it like this:
app.post("/registerUser", middleware.duplicate_email(db), function(req, res) { ... }


text:
Q: Qt: What is the most scalable way to iterate over a QImage? I'm aware of two methods in order to access to all the pixels in a QImage called img.
Method 1
for (int y = 0; y < img.height(); y++) {
    QRgb *line = (QRgb *) img.scanline(y);
    for (int x = 0; x < img.width(); x++) {
        // line[x] has an individual pixel
        line[x] = QColor(255, 128, 0).rgb();
    }
}

Method 2
QRgb *st = (QRgb *) img.bits();
quint64 pixelCount = img.width() * img.height();

for (quint64 p = 0; p < pixelCount; p++) {
    // st[p] has an individual pixel
    st[p] = QColor(255, 128, 0).rgb();
}

I'm keen on using the second method as it only involves one loop, but am also concerned about any possible overflows on pixelCount if processing a "big enough" image.
Question
What is the most scalable way to iterate over all pixels stored in a QImage? By scalable I mean that it will still work no matter what the image dimensions (width and height) are.
NOTE: I'm already aware there are "physical" limits in terms of memory usage. I just want to know whether both methods are capable of reaching such a limit.


text:
Q: Hibernate connect to a MySQL Cluster I am trying to connect to a MySQL cluster using Hibernate from a Tomcat/Spring application. My database connection string is:
jdbc:mysql:loadbalance://host-1,host-2/database?loadBalanceBlacklistTimeout=5000, where host-1 is like 10.xx.xx.xxx:3306.
The schema is always created just on host-2 with the InnoDB storage engine, instead of NDBCLUSTER.
I am using Hibernate 4.3.7. My MySQL JDBC driver is of 5.1.34 version.
The MySQL cluster is active-active type.


text:
Q: Video does not work on Safari and iOS I'm facing the problem that my HTML5 sample video doesn't load in Safari 11 on OSX, but works perfectly fine with Chrome and Firefox. Also, the video does not work on iOS in general (neither Safari nor Chrome).
Here is the HTML:
<video id="VideoElement" width="200" height="160" muted controls src="/static/media/fitness/theraband1.mp4"  type="video/mp4"></video>

Yet, I don't think that the html is the problem, as I cannot even
  access the video on Safari with a direct link to the file. In case you
  want to try by yourself, here is the link: Placeholder video

The app is programmed in Python 3 and Django 2. The video can neither be loaded by using the pythonanywhere page nor by my local Django development server.
I already searched Stack Overflow, but cannot not find a solution (e.g. question HTML5 Video tag not working in Safari , iPhone and iPad
 focuses much on the HTML and the video format, which I think are fine here).

A: I could finally solve the issue (in a quite inelegant way though). Instead of linking to the file on pythonanywhere, I use github as a host and it works:
Does not work:
<video id="VideoElement" width="200" height="160" controls muted src="http://USER.pythonanywhere.com/static/video.mp4"  type="video/mp4"></video>

Works:
<video id="VideoElement" width="200" height="160" controls muted src="https://github.com/USER/mysite/blob/master/static/video.mp4?raw=true"  type="video/mp4"></video>

I use exactly the same file and even the same github repository which I pull to pythonanywhere. One possible answer to that could be that pythonanywhere does not support HTTP byte-range requests (?)... well anyway, it works now...

A: Django can totally serve videos and other media types.
The problem is that django development server is not meant to be a full fledged web server. You should perhaps consider serving the site using a webserver such as nginx or apache. You don't need to host the static content somewhere else.
Example setup:

*

*Gunicorn runs the app and listens on a socket e.g.
/var/sockets/mysite.sock

*Configure the web server to serve the site.
Reference: https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html
You should also run collectstatic and configure the webserver to load static content from this location. This is not mandatory but recommended since the web server can be configured to cache this static content for you for better performance.
Hope this helps.


text:
Q: Assign new ol.View.Extent with coordnation points I'm new to GIS concepts so this might be a noob question. I'm using OpenLayers 3 for map. I want to restrict the panning to a specific area.
The code that I came across should do it but I don't know the values to assign to minx, miny, maxx, and maxy variables.
    var view = new ol.View({
        center: new ol.proj.transform([-116.284636, 43.619528], 'EPSG:4326', 'EPSG:3857'),
        zoom: 11,
        extent: [minx, miny, maxx, maxy]
    });

I've gotten the coordinates from the click evt.coordinate variable but I don't know how they correlate to the parameters of the extent.
    left top
    '0' => "-12972739.566503541"
    '1' => "5427487.630417225"

    right top
    '0' => "-12913118.684441104"
    '1' => "5426723.260134374"

    bottom right
    '0' => "-12908838.210857134"
    '1' => "5364962.141279951"

    bottom left
    '0' => "-12983440.750463465"
    '1' => "5367713.874298218"

Can someone explain how to take the coordinates and create a new extent?
Thanks

A: minx = bottomleft[0]
miny = bottomleft[1]
maxx = topright[0]
maxy = topright[1]


text:
Q: ActiveX not working on client machine I'm trying to run activex control for a simple hello world message box.
First i created the class library and i have now the dll , then i created the HTML page and called the activeX control :
<!DOCTYPE>
<html>
<head>
      <title>DemoActiveX</title>
</head>
<body>
   <OBJECT id="DemoActiveX" classid="clsid:400DCE17-4B26-4E59-9A88-AF39E2BE4A55">
</OBJECT>
    <script type="text/javascript">
        try {
            var obj = document.DemoActiveX;
            if (obj) {
                alert(obj.SayHello());
            } else {
                alert("Object is not created!");
            }
        } catch (ex) {
            alert("Some error happens, error message is: " + ex.Description);
        }
    </script>
</body>
</html>

when i tried it in my machine i used to register the dll using regasm /codebase "dll path" and it worked fine.
The problem when i tried to run in another machine, i followed the coming steps :
1) I created setup project and added the dll file.
2) I created .inf file and tried two contents which are :
[version]
signature="$CHICAGO$"
AdvancedINF=2.0
[Add.Code]
ActiveX.dll=ActiveX.dll

[ActiveX.dll]
file-win32-x86=thiscab
clsid=400DCE17-4B26-4E59-9A88-AF39E2BE4A55
FileVersion=1,0,0,0

    RegisterServer=yes
[version]
signature="$CHICAGO$"
AdvancedINF=2.0

[Setup Hooks]
install=install

[install]
run=msiexec.exe /package """%EXTRACT_DIR%\DemoActiveXSetup.msi""" /qn

3) I created .CAB file which contains the .inf and setup.exe files
4) Changed the object in HTML page to be :
<OBJECT id="DemoActiveX" classid="clsid:400DCE17-4B26-4E59-9A88-AF39E2BE4A55"
codebase="ActiveXCAB.CAB" ></OBJECT>

when i tried to open the page on the other machine a request windows opened which request to open CAB ,when i press yes nothing happened !!!!!
why it doesn't open the setup.exe or msi file ??
BTW when i installed manually the setup file the activeX worked !

A: I solved the problem :)
The problem was :
1) I used to put msi file only or setup.exe in CAB file but i must put both msi and setup.exe and refer to setup.exe in inf file
2) inf file format was wrong , the correc one is :
 [version]
 signature="$CHICAGO$"
 AdvancedINF=2.0

 [Add.Code]
 setup.exe=setup.exe

 [setup.exe]
 file-win32-x86=thiscab
 clsid={415D09B9-3C9F-43F4-BB5C-C056263EF270}
 FileVersion=1,0,0,0

 [Setup Hooks]
 RunSetup=RunSetup

 [RunSetup]
 run="%EXTRACT_DIR%\setup.exe"

Good Luck :)


text:
Q: Constant unseen by compiler I have a problem with code below. It throws me errors which tells me nothing.
I have a file memory.h where i have:
#ifndef BLOCK_SIZE
#define BLOCK_SIZE 8
#endif

I have also configuration.ac file with fragment as below:
AC_ARG_WITH([block-size],
    [AS_HELP_STRING([--with-block-size],["Define blocksize to initialize with. Default value: 8]")],
        [bsize="$withval"],
        [])

if test ! -z "${bsize}"; then
        if test  "${bsize}" > 0 ; then
                AC_DEFINE_UNQUOTED([BLOCK_SIZE], [$b_size], [Defining block size in bytes])
        else
                AC_DEFINE_UNQUOTED([BLOCK_SIZE], [8], [Default block size : 8B])
        fi
fi

Later i used command ./configure --with-block-size=16 --with-allocator=STR_MIN to finalize making makefile. But now ehen i use make command i get a buch of errors:
memory.c: In function 'initialize':
memory.c:15:59: error: expected expression before ')' token
memory.c: In function 'allocate':
memory.c:26:41: error: expected expression before ')' token
memory.c:53:56: error: expected expression before ';' token
memory.c: In function 'defragment':
memory.c:140:73: error: expected expression before ')' token
memory.c: In function 'diagnoze':
memory.c:174:183: error: expected expression before ',' token

All lines with error looks like this:
mem -> unused_list -> address = malloc(count * BLOCK_SIZE);
new -> address = space -> address + size * BLOCK_SIZE;

It looks like compiler do not see BLOCK_SIZE at all. Now there is just a question why.
Knowing me I have probably eat latter or two in this code. But i can't find it and have no clue what more can cause this problem. All other commands of automake which i used earlier (including ./con..) didn't throw any errors.

A: As stupid mistake as I thought. I just had to change line:
AC_DEFINE_UNQUOTED([BLOCK_SIZE], [$bsize], [Defining block size in bytes])

There was no missing quotes as someone suggested, but just simple _ to much.
Thanks for help anyways.


text:
Q: What is best and recommended way of using constants in Angular 5 I have a Angular 5 application where I want to use

*

*a. application level constants

*b. Module level constants

I know we can use DI (Injection Token), or Services to use constants, or create a global.ts file with all constants and then access them anywhere.
I wanted to understand what is the best and recommended way of doing this.

A: How i would do it is just create two different namespace
- ApplicationConstant
- ModuleContants
Then exports the individuals Constant from the namespace eg:
export namespace ApplicationConstant {
  export const APP_NAME = 'Todo_list';
}

Do not over complicate it, as they are just constant, no need to introduce DI.
Always try to be independent on the framework unless there is a real need.
DI is good when you need to mock..etc, but for constant, they are usually just values.
If you use DI (Service), you will have to add it inside the app-module..etc then inject that in other places. This is added complexity with no real benefits.
The only benefits I can see if you you use the DI (Service) might be if you want to LazyLoad by modules, however constants are usually really lightweight.
Your global.ts is fine, but always encapsulates it in a namespace as my example above, so when you access it, you know where its coming from eg: ApplicationConstant.APP_NAME.


text:
Q: 'str' object cannot be interpreted as an integer in regex import re

def regex(tex):
  text = re.compile('[А-ЯӨҮа-яөү0-9/s]')
  tex = text.sub("\n+", '\n', tex)
  tex = text.sub('\s+', ' ', tex)
  tex = text.sub("\s+($)", '', tex)
  stopword = ['ч','л','аа', 'ээ', 'оо', 'өө', 'даа', 'дээ', 'дөө', 'доо']
  text = ' '.join([word for word in text.split() if word not in stopword])
  return text

text = "Намайг Анужин \n\n\n гэдэг  дээ shushus "
print(text)
print(regex(text))

Please tell me what the error is and how to fix it.

A: The error is due to the text.sub("\n+", '\n', tex) line where text is a Pattern and Pattern.sub singature is Pattern.sub(repl, string, count=0). As you see, the "\n+" is a repl, '\n' is a string and tex is a count (an integer!).
Also, note that running sub("\n+", '\n', tex) before sub('\s+', ' ', tex) makes little sense since the \s+ will match the \ns and will still replace them with a single space.
The sub("\s+$", '', tex) is also redundant since later, you split and re-join the string with whitespace, it will automatically strip whitespace on the left and right.
At some moment in the code later, you mixed tex and text, do not name separate variables almost identically, it is easy to mix them up.
You need to rearrange the code in the following way to clean the input string:
import re

invalid_char_rx = re.compile('[^А-ЯӨҮа-яөү0-9\s]+')
stopword = ['ч','л','аа', 'ээ', 'оо', 'өө', 'даа', 'дээ', 'дөө', 'доо']

def regex(s):
  s = invalid_char_rx.sub(' ', s)
  s = ' '.join([word for word in s.split() if word not in stopword])
  return s

text = "Намайг Анужин \n\n\n гэдэг  дээ shushus "
print(f"'{text}'")
print(f"'{regex(text)}'") # => 'Намайг Анужин гэдэг'

See the Python demo.


text:
Q: Angular 2 Http delete send json in body Could Angular2 send json body via http method delete ?
I try it and it said error
ORIGINAL EXCEPTION: options.search.clone is not a function

service.ts
deletetag(tagid: number): Observable<any> {

    let body = JSON.stringify(
        {
            "token": "test",
            "content": {
                "tagId": tagid
            }
        }
    );

    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.delete("http://localhost:8080/backend/tag", body, options)
        .map(res => this.extractData(res))
        .catch(this.handleError);
}

component.ts
this.tagService.deletetag(1)
   .subscribe(
      data => { },
      error => { },
      () => { }
   );

A: As per RequestOptionsArgs interface and Http delete function argument, i think you need to send delete request as below :
deletetag(tagid: number): Observable<any> {

  let body = JSON.stringify(
      {
        "token": "test",
        "content": {
        "tagId": tagid
      }
    }
  );
  let headers = new Headers({ 'Content-Type': 'application/json' });
  let options = new RequestOptions({
    headers: headers,
    body : body
  });

  return this.http.delete("http://localhost:8080/backend/tag", options)
        .map(res => this.extractData(res))
        .catch(this.handleError);
}


text:
Q: Why doesn't the directory I created appear in both Gallery and Google Photos? In my CameraFragment.java I have a library called nataro1 CameraView which basically allows me to open up the device's camera and take a photo. That photo is saved in a directory created by the app, called "Feel". Everything works fine, the directory is created and the photos are stored there. The problem is, whenever I try to see them in the Gallery or in Google Photos, I can't. There is no directory and no photos. If I want to see them I must go to "Settings/Storage/InternalStorage/Explore/Pictures". Why can't I see the directory in Gallery and in Google Photos?
This is the code I have:
 private void saveImage(Bitmap finalBitmap, String image_name) {

    final String appDirectoryName = "/Feel"; // Nome da pasta onde irão ser guardadas as fotos
    String root = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES).toString() + appDirectoryName; // Caminho do root da galeria do telemóvel
    File myDir = new File(root); // Declara um novo ficheiro com o nome do root + "/Feel"
    if(!myDir.exists()){ // Caso o diretório ainda não exista...
        myDir.mkdirs(); // ... cria um com esse nome
    }
    String fname = "Image" + image_name + ".jpg"; // Concatena o nome da imagem com a extensão ".JPG"
    File file = new File(myDir, fname); // Declara um novo ficheiro com o caminho e o nome da imagem
    Log.i("LOAD", root + fname);
    try { // Caso dê erro...
        FileOutputStream out = new FileOutputStream(file); // Declara um OutputStream
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); // Cria e comprime o ficheiro
        out.flush();
        out.close(); // Fecha o output
    } catch (Exception e) { // ... não dá crash
        e.printStackTrace();
    }

}

A: You need to add some extra code to view your picture in the gallery.
// Mention your file
String filePath=imageFile.getPath();

// add this code to view the picture in gallery
MediaScannerConnection.scanFile(this, new String[] { filePath }, new String[] { "image/jpeg" }, null);

A: private fun notifyGallery(photo: File) {

        // the listner inside mediascanner runs on binder thread that why handler post method to execute inside ui thread for showing toast and notidication
        MediaScannerConnection.scanFile(context, arrayOf(photo.absolutePath), null) { path, uri ->
            Handler(context.mainLooper).post({
                Toast.makeText(context, "${photo.name} saved to gallery", Toast.LENGTH_SHORT).show()
            })
        }
}


text:
Q: SFML C++ Excepción al eliminar sf::SoundBuffer Si intento crear un sf::SoundBuffer y eliminarlo con su destructor resulta en una excepcion.
Esto llega a ser estresante hasta el punto de que el siguiente codigo este bugeado.
#include <SFML\Audio.hpp>

int main()
{
    sf::SoundBuffer SomeSoundBuffer;

    SomeSoundBuffer.~SoundBuffer();

    return 0;
}

Buscando encontré que tal ves SFML limpie mal la memoria de OpenAL y que al llamar a su destructor, éste no se elimina en el momento, sino que en el próximo Tick.
Incapaz de encontrar información sobre ello lo deje como una posible teoria.
Mi pregunta es simplemente como eliminar el sf::SoundBuffer sin causar un error.

A: En tu código hay un problema y es que se invoca dos veces el destructor:

*

*La primera vez se corresponde con la llamada explícita que has añadido al main

*La segunda cuando finaliza el programa (la ejecución abandona la instrucción main y ello provoca que se llame al destructor de todos los objetos cuyo ámbito sea la propia función main).

¿Y por qué llamar dos veces al destructor provoca el fallo del programa?
Puede ser algo tan tonto con un borrado doble:
Es bastante probable que la clase sf::SoundBuffer haga uso de memoria dinámica, luego no sería dificil encontrar una implementación similar a la mostrada en el ejemplo siguiente:
class Test
{
  int* ptr;

public:
  Test()
    : ptr{new int(5)}
  { }

  ~Test()
  {
    delete ptr;
  }
};

Aquí tienes una clase de lo más tonta que solo implementa un constructor y un destructor... Y al usarla correctamente no da ningún problema:
int main()
{
  Test t;
}

Sin embargo basta con llamar explícitamente al destructor para que esa clase tan simplona empiece a dar problemas:
int main()
{
  Test t;
  t.~Test();
}

Lo que sucede aquí es que la llamada explícita al destructor libera la memoria asignada a ptr y, posteriormente, se ejecuta un segundo delete sobre el mismo puntero y esto provoca un comportamiento indefinido que, generalmente, se traduce en que el sistema operativo mata tu aplicación para que no corrompa la memoria de otros procesos.
El error se puede subsanar facilmente haciendo que ptr apunte a 0 después del delete:
~Test()
{
  delete ptr;
  ptr = nullptr; /* o, si no compilas con C++11, tambien vale 0 o NULL */
}

Ahora el error ya no se reproducirá porque un delete de un puntero que apunta a 0 no tiene consecuencias... sin embargo siempre será más limpio y sano para tu código evitar hacer cosas raras y dejar al compilador la responsabilidad de ejecutar las funciones especiales (constructores y destructores generalmente).
Pero claro, es mucho más sencillo no hacer cosas raras y dejar

A:
El siguiente código este bugeado

El problema no está en el código si no en tu comprensión del lenguaje C++.

Los objetos de C++ no requieren una llamada explícita a su destructor para ser destruidos1 pues se destruyen automáticamente al finalizar su ciclo de vida.
Así pues llamando al destructor de manera explícita provocas dos destrucciones del objeto creado:

*

*Al llamar al destructor.

*Al finalizar su ciclo de vida.

Según el apartado 12.4 del estándar (traducción y resaltado míos) hacer lo que has hecho deriva en comportamiento indefinido:

12.4 Destructores.

*Cuando se invoca el destructor de un objeto, el objeto ya no existe; el comportamiento no está definido si el destructor se invoca para un objeto cuyo ciclo de vida ha finalizado [Ejemplo: si el destructor de un objeto automático es explícitamente invocado, y se abandona el bloque de manera que se invoque implícitamente la destrucción del objeto, el comportamiento es indefinido — fin del ejemplo ]

El comportamiento indefinido puede hacer que tu código se comporte de manera errática o que aparentemente no suceda nada (lee este hilo para más detalles).
Así pues, el código no tiene ningún bug, se está comportando como se espera. El destructor no debe ser llamado explícitamente porque será llamado implícitamente al finalizar el ciclo de vida de la variable automática, ¿tal vez querías en realidad hacer uso de memoria dinámica?
#include <SFML\Audio.hpp>

int main()
{
    auto SomeSoundBuffer = new sf::SoundBuffer; // <--- crear

    delete SomeSoundBuffer; // <--- destruir explícitamente

    return 0;
}

*

*La llamada explícita a destructor es requerida en muy pocos casos y ninguno de los casos es aplicable al código que has mostrado.


text:
Q: Retrieve JSON Parameter with AJAX HTML code:
<form method="post" action="process.php">
    <button id="process" type="submit">Button</button>
</form>

JavaScript code:

My process.php page prints the following code:
{
  "status" : "success",
  "data" : {
    "parameter1" : "hello",
    "parameter2" : 42,
    "parameter3" : "hello world",
    "parameter4" : "hello again"
  }
}

The problem is that I get "undefined" while calling AJAX. Why?

A: Try this;
$form.before("
"+responseJson.data.parameter3+"
");

you forget data to access your parameter3 value


text:
Q: Handling async events in javascript classes / libs without bind so this is my code
function dl(name){
 this.name=name;
 this.getInfo();
};
dl.prototype={
 getInfo:function(){
  this.x=new XMLHttpRequest;
  this.x.open('GET',this.name);
  this.bind=this.setInfo.bind(this);
  this.x.addEventListener('load',this.bind,false);
  this.x.send();
 },
 setInfo:function(){
  this.info=this.x.response;
  this.x.removeEventListener('load',this.bind,false);
  delete this.bind;
  delete this.x;
  this.insertDOM();
 }
};

I use function dl(){} approach because i want to have access to everything with this.
I use prototype because when i create many new dl(SOMEURL) it won't touch the memory.
But yeah as it has many xhr2 functions inside i need to find the best way to return everything correctly.
So using xhr2 normally is wonderfull...
function ajax(a,b,c){ //url,function,placeholder
 c=new XMLHttpRequest;c.open('GET',a);c.onload=b;c.send();
}
//example onload function
function b(){ //don't even need event....
 console.log(this.response)
}

Good: i pass only the function reference (no arguments,no strange that,me vars..)
Bad: in a class i loose the this pointer to my class
so i started with defining the xhr object inside my class
this.x=new XMLHttpRequest;

and used bind to pass this on my next function this.setInfo
but to remove the eventlistener later i need to define a new variable that contains the binded function.
this.bind=this.setInfo.bind(this);

and i really hate that.(i'm trying to use as many variables as possible and using low memory)
i don't even know if this really removes the event.
other solution i'm thinking of is to refer the this to the xhr2 object.
function dl(name){
 this.name=name;
 this.getInfo(this.name);
};
dl.prototype={
 getInfo:function(){
  var x=new XMLHttpRequest;
  x.that=this;
  x.open('GET',this.name);
  x.addEventListener('load',this.setInfo,false);
  x.send();
 },
 setInfo:function(){
  this.that.info=this.response;
  this.removeEventListener('load',this.setInfo,false);
  this.that.insertDOM();
  delete this.that;
 }
};

A. is this.that only a reference or does it fill the memory?
i need to be shure that after each of this functions i delete/clear every var that i don't need anymore to help the garbage collector.
B. Are there any better solutions in writing this type of javascript class??
ps.:is there a more elegant wayto init the first function inside dl?

What is this class for??
it's a download manager for chrome
How it works??
i put a download link into a input field
the class adds a new dl(SOMEURL) to an array
retrieves the file info with a php cUrl script.
stores the file info inside the class
and executes another xhr with retrieves the first chunk of the file based on it's size.
the chunk will be appended to a window.webkitrequestfilesystem file previously created.
then it continues to loop over xhr requests until all chunks are downloaded and appended to the filesystem.
Saving the file offset status into window.LocalStorage gives me the opportunity to resume downloads later.

A: Ok, i've got the script to work, but I changed a few things. Firstly, I took put x.that and replaced it with a local variable (instance) that can be used inside onreadystatechange events. Secondly I added an onreadystatechange event, allows you to run a function when the ajax request loads, I  also modified the event listeners so that they would work, but I recommend using the onreadystatechange. Thirdly, I added a few things to test and the code works on Chrome. Finally, I changed setInfo so that it would take the response of the ajax request as a parameter. I think that's everything I did, so heres the code:
function dl(name){
    this.name = name;
    this.getInfo(this.name);
};
dl.prototype = {
    getInfo:function(){
        var instance = this;
        var x = new XMLHttpRequest();
        x.open('GET', this.name, false);

        // onreadystatechange event
        x.onreadystatechange = function(){
            if(x.readyState == 4){
                if(x.status == 200){
                    instance.setInfo(x.responseText);
                } else {
                    /*
                        there was a network failure
                        (File Not Found, Internal Server Error ...)
                    */
                }
            }
        }

        // if you really want to use event the listeners you had previously:
        this.request = x;
        x.addEventListener('load', function(){
            instance.setInfo(x.responseText);
        } ,false);

        x.send();
    },
    setInfo:function(response){
        this.info = response;

        // if you used the event listeners
        this.request.removeEventListener('load', function(){
            instance.setInfo(x.responseText);
        } ,false);
        delete this.request;

        // this.insertDOM();
        // I just added this for testing purposes only
        document.body.innerHTML = this.info;
    }
};

// added for testing
window.addEventListener("DOMContentLoaded", function(){
    var dlTest = new dl("filetoget")
}, false);

Hope this helps.

A: Here is the new code:
function dl(name, callback) {
    this.name = name;
    this.callback = callback;
    this.getInfo();
}
dl.prototype = {

 getInfo:function(){
  var x=new XMLHttpRequest;
  x.that=this;
  x.open('GET',this.name,false);
  x.addEventListener('load',this.setInfo,false);
  x.send();
 },
 setInfo:function(){
  this.that.info=this.response;
  this.removeEventListener('load',this.setInfo,false);
  //this.that.insertDOM();
  // when you need to refer back
     this.that.callback(this.responseText);

  delete this.that;
 }
}

function call() {
    var a = 1;
    var b = 2;

    new dl("filetoget", function (response) {
        console.log(a + b);
        console.log(response);
    });
}

call();


text:
Q: Preserve data through memory cleaners I have an issue with the preserving bundled data of an Activity.
Certain memory cleaners (such as clean master), as well as the GC of certain devices seem to remove all of the data, and bundled data, from an activity and corresponding ViewModel causing the activity to crash.
My question is: is there a way to hold to the data (usually passed via bundle) required for the activity to load?
I have tried solutions to try and preserve the data via onSavedInstanceState
@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putInt(BUNDLE_ARGUMENT_CUSTOMER_ID, this.mViewModel.getCustomer().getId());

    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    if (savedInstanceState != null) {
        this.mViewModel.setCustomer(new Customer(savedInstanceState.getInt(BUNDLE_ARGUMENT_CUSTOMER_ID, -1)));
    }
}

As well as rely on ViewModel to keep the data alive, none of which have worked.
However, the only solution so far that actually works is to save data to a local storage (either using SharedPreference or InternalStorage), which open certain other issues of additional management of data.
Even after saving the data, the effect of the application is as if an crash occurred when navigation through the back stack.

A: Unfortunately you will HAVE to use some form of more permanent storage like a file or SQLite as the whole point of those "cleaners" is to reclaim resources being used.
You can optionally store the data in a cloud provider(like firebase) and request it. firebase gives you a gb of data to store on the free tier. It is overhead though, I highly recommend just using a file or SQLite. it's a best practice you will need to adopt
In any case it is not your fault that the user is putting these cleaners on their phones, you just have to manage your app's lifecycle gracefully
One option is to disable history so user cannot navigate the back stack. another option is to always ensure data is loaded in memory before trying to display it and displaying an error message in case data is getting erased prematurely. you can detect other applications installed on the user's device and inform them that usage of those applications will crash YOUR app(but I don't recommend this as it adds permissions overhead that will decrease number of people who're willing to download your app)


text:
Q: how to sort django templates folder i made  my first blog templates in order blog/templates/sth.html becuz it didnt find in this order blog/templates/blog/sth.html but now i made a new app and made it in order users/templates/registiration/login.html and got this error
Using engine django:
django.template.loaders.app_directories.Loader: C:\Users\NDarksoul\.virtualenvs\blog-PCvr0qFP\lib\site-packages\django\contrib\admin\templates\blog\base.html (Source does not exist)

django.template.loaders.app_directories.Loader: C:\Users\NDarksoul\.virtualenvs\blog-PCvr0qFP\lib\site-packages\django\contrib\auth\templates\blog\base.html (Source does not exist)

django.template.loaders.app_directories.Loader: C:\projects\rightnow\blog\blog\templates\blog\base.html (Source does not exist)

django.template.loaders.app_directories.Loader: C:\projects\rightnow\blog\users\templates\blog\base.html (Source does not exist)

can u hlp me pls how to fix this mess

A: In the main templates folder, all folders for each app
then add in these folder their templates depend on the app
and the main template in templates folder.


text:
Q: What UWP API raises a purchase event? I am creating a UWP video editor application centered on the MediaComposition class and I want the user to play with and test it for as long as they want as they would be granted an unlimited free trial upon downloading and installing it. (The app will be made available through the Windows Store.) However, any videos produced will have a watermark. The watermark will be removed as soon as they purchase the app.
What API will raise a purchase event to help me accomplish this?

A: You may use the StoreContext.OfflineLicensesChanged event from the Windows.Services.Store to detect changes in your app's Microsoft Store license:

StoreContext.OfflineLicensesChanged Event
Raised when the status of the app's license changes (for example, the trial period has expired or the user has purchased the full version of the app).
public event TypedEventHandler<StoreContext,object> OfflineLicensesChanged;

When this event is raised, you can get the latest app license from the Microsoft Store by calling the GetAppLicenseAsync method. The StoreAppLicense object returned by this method also contains the latest add-on licenses for the app in the AddOnLicenses property.

However, note the following version restriction:

The Windows.Services.Store namespace was introduced in Windows 10, version 1607, and it can only be used in projects that target Windows 10 Anniversary Edition (10.0; Build 14393) or a later release in Visual Studio. If your app targets an earlier version of Windows 10, you must use the Windows.ApplicationModel.Store namespace instead of the Windows.Services.Store namespace. For more information, see this article.

On earlier versions versions, the equivalent event is documented to be the LicenseChanged event in the Windows.ApplicationModel.Store namespace, which has the following additional remark:

LicenseChanged events aren't always immediate. If you've registered for the event, the event should fire within an hour; if not, it should occur within 6 hours. Generally, it's recommended to wait up to 6 hours when testing with CurrentApp, knowing that it will most likely take less time if the app has registered the event.

See also:

*

*Implement a trial version of your app

*In-app purchases and trials.

*Exclude or limit features in a trial version


text:
Q: Centering plots The two plots look like they have been "flushed left". How can I make them appear in the center or centered?

\documentclass[tikz,border=7pt]{standalone}
\usetikzlibrary{positioning,arrows.meta,shadows.blur}
\usepackage{graphicx}
\usepackage{subcaption}
\begin{document}

\begin{figure}
    \begin{center}

    \begin{subfigure}{.6\textwidth}
        \centering
        \includegraphics[width=.9\linewidth]{insesgado_svd_100k}
        \caption{Error }
        \label{}
    \end{subfigure}%
    \begin{subfigure}{.6\textwidth}
        \centering
        \includegraphics[width=.9\linewidth]{sesgado_svd_1M_matlab}
        \caption{Error}
        \label{}
    \end{subfigure}
    \caption{ $\Lambda$ f $F$.}
    \end{center}
\end{figure}
\end{document}

A: Probably you looking for something like this:

(red lines indicate text borders)
\documentclass{article}
\usepackage[demo]{graphicx}
\usepackage{subcaption}

%---------------- show page layout. don't use in a real document!
\usepackage{showframe}
\renewcommand\ShowFrameLinethickness{0.15pt}
\renewcommand*\ShowFrameColor{\color{red}}

\begin{document}
    \begin{figure}
    \centering
\begin{subfigure}{.45\textwidth}
\includegraphics[width=\linewidth]{insesgado_svd_100k}
    \caption{Error }
    \label{fig:mysubfig1}
\end{subfigure}\hfil
\begin{subfigure}{.45\textwidth}
\includegraphics[width=\linewidth]{sesgado_svd_1M_matlab}
    \caption{Error}
    \label{fig:mysubfig2}
\end{subfigure}
    \caption{ $\Lambda$ f $F$.}
    \label{fig:myfig}
    \end{figure}
\end{document}

From comparison of the mine and yours MWE follows:

*

*Used is article document class since in standalone class you can't use floats (without option varwidth) and in it you can't see, if the image are horizontal centered in text. Shortly, your MWE doesn't work.

*In the figure environment is not used \begin{center} ... \end{center} environment since it insert additional vertical space around images. Instead of it is used \centering.

*Sum of the subfigures widths should be equal or better smaller than \textwidth. Otherwise they will spill out on the right side of text area (or even page).

*Code is shorter, if you define images widths with with of subfigure, i.e. \includegraphics[width=\linewidth]{....}. In this case you can omit command \centering inside subfigures.


text:
Q: Shorter proof for this? if $G = T + N$ and $T = N * t$, where $t$ is a $\%$, find $T$ if the only given values are $G$ and $t$.
I already has a formula but it needs to compute for $N$ first which is lengthy, is there a shorter formula without computing for $N$ first?
Please help. Thanks in Advance.

A: $$G=N\cdot t+N=N\cdot(1+t)$$
$$N=\frac{G}{1+t}$$
$$T=\frac{G\cdot t}{1+t}$$


text:
Q: jQuery class selector performance (confused) So is $('table.selectable td.capable input:text') preferable to $('table.selectable td input:text')? In other words, does specifying a class speed up or slow down the selection (assuming it isn't absolutely required in this scenario)?

A: I did not check the Sizzle implementation, but in the best case, td would map to something like getElementsByTagName() and .capable to something like getElementsByClassName(), if available. So both would be comparable in terms of speed.
However, there is no getElementsByTagNameAndClassName() method as far as I know, so resolving td.capable probably requires an additional filtering pass after the DOM call. So, I'm quite inclined to think it would be slower.
Naturally, a benchmark would tell for sure.

A: So I did some benchmarking with firebug, and in the particular example I listed in the question, the latter (without the td class specifier) is faster.

A: Depends on the context.
Generally, the more sub-checks that need to be made, the slower it will be, as each takes time.  The point is, they are obviously not necessarily the same results.  One is a sub-set of the other.
For the most part, aim to have the minimal number of selectors required to target the specific set you require.  Also bare in mind that some selectors perform far better (due to browser method availability) than others.  ID selectors #id and in modern browsers tag selectors, are far quicker than class searches .class, which require iterative string analysis of the .className parameter, or indeed attribute based searching, which is much the same usually.
If in doubt, perform metrics.


text:
Q: Unable to find the Element on the pop up using Selenium Webdriver with C# namespace ABC.ABCManager.UIAutomation.Authorization
{
[TestClass]
public class VerifyCreateUsersSendInvite : BaseTest
{
    [TestMethod]
    public void VerifySendAnInviteLink()
    {
        Actions actions = new Actions(driver);
        selectAndClickOnCustomerName();
        Thread.Sleep(3000);
        try
        {
            //Click Send an Invite link

            var LinksOnOverview = driver.FindElements(By.CssSelector(".popupFrameLink.summary-tool-link"));
            LinksOnOverview[2].Click();

            //Verification point to see "Send an Invite" link has opened by checking "TextName" textbox is present or not by using CSS selector
            if (IsElementPresent(By.CssSelector("#FirstName")))
            {
                ExtentManager.verifySafely(driver.FindElement(By.CssSelector("#FirstName")).TagName, "input", "VerifySendAnInviteLink", "link has opened ", driver);
                Console.WriteLine("'Send an Invite' link has opened ");
            }

        }
        catch (Exception ex)
        {
            driver.Close();
        }
    }
}
}

In above code,I am clicking link "Send an Invitation" and after that, I am getting exception "Element not found" on the line :
if (IsElementPresent(By.CssSelector("#FirstName")))
.... I am inspecting element by CssSelector. I tried xpath then also same exception I am getting. I am unable to find any other element(including first name) on that pop up.Please suggest me solution. Thanks in advance!!!

A: Probably you should change frame on which you looking for elements
ReadOnlyCollection<string> windowHandles = driver.WindowHandles;
driver.SwitchTo().Window(windowHandles[1]);
// ELEMENTS on Second frame (window)
driver.SwitchTo().Window(windowHandles[0]);
// ELEMENTS on First Frame

A: try
            {
                List<IWebElement> frames = new List<IWebElement>(driver.FindElements(By.TagName("iframe")));

                driver.SwitchTo().Frame(1);
                //Verification point to see "Send an Invite" link has opened by checking Text Name textbox is present or not by using CSS selector
                if (IsElementPresent(By.CssSelector("#FirstName")))
                {
                    ExtentManager.verifySafely(driver.FindElement(By.CssSelector("#FirstName")).TagName, "input", "VerifySendAnInviteLink", "link has opened ", driver);
                    Console.WriteLine("'Send an Invite' link has opened ");
                }


text:
Q: Lerna and Jenkins build strategy first of all sorry if this is the wrong place for the question!
A team I work with have recently adopted lerna as a tool to manage multiple javascript / node packages in one repository. However we are struggling to identify a good way to build these multiple packages with Jenkins. When we push code to the remote (git) a webhook is triggered that causes Jenkins to start building code (typical process). This triggers the job for all of the packages in the repository even if only one package has been changed.
Our current thoughts are man in the middle the webhook and based on calling GitHub API choose what packages to build or find something in Jenkins that lets us do path based checkouts (struggling with this).
I've had a good search and haven't really been able to find anything that works yet. Any advice would be massively appreciated.

A: It is possible in Jenkins to conditionally run a step when a changeset contains one or more files matching a given pattern (documentation)
E.g.,
stage('build project') {
  when { changeset "packages/project-a/**/*" }

  steps {
    echo "Project A changed..."
  }
}


text:
Q: Laravel - hacer un pluck de todas las relaciones a partir de una relacion polimorfica tengo un model label: que son etiquetas de otros modelos, en mi caso : prodcutos y servicios.
Ejemplo:
Tengo la etiqueta : barato.
En mi relacion polimorfica digamos que el label barato me trae 2 productos y 1 servicio, es decir, hay 2 productos que tienen la etiqueta barato y un producto.
Mi quey seria la siguiente:
$labels = Label::where('name','barato'])->with(['services','products'])->get();

Vale, en este punto tengo una coleccion de etiquetas:
Como puedo hacer para obtener con pluck un array conformado por todos los modelos relacionados con este polimorfismo? es decir un array ya formado con servicios y productos (sin indice n=>[]) para devolverlo en json ya que lo que me interesa es el resultado no las etiquetas.

Pretendo obtener un array cargado de todas las relaciones con las etiquetas obtenidas en la relacion, algo como array_merge del conjunto de relaciones, de esto:
  #relations: array:2 [▼
    "services" => Illuminate\Database\Eloquent\Collection {#608 ▼
      #items: array:1 [▶]
    }
    "products" => Illuminate\Database\Eloquent\Collection {#1227 ▼
      #items: array:1 [▶]
    }
  ]

Como si recorriera cada tipo de relacion  y por cada una lo recorriera de nuevo para obtener un array de un nivel con todas ellas.
He probado con esto:
$plucked = $labels->pluck('services','products')

Pero no funciona como deberia.


text:
Q: DELL PowerEdge T110 - Unable to connect to Postgres Server i've just bought a DELL PowerEdge T110 II with Microsoft Windows Small Business Server 2011.
I've installed PostgreSQL (latest version 9.1) and i've made the pg_hba configuration for access the DB from other LAN PC.
Here is my problem, if i try to connect to PGServer with PGAdmin from LAN PC quickly after the bootup of the server i can connect without problems.
After few minutes (2-3) i cannot connect anymore to the PGServer. If i connect to the server with PGAdmin local there is no problem and only after that i can successfully connect to the PGServer w/o problems.
Another solution is to remove the LAN Cable from the server and plug-in again. In this way the PGAdmin from other LAN PC gets back to work.
Here the message i get

Server doesn't listen
  The server doesn't accept connections: the connection library reports
  could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "192.168.4.10" and accepting TCP/IP connections on port 5432?

Is some sort of standby of the Postgres process?
(I know my english is not wonderful, if you don't understand something, ask and i'll explain better)
Edit:  The same thing happens with remote desktop so this does not seem to be a PostgreSQL issue.


text:
Q: Datetimepicker form validation I've been trying to create a validation for my form. I've been looking around on how to disable weekends in date time picker as well as holidays. I am using this Jquery script from Trentrichardson http://trentrichardson.com/examples/timepicker/
I am sort of new in JS and am about to pull out my hair as I cannot find a way to make this code work:
$(document).ready(function(){
    $('.timepicker').datetimepicker({ beforeShowDay: $.datepicker.noWeekends });

    var natDays = [
    [2, 26, 'ph'], [2, 6, 'ph'], [2, 17, 'ph']
    ];

    function noWeekendsOrHolidays(date) {
        var noWeekend = $.datepicker.noWeekends(date);
        if (noWeekend[0]) {
            return nationalDays(date);
        } else {
            return noWeekend;
        }
    }

    function nationalDays(date) {
        for (i = 0; i < natDays.length; i++) {
            if (date.getMonth() == natDays[i][0] - 1
            && date.getDate() == natDays[i][1]) {
                return [false, natDays[i][2] + '_day'];
            }
        }
        return [true, ''];
    }

});

I found this code yesterday, which is the correct answer(Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?), but I can't get it to work. It doesn't show the holidays but weekends have been disabled(working).
Any ideas?

A: Checking whether a date is a Saturday or Sunday should not require a separate function:
if (date.getDay() % 6) {
  // date is not a weekend
} else {
  // date is a weekend
}

Checking for public holidays (which can be much more difficult given that dates change from year to year and place to place) can be easy too. Create a list of the dates in a set format (ISO8601 is convenient), then you can just test against current date:
// You may have a function like this already
// d is a javascript Date object
function dateToISO(d) {
  function z(n){return (n<10? '0':'')+n}
  return d.getFullYear() + '-' +
         z(d.getMonth() + 1) + '-' +
         z(d.getDate());
}

// s is a date string in ISO8601 format
function isPublicHoliday(s) {
  var holidays = '2012-12-25 2012-12-26'; // list holidays
  var m = holidays.match(s);
  return !!(m && m.length);
}

isPublicHoliday(dateToISO(date));  // true for 2012-12-25

Of course you will want to implement the above differently, but it gives you the gist of it. Presumably the date picker returns a date object, or a formatted string that you can test. Testing against a string is very fast and saves a lot of hassle with arrays and functions. Very easy to maintain too, since the dates are quite human readable.


text:
Q: How to fix docker so that it stops messing with android studio from connecting to emulator in OSX Related to this question : Android Emulator doesn't start in MacOS 10.10
Indeed docker installation makes impossible to start an emulator in android studio. Quiting docker makes it possible to start the emulator but not to start the app (the emulator stays on the main screen). With error :
Error while waiting for device: Timed out after 300seconds waiting for emulator to come online.

Somebody has a solution for this ?

A: So. Not sure how I did it but here is what I did:

*

*Installed all the updates of android studio

*Deleted all the virtual devices

*Installed only the latest device with the latest version of android

Seems to work... for now.