text:
Q: Retrieving value based on matched dates I have two dataframes. The first ones containing Events with corresponding start and end times. The second one containing the prices of different ID's for every minute. Look below:
Event                       starttime             endtime
Change in Nonfarm Payrolls  2020-03-06 08:15:00   2020-03-06 09:00:00
Change in Nonfarm Payrolls  2020-02-07 08:15:00   2020-02-07 09:00:00
Change in Nonfarm Payrolls  2020-01-10 08:15:00   2020-01-10 09:00:00
Change in Nonfarm Payrolls  2020-01-10 08:15:00   2020-01-10 09:00:00

Price    date_time             ID
24813    2020-03-06 08:14:00   DJ
24763    2020-03-06 08:15:00   DJ
24750    2020-03-06 08:16:00   DJ
24725    2020-03-06 08:17:00   DJ

I would like to obtain the price and ID from the second dataset (for the starttime and endtime) and add it to the first one. I have tried using ifelse like this but it doesn't work.
df1$startprice <- ifelse(df1$starttime == df2$date_time, df2$Price, "no")

Can someone help me out?
To reproduce the data: (For the first Event the start and end time are included)
df1 <- structure(list(Event = structure(c(1L, 1L, 1L, 1L, 1L), .Label = c("Change in Nonfarm Payrolls"), class = "factor"),
                    starttime = structure(c(1583478900, 1581059700, 1578640500, 1578640500, 1581059700), class = c("POSIXct", "POSIXt"), tzone = ""),
                    endtime = structure(c(1583481600, 1581062400, 1578643200, 1578643200, 1581062400), class = c("POSIXct","POSIXt"), tzone = "")), row.names = c(NA, 5L), class = "data.frame")

df2 <- structure(list(Price = c(24813, 24763, 24750, 24725,
                                      24746, 24735, 24755, 24735, 24735, 24744, 24762, 24763, 24773,
                                      24773, 24778, 24832, 24856, 24845, 24842, 24902, 24934, 24854,
                                      24888, 24914, 24922, 24875, 24896, 24853, 24834, 24845, 24886,
                                      24872, 24844, 24846, 24860, 24812, 24791, 24767, 24765, 24756,
                                      24745, 24791, 24800, 24789, 24787, 24887, 24876, 24911), date_time = structure(c(1583478840,
                                                                                1583478900, 1583478960, 1583479020, 1583479080, 1583479140, 1583479200,
                                                                                1583479260, 1583479320, 1583479380, 1583479440, 1583479500, 1583479560,
                                                                                1583479620, 1583479680, 1583479740, 1583479800, 1583479860, 1583479920,
                                                                                1583479980, 1583480040, 1583480100, 1583480160, 1583480220, 1583480280,
                                                                                1583480340, 1583480400, 1583480460, 1583480520, 1583480580, 1583480640,
                                                                                1583480700, 1583480760, 1583480820, 1583480880, 1583480940, 1583481000,
                                                                                1583481060, 1583481120, 1583481180, 1583481240, 1583481300, 1583481360,
                                                                                1583481420, 1583481480, 1583481540, 1583481600, 1583481660), class = c("POSIXct",
                                                                                "POSIXt"), tzone = ""), ID = c("DJ", "DJ", "DJ",
                                                                                "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ",
                                                                                "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ",
                                                                                "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ",
                                                                                "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ", "DJ",
                                                                                "DJ")), row.names = 62835:62882, class = "data.frame")

Thanks in advance!
Kind regards,
Jurgen

A: I'm assuming you are trying to add the Price and ID from the second dataset to the first dataset by matching the date_time of the second dataset to the starttime of the first dataset.
In that case it can be achieved using dplyr's left_join:
library(dplyr)
df1 %>% left_join(df2, by = c('starttime' = 'date_time'))

Output:
                       Event           starttime             endtime Price   ID
1 Change in Nonfarm Payrolls 2020-03-06 15:15:00 2020-03-06 16:00:00 24763   DJ
2 Change in Nonfarm Payrolls 2020-02-07 15:15:00 2020-02-07 16:00:00    NA <NA>
3 Change in Nonfarm Payrolls 2020-01-10 15:15:00 2020-01-10 16:00:00    NA <NA>
4 Change in Nonfarm Payrolls 2020-01-10 15:15:00 2020-01-10 16:00:00    NA <NA>
5 Change in Nonfarm Payrolls 2020-02-07 15:15:00 2020-02-07 16:00:00    NA <NA>

Update:
You would like to obtain the Price at the starttime AND the Price of the endtime.
You can pipe another left_join to the previous code, this time linking df1's endtime instead of starttime:
combinedPrice <- df1 %>% left_join(df2, by = c('starttime' = 'date_time')) %>% left_join(df2, by = c('endtime' = 'date_time'))

Output of combinedPrice:
Event                           starttime             endtime Price.x ID.x Price.y ID.y
1 Change in Nonfarm Payrolls 2020-03-06 15:15:00 2020-03-06 16:00:00   24763   DJ   24876   DJ
2 Change in Nonfarm Payrolls 2020-02-07 15:15:00 2020-02-07 16:00:00      NA <NA>      NA <NA>
3 Change in Nonfarm Payrolls 2020-01-10 15:15:00 2020-01-10 16:00:00      NA <NA>      NA <NA>
4 Change in Nonfarm Payrolls 2020-01-10 15:15:00 2020-01-10 16:00:00      NA <NA>      NA <NA>
5 Change in Nonfarm Payrolls 2020-02-07 15:15:00 2020-02-07 16:00:00      NA <NA>      NA <NA>

The start and end price are named Price.x and Price.y respectively. Also, we have 2 ID columns as result of the join. We can rename the Price columns and remove 1 ID column like so:
combinedPrice %>% rename('PriceStart' = Price.x, 'PriceEnd' = Price.y, 'ID' = ID.y) %>% select(-ID.x)

Output:
  Event                           starttime             endtime   PriceStart PriceEnd   ID
1 Change in Nonfarm Payrolls 2020-03-06 15:15:00 2020-03-06 16:00:00      24763    24876   DJ
2 Change in Nonfarm Payrolls 2020-02-07 15:15:00 2020-02-07 16:00:00         NA       NA <NA>
3 Change in Nonfarm Payrolls 2020-01-10 15:15:00 2020-01-10 16:00:00         NA       NA <NA>
4 Change in Nonfarm Payrolls 2020-01-10 15:15:00 2020-01-10 16:00:00         NA       NA <NA>
5 Change in Nonfarm Payrolls 2020-02-07 15:15:00 2020-02-07 16:00:00         NA       NA <NA>

A: You can merge twice first with starttime and again with endtime.
merge(df1, transform(df2, start_time_price = Price)[-1],
      by.x = 'starttime', by.y = 'date_time') |>
  merge(transform(df2, end_time_price = Price)[-1],
        by.x = c('ID', 'endtime'), by.y = c('ID', 'date_time'))

If you want to keep all the rows of df1 in the final output use all.x = TRUE in merge. Pipe operator (|>) has been introduced in R 4.1 if you have older version of R use -
merge(merge(df1, transform(df2, start_time_price = Price)[-1],
      by.x = 'starttime', by.y = 'date_time'),
  transform(df2, end_time_price = Price)[-1],
        by.x = c('ID', 'endtime'), by.y = c('ID', 'date_time'))


text:
Q: What is the least ordinal $\beta$ for which the function $f_\beta(n)$ in fast-growing hierarchy is incomputable? Fast-growing hierarchy consists of a transfinite succession of faster growing functions $f_\alpha$:
$f_0(n) := n+1$,
$f_{\alpha+1}(n) := f^n_\alpha(n)$,
$f_{\alpha}(n) := f_{\alpha[n]}(n)$ if $\alpha$ is a limit ordinal where $\alpha[n]$ denotes the n-th element of the fundamental sequence assigned to the limit ordinal $\alpha$.
Ackermann function grows about as fast as $f_\omega$. Some functions like busy beavers grow faster than any computable function. My question is:
What is the least ordinal $\beta$ for which the function $f_\beta(n)$ in fast-growing hierarchy is incomputable?
Clearly, $\beta$ is no greater than Church-Kleene ordinal $\omega^{CK}_1$ since that is the incomputable ordinal itself, but could $\beta$ be smaller, e.g. $\epsilon_0$?

A: That depends on the system of fundamental sequences that is used.  If the system of fundamental sequences for all limit ordinals less than or equal to $\beta$ is computable, then $f_\beta$ will be computable.
More precisely, say we have a computable ordinal $\beta$ and some injective function $g: \beta+1 \mapsto \bf{N}$ such that the image of the limit ordinals, the image of the successor ordinals, and the predecessor function $j(g(\alpha+1)) = g(\alpha)$ are all computable.  Suppose further that there is a computable function $h: \bf{N} \times \bf{N} \mapsto \bf{N}$ such that, for each limit ordinal $\alpha \le \beta$,  $g^{-1}(h(g(\alpha),n))$, as a function of $n$, gives the fundamental sequence for $\alpha$.  Then $f_\beta$ is computable.
Note that it would not be sufficient if for each limit ordinal $\alpha \le \beta$ there would be a computable function $h_\alpha$ such that $g^{-1}(h_\alpha(g(n))$ gives the fundamental sequence for $\alpha$.  A counterexample would be to set $\omega (n+1) [m] = \omega n + BB(n+1)+m$ and $\omega^2 [m] = \omega m$, where $BB(n)$ is the busy beaver function.  Then $f_{\omega^2}(n)$ would exceed the busy beaver function.
Also, it is not clear to me that $f_{\omega^{CK}_1}(n)$ must be incomputable.  Certainly we cannot compute it through an ordinal notation for $\omega^{CK}_1$, but it may be computable some other way.

redpajama_set_name: RedPajamaStackExchange


text:
Q: A question on the prime generating polynomial $x^2 -79x+1601$. In Tom Apostol's book Analytic Number Theory, author says $x^2 -79x+1601$ gives prime numbers for $x=0,1,...,79$.
We can see this by putting values. Is there any other way of knowing this property of this expression? How can we construct more expression with this property?

A: There is a good deal of repetition involved here. If we take the pure translation
$$ x = t + 40 $$ the polynomial becomes
$$ t^2 + t + 41 $$
which is prime for $0 \leq t \leq 39.$ It is also prime for $-40 \leq t \leq -1,$ however these primes are exactly the same primes as thos for non-negative $t.$
The reason we know that this polynomial ($t$) gives all those prime values is that $41$ is prime, $4 \cdot 41 - 1 = 163$ is also prime, and the positive binary quadratic form $$ x^2 + xy + 41 y^2$$ is of class number one, meaning all forms of that discriminant are ($SL_2 \mathbb Z$) equivalent to it. The basic facts here were known to Gauss, an elementary proof of if and only if was provided by Rabinowitz in 1913. See my proof at Is the notorious $n^2 + n + 41$ prime generator the last of its type?
For those who do not know anything about binary quadratic forms, this is a table from Rose, A Course in Number Theory The ordered triple $A,B,C$ refers to the (positive) quadratic form
$$ f(x,y) = A x^2 + B xy + C y^2. $$ See how there is just one entry for discriminant $-163.$


text:
Q: Python: Is isinstance() necessary in this case? I defined a class Time that has three int attributes: hrs, min, sec
And I defined methods intToTime() that convert a Time instance to an int, which is the number of seconds in that time, and also a method timeToInt() that do the reverse.
I'd like them to implement __add__, so I can do things like "TimeA + TimeB" or "TimeA + 100", where 100 is the number of seconds add to TimeA.
As I'd like to merge these two (since there's no overloading in Python),
def __add__(self,num):
    return Time.intToTime(self,Time.timeToInt(self)+num)

def __add__(self,other):
    return Time.intToTime(self,Time.timeToInt(self)+Time.timeToInt(other))

"num" is supposed to be an int, "other" is another Time instance. I know one way using isinstance().
But my question is,
in this case, how should I implement such an add without using isinstance()?

A: You really have two choices: EAFP or LYBL. EAFP (easier to ask forgiveness than permission) means use try/except:
def __add__(self, other):
   try:
       return Time.intToTime(self, Time.timeToInt(self)+Time.timeToInt(other))
   except AttributeError as e:
       return Time.intToTime(self, Time.timeToInt(self) + other)

Note that Time.timeToInst(self) is kind of weird; you would normally write that self.timeToInt().
LYBL means look before you leap - i.e. isinstance. You already know that one.

A: You'd better make intToTime and timeToInt module level functions, the same level as your class Time, and implement your __add__ like this:
def __add__(self, num):
    if isinstance(num, Time):
        num=timeToInt(num)
    elif not isinstance(num, int):
        raise TypeError, 'num should be an integer or Time instance'
    return intToTime(timeToInt(self)+num)

A: It is possible to use overloads in python but it requires extra code to handle it for you. You can find what you are looking for in a package called pythonlangutil which is available on pypi.
from pythonlangutil.overload import Overload,signature

@Overload
@signature("int")
def __add__(self,num):
    return Time.intToTime(self,Time.timeToInt(self)+num)

@__add__.overload
@signature("Time")
def __add__(self,other):
    return Time.intToTime(self,Time.timeToInt(self)+Time.timeToInt(other))


text:
Q: Xamarin Android two way communication between Javascript and C# I am developing an app using Xamarin Android which has a WebView displaying a web page. I want to implement a two way communication between Javascript from WebView to c#. I could call C# from Javascript using this link. However i couldn't find a way to send data back from C# to Javascript.
Is there a way to send data back and forth in this approach. I thought writing a callback in Javascript would work but how to fire it from C# code.
Now, My problem is how to call WebView from a javascript interface class. I have a Javascript interface class as mentioned https://developer.xamarin.com/recipes/android/controls/webview/call_csharp_from_javascript/
     namespace ScannerAndroid
     {
      public class JSInterface: Java.Lang.Object
      {
        Context context;
        WebView webView;
    public JSInterface (Context context, WebView webView1)
    {
      this.context = context;
      this.webView = webView1;
    }

    [Export]
    [JavascriptInterface]
    public void ShowToast()
    {
      Toast.MakeText (context, "Hello from C#", ToastLength.Short).Show ();
      this.webView.LoadUrl ("javascript:callback('Hello from Android Native');");

    }
  }
}

The code throws an exception at LoadUrl line. java.lang.Throwable: A WebView method was called on thread 'Thread-891'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {42ce58a0} called on null, FYI main Looper is Looper (main, tid 1) {42ce58a0})
Now i am struggling how to refer the WebView from this Java script interface class

A: Yes. That is possible. If you are targeting KitKat or higher you can use:
webView.EvaluateJavascript("enable();", null);

Where in this case enable(); is a JS function.
If you are targeting lower API levels you can use LoadUrl();:
webView.LoadUrl("javascript:enable();");

EDIT:
The error you get where it complains on LoadUrl is because it for some reason happens on a non-UI thread.
Since you have already passed on the Context into your JavascriptInterface class, then you can simply wrap the contents of ShowToast in:
context.RunOnUiThread(() => {
   // stuff here
});

Just change signature from Context to Activity and it should help you marshal you back on UI thread.


text:
Q: How to style the same component in multiple ways using CSS Modules in React? I have just recently switched to using CSS Modules in my project and have come into a bit of an issue.
In the simple code example below, I am creating an input component that I want to be able to reuse as a form field when creating forms. The issue comes in when I want to be able to style the input component differently in certain situations.
FormInput.js

const FormInput = props => (
  <FormControl>
    <InputLabel>{props.label}</InputLabel>
    <Input />
  </FormControl>
);

Form.js

import React from 'react';
import Button from '@material-ui/core/Button';
import Input from './input';

const Form = () => (
  <form>
    <Input label="Name" />
    <Button> Submit </Button>
  </form>
);

I know this can be done using styled-components, but I am really looking for a solution that uses CSS Modules. Any help would be appreciated

A: You can simply import the css and pass it as a prop to Input. In this case, you can pass it down as className.
Note: As you'll notice below, CSS can be a bit redundant when it comes to styling nested and pseudo elements, which is why I'd highly recommend SASS (scss or less) for preprocessed stylesheets (post-processing will convert the SASS stylesheets to a plain CSS stylesheet for you).
Working example (reusing Input but styling it with different classes):

components/Input (it accepts a className string, onChange function (required), label string, name string (required), and a value string)
import React from "react";
import PropTypes from "prop-types";

const Input = ({ className, onChange, label, name, value }) => (

    {label}:
    <input value={value} onChange={onChange} name={name} type="text" />

);

// PropTypes ensures that passed down props adhere to the type checking
// rules defined below
Input.propTypes = {
  className: PropTypes.string,
  onChange: PropTypes.func.isRequired,
  label: PropTypes.string,
  name: PropTypes.string.isRequired,
  value: PropTypes.string
};

export default Input;

styles.css (you'll need to use camelCase instead of snake-case for classNames)
.appContainer {
  text-align: center;
  padding: 20px;
}

input {
  height: 40px;
  vertical-align: middle;
  display: inline-block;
  border: 0 none;
  padding: 0 10px;
  background: #fff;
  color: #666;
  border: 1px solid #e5e5e5;
  transition: 0.2s ease-in-out;
  transition-property: color, background-color, border;
  font-size: 15px;
}

.nameField {
  font-weight: bold;
  color: blue;
  margin-bottom: 20px;
}

.nameField > input {
  color: green;
}

.emailField {
  font-weight: bold;
  color: red;
  margin-bottom: 20px;
}

.emailField > input {
  color: blue;
}

.resetButton {
  cursor: pointer;
  background-color: transparent;
  color: #222;
  border: 1px solid #e5e5e5;
  margin: 0;
  overflow: visible;
  box-sizing: border-box;
  padding: 0 30px;
  vertical-align: middle;
  font-size: 14px;
  line-height: 38px;
  text-align: center;
  text-decoration: none;
  text-transform: uppercase;
  transition: 0.1s ease-in-out;
  transition-property: color, background-color, border-color;
}

.resetButton:hover {
  background-color: transparent;
  color: #222;
  border-color: #b2b2b2;
}

.resetButton:focus {
  outline: none;
}

components/App (import all of the css as classes and apply them as needed -- you can also use ES6 destructuring to pull out single classes, for example:
import { appContainer } from "./styles.css";)
import React from "react";
import { render } from "react-dom";
import Input from "./components/Input";
import useFieldHandler from "./hooks/useFieldHandler";
import classes from "./styles.css";

const App = () => {
  const { values, handleChange, resetValues } = useFieldHandler({
    name: "",
    email: ""
  });

  return (

CSS Modules

      <Input
        label="Name"
        name="name"
        className={classes.nameField}
        value={values.name}
        onChange={handleChange}
      />
      <Input
        label="Email"
        name="email"
        className={classes.emailField}
        value={values.email}
        onChange={handleChange}
      />

        <button
          type="button"
          className={classes.resetButton}
          onClick={resetValues}
        >
          Reset
        </button>

  );
};

render(<App />, document.getElementById("root"));

A: So what I was explaining above is to pass a unique id as a prop and then you need to use a template literal to append that to the existing class name in the Input component.
FormInput.js

const FormInput = props => (
  <FormControl>
    <InputLabel>{props.label}</InputLabel>
    <Input uniqueClass='unique-class'/>
  </FormControl>
);

Form.js

import React from 'react';
import Button from '@material-ui/core/Button';
import Input from './input';

const Form = () => (
  <form>
    <Input uniqueClass='unique-class' label="Name" />
    <Button> Submit </Button>
  </form>
);


text:
Q: StreamWriter Access Denied on Windows Startup I'm having an issue with StreamWriter, here's my code:
WebClient versionDownloader = new WebClient();
versionDownloader.DownloadFile("/* Version file here */", "EHWVBVersion.txt");
StreamReader reader = new StreamReader("EHWVBVersion.txt");
if (Version.Parse(reader.ReadLine()) > version)
{
    DialogResult dialogResult = MessageBox.Show("New version available ! Do you want to download it ?", "EHWVB", MessageBoxButtons.YesNo);
    if (dialogResult == DialogResult.Yes)
    {
        reader.Close();
        File.Delete("EHWVBVersion.txt");
        Process.Start("/* Download link Here */");
        Application.Exit();
    }
}
reader.Close();
File.Delete("EHWVBVersion.txt");

(Yes, there are actual links instead of comments in my code)
It's giving me an error mentioning Access Denied to "C:\WINDOWS\System32\EHWVBVersion.txt" even though I'm not wrtiting there. I guessed it had to so with something about temp file not loaded yet so I tried to print mentioned path before and tried, and nope, it is loaded.
So then I coded this function :
private void Log(string line)
{
    if (!File.Exists("EHWVB.log"))
        File.Create("EHWVB.log").Close();
    StreamWriter writer = new StreamWriter("EHWVB.log", true);
    writer.WriteLine(DateTime.Now + " : " + line);
    writer.Close();
}

And tried to log everything that was accessing the version file.
I was quite surprise to discover that it isn't my version file that creates an issue or it's path, but the File Creation process directly. Same error, but for "C:\WINDOWS\System32\EHWVB.log" this time.
The thing is, if I try all this again not on Windows Startup, everything work fine. Version file is downloaded, logging works, etc.
Any idea ?


text:
Q: react-player youtube player swallows keypress events I'm using react-player to play youtube videos and have a lot of custom hotkeys defined with react-hotkeys-hook. I've got the following config which prevents the default youtube key handlers from running:
const PLAYER_CONFIG: Config = {
  youtube: {
    playerVars: { controls: 0, disablekb: 1, rel: 0 },
  },
}

However with this config (or event with disablekb: 0) the youtube player still swallows all keypress events when it has focus and my custom hotkey handlers don't run. There was a similar issue in the react-player repo back in 2022, closed without resolution.
Is there a way I can get the youtube embedded player to forward these on?

EDIT (things I've tried)
It turns out I can access the internal iFrame in React Player by
<ReactPlayer
    onReady={(player) => {
        console.log(player.getInternalPlayer()['getIframe']())
    }}
    // ...

But attempting to  .contentWindow.addEventListener(...) results in a security error:
Uncaught DOMException: Blocked a frame with origin "http://localhost:3000" from accessing a cross-origin frame.

Related?
I'm beginning to think this might not be possible with the youtube iFrame API.
How to add keydown event on iframe while playing youtube video?

A: There doesn't currently appear to be a workaround for this, the youtube iFrame swallows keypress events and most video players simple wrap the youtube API.
As a workaround I've positioned a transparent div over the top of the youtube player and added onClick handlers on it to mock the youtube mouse events.
Its not perfect as this means there are things like related videos that appear to be clickable but aren't, but at least the player can be contorolled with key combinations.


text:
Q: using = inside bquote a <- "A"
bquote(.(as.name(a)) = 4)

Error: unexpected '=' in "bquote(.(as.name(a)) ="
bquote(A = 4)

Error in bquote(A = 4) : unused argument (A = 4)
a <- "A"
bquote(f(.(as.name(a)) = 4))

Error: unexpected '=' in "bquote(f(.(as.name(a)) ="
How can I get around this?

A: We don't need as.name
plot(1, 1, main = bquote(.(a) == 4))

-output

or another option with quotes
plot(1, 1, main = bquote(.(a)~'= 4'))


text:
Q: mongodb with nodejs this is th code I am using inserting a document to mongodb.
        var client = new Db('test', new Server("127.0.0.1", 27017, {}), {w: 1}),
        test = function (err, collection) {
        collection.insert({a:2}, function(err, docs) {

        collection.count(function(err, count) {
          test.assertEquals(1, count);
        });

        // Locate all the entries using find
        collection.find().toArray(function(err, results) {
          test.assertEquals(1, results.length);
          test.assertTrue(results[0].a === 2);

          // Let's close the db
          client.close();
        });
      });
    };

client.open(function(err, p_client) {
  client.collection('test_insert', test);
});

but while running I am getting error
xports, require, module, __filename, __dirname) {  var client = new Db('test',
                                                                    ^
ReferenceError: Db is not defined
    at Object. (C:\Users\Basic node\cheerio\mongonode.js:1:81
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)

can you suggest me how to solve this problem
thanks in advance

A: Please import all the required modules, which you are using. Db is not defined points out that Db is defined in some other module or you have forgot to declare it.

A: You'll notice this exact code block posted in a number of different stackoverflow questions. The problem here is that this is a copy and pasted code block from mongodb's documentation, as is in fact the first example of a mongodb nodejs program.
https://npmjs.org/package/mongodb
You'll find this under "Introduction" as "A simple example of inserting a document."
It's clearly an incomplete example, but a lot of people are just trying it out to see if they've got everything installed correctly and immediately run into a wall.
Most people will have installed the mongodb driver, but will be missing something at the top like this:
var mongodb = require('mongodb');
var Db = mongodb.Db;
var Server = mongodb.Server;

I also fell into the copy-paste trap here and ran into another issue with the "assertEquals" method not existing. I've seen other people reference that function in other places on the web, but not really sure how it works.
In any case, to make it work for me, I required the assert module:
var assert = require('assert');

And then I replaced the assertEquals lines with something like this:
          assert.equal(1, count, "Unexpected result");

Note that you're going to run into an issue if you've run this a couple of times; it's going to count the number of things in that table, and there is going to be more than one.
You'll have to figure out how to get into mongo's CLI and remove them to get it to run successfully.

A: Try to install mongodb native driver
npm install mongodb


text:
Q: Execution of neo4j cypher query from spring boot Hi neo4j/spring boot masters
I am new to spring boot and I am trying to execute a cypher query without the @Query annotation.
I can see that my requirement is possible with entityManage.createQuery() in spring repository (javax)
But the adaptor for neo4j doesn't seem to have an entity Manager.
Any help is greatly appreciated.

A: I used the neo4j java driver in my spring boot as described at Using Neo4j from Java
This is maybe not what neo4j offers first, but i feel it is simple. You can also use it without transactions.

A: Depending on your needs, have a look at org.springframework.data.neo4j.core.Neo4jClient - specifically the query() method - if you have setup neo4j correctly in Spring then you can simply inject this class.


text:
Q: system_clock returning negative time c++ I'm writing code to time a for loop, and I used code given to me by my professor, and it uses system_clock.
My problem is that on one of my for loops that I am timing, it is returning a negative time. Sometimes it's different number, but always negative.
Here's the code:
std::chrono::time_point<std::chrono::system_clock> start2, end2;
int sum2 = 0;
std::cout << "Sum on reference ";
start2 = std::chrono::system_clock::now();
for(int i = 0; i < 10000; i++)
{
    sum2 = secondSum(dr);
}
end2 - std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds2 = end2 - start2;
std::cout << "sum: " << sum2 << std::endl;
std::cout << "Elapsed time for data processing on reference: " << elapsed_seconds2.count() << "s\n";

Where dr is a reference to a struct with a filled array inside and secondSum is a function that sums different values inside that array.

A: You need to change the line end2 - std::chrono::system_clock::now(); to end2 = std::chrono::system_clock::now();. After that your code should work exactly how you intended it to work.


text:
Q: How do I use raw sockets in Perl? How can you get a raw socket in Perl, and then what's the best way to built a packet for use with it?

A: The same way you do in C... by setting the socket type when creating the socket.
In the example on CPAN use SOCK_RAW rather than SOCK_DGRAM (UDP) or SOCK_STREAM (TCP).
NOTE: creating raw sockets typically requires administrative privileges (i.e. root on UNIX). Windows OS's may have disabled ability to create raw sockets, you'll just have to test it and see.

A: Perhaps searching CPAN might help?  IO::Socket comes to mind.

A: At first I was thinking that most previous answers were not responsive to the question.
After further thought, I think the author is probably not asking the right question.
If you're writing an application, you don't usually think of "building packets". you just open sockets, format up the data payload, and it's the protocol stack that builds packets with your data.  OK, if you're using datagrams, you do need to define, generate and parse your payloads.  But you typically let the kernel encapsulate it at the network level (e.g. add IP header) or link layer (e.g. add Ethernet framing).  You usually don't use pcap.  Sometimes just pack and unpack and maybe vec is enough.
If you're writing an unusual packet processor such as an active hostile attack tool, a man-in-the-middle process, or a traffic shaping device, then would be more likely to be "building packets" and using pcap.  Maybe Net::Packet is for you also.

A: Looks like Net::RawIP was what I was looking for:
use Net::RawIP;
$a = new Net::RawIP;
$a->set({ip => {saddr => 'my.target.lan',daddr => 'my.target.lan'},
         tcp => {source => 139,dest => 139,psh => 1, syn => 1}});
$a->send;

$a->ethnew("eth0");
$a->ethset(source => 'my.target.lan',dest =>'my.target.lan');
$a->ethsend;

$p = $a->pcapinit("eth0","dst port 21",1500,30);
$f = dump_open($p,"/my/home/log");
loop $p,10,\&dump,$f;

A: As austirg and others said, Socket will do this just fine:
use Socket;

socket my $socket, PF_INET, SOCK_RAW, 0 or die "Couldn't create raw socket: $!";

send $socket, $message, $flags, $to or die "Couldn't send packet: $!";

my $from = recv $socket, $message, $length, $flags or die "Couldn't receive from socket: $!";

A: The basic call to get a socket is...  socket().  It comes standard with perl 5.  perl 5 basically gives you the standard socket(), bind(), listen(), accept() calls that traditional UNIX does.
For a more object oriented model, check out IO::Socket.

A: Be aware that if you're trying to use raw sockets to send a pile of SYN packets, and you just "use Socket;" that's going to fill up your ARP tables and bomb out with "No buffer space available" and a stack of "CLOSE_WAIT" entries in "netstat" (which stops your machine doing any more connections of any kind until some of them free up).
Or in other words - you do really need Net::RawIP - it makes a difference.


text:
Q: How to create technical conference posters using LaTeX in 2018? What do you use create technical posters in 2018?
I tried searching on the web and https://www.sharelatex.com/learn/Posters seems to be leaning towards tikzposter for the ease of flexibility.
I have seen How to create posters using LaTeX too and the top answer recommends beamerposter but that answer is quite old and dates back to 2010.
This is why I am asking a new question to know what do you use to create technical conference posters in 2018?


text:
Q: Parse json data seperated by new line in Nodejs I have been working on some project i have to work on JSON data separated by a newline. Here is the shape of the data:
{"response": "True", "controllerId": "2751", "level": "INFO", "logType": "watchdogResponse", "deviceId": "2751", "container": "firmware", "epoch": "1549996256", "module": "hostServices", "ts": "2019-02-13 00:00:56"}
{"ts": "2019-02-13 00:01:10", "epoch": "1549996270", "level": "INFO", "module": "jr", "logType": "running", "controllerId": "2751", "deviceId": "2751", "rid": "EXTERNAL CALL", "val": "1549996260000"}
{"ts": "2019-02-13 00:01:10", "epoch": "1549996270", "level": "INFO", "module": "applicationMain", "logType": "wifi", "controllerId": "2751", "deviceId": "2751", "networkStrength": "100.0"}

Now how can I parse it and I have to sort the data by its key.

A: If I understand correctly, the data is not a valid JSON string, but rather JSON strings separated by line breaks. So this is how the data can be converted into the array of objects with sorted key order:

'use strict';

const data =
`{"response": "True", "controllerId": "2751", "level": "INFO", "logType": "watchdogResponse", "deviceId": "2751", "container": "firmware", "epoch": "1549996256", "module": "hostServices", "ts": "2019-02-13 00:00:56"}
{"ts": "2019-02-13 00:01:10", "epoch": "1549996270", "level": "INFO", "module": "jr", "logType": "running", "controllerId": "2751", "deviceId": "2751", "rid": "EXTERNAL CALL", "val": "1549996260000"}
{"ts": "2019-02-13 00:01:10", "epoch": "1549996270", "level": "INFO", "module": "applicationMain", "logType": "wifi", "controllerId": "2751", "deviceId": "2751", "networkStrength": "100.0"}`;

const sortedArrayOfObjects = data
  .split('\n')
  .map(JSON.parse)
  .map(obj => Object.entries(obj).sort().reduce(
    (o, [k, v]) => (o[k] = v, o), {})
  );

console.log(sortedArrayOfObjects);

A: Assuming you want to sort using the date.

let input = `{"response": "True", "controllerId": "2751", "level": "INFO", "logType": "watchdogResponse", "deviceId": "2751", "container": "firmware", "epoch": "1549996256", "module": "hostServices", "ts": "2019-02-13 00:00:56"}
{"ts": "2019-02-13 00:01:10", "epoch": "1549996270", "level": "INFO", "module": "jr", "logType": "running", "controllerId": "2751", "deviceId": "2751", "rid": "EXTERNAL CALL", "val": "1549996260000"}
{"ts": "2019-02-13 00:01:10", "epoch": "1549996270", "level": "INFO", "module": "applicationMain", "logType": "wifi", "controllerId": "2751", "deviceId": "2751", "networkStrength": "100.0"}`

let out = input.split('\n').map(JSON.parse).sort((a, b) => {
  new Date(a.ts) > new Date(b.ts);
})
console.log(out);

A: You can use JSON.parse() to parse JSON into a javascript object. To sort the data by their key in lexicographical order you could create an array using Object.entries() and then sort it using the array's sort() method.
let obj = JSON.parse(data)
let arr = Object.entries(obj).sort()

Where arr would then be an array containing the key-value pairs (as arrays) sorted by their key.


text:
Q: CUDA version crash I installed CUDA 11.2 and realised that's not the version I wanted... Then I uninstall it via Control Panel "Uninstall a Program" and uninstall all CUDA 11.2 stuff(but I didn't uninstall those Nvidia Nsight stuff)
After that I install CUDA 10.2, but as I key in below 2 commans, both showed me different CUDA verisons.
I'm using Windows 10, with GeForce GTX 1650.
> nvcc --version

nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2019 NVIDIA Corporation
Built on Wed_Oct_23_19:32:27_Pacific_Daylight_Time_2019
Cuda compilation tools, release 10.2, V10.2.89

But with
>nvidia-smi

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 461.09       Driver Version: 461.09       CUDA Version: 11.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name            TCC/WDDM | Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  GeForce GTX 1650   WDDM  | 00000000:01:00.0 Off |                  N/A |
| N/A   38C    P8     8W /  N/A |    134MiB /  4096MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+

10.2 and 11.2... Any idea on this?
Thank you!!

A: nvidia-smi shows the highest version of CUDA supported by your driver. nvcc shows the version of the current CUDA installation. As long as your driver-supported version is higher than your installed version, it's fine. You can even have several versions of CUDA installed at the same time.


text:
Q: Making Windows to go usb on UBUNTU How can i make "windows to go" usb using operating system ubuntu or other linux distros. I have iso image of windows 10 and 32gb usb stick and running ubuntu, and i want to make windows to go 32gb stick

A: You can try running Rufus in Wine:

*

*Install a Rufus .exe file at https://rufus.ie
You can get the installer or portable but in this answer, I'm going to use portable.

*Open a terminal and do the following:
sudo apt install wine

This will install WINE and take a while.

*Cd to your rufus .exe file:

cd <path/to/rufus-X.X.exe>

Where the X replaces your version no.

*Run Rufus:

wine <name of rufus .exe file>

For e.g:
sudo wine rufus-3.5p.exe

*Then go here to work out how to do it with Rufus:
https://beebom.com/how-create-windows-to-go-usb/
Look for the part where it says: "Create Windows To Go USB Using Rufus"

Hope this helps!
-GalaxCode


text:
Q: What is preventing my Chrome profile from working with Selenium in Python? I am trying to use Python to automate a number of work processes that primarily take place in an online content management system, and to access the CMS, I need to be logged into my work profile on Chrome. While I could sign in once Chromedriver is open, I would have to approve the login on my authenticator each time, somewhat defeating the purpose of automation.
I am using the following code for opening Chromedriver and attempting to load my regular Chrome profile. However, while the rest of the code works as intended, it does not load my profile and I am unsure why.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("--start-maximized")
options.add_argument("--user-data-dir=C:\\Users\\Saul\\AppData\\Local\\Google\\Chrome\\User Data\\Default")
driver = webdriver.Chrome("C:\\Users\\Saul\\Downloads\\chromedriver_win32\\chromedriver.exe", options=options)
driver.get("https://myaccount.google.com/")
while(True):
    pass

I do get the following error while running the code, but I don't believe this is affecting my issue.

C:\Users\Saul\PycharmProjects\OnlineAutomation\main.py:12: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome("C:\\Users\\Saul\\Downloads\\chromedriver_win32\\chromedriver.exe", options=options)

A: Your question is not related to the error you mentioned.
For the error - 'DeprecationWarning: executable_path has been deprecated, please pass in a Service object', you have to use Service:
from selenium.webdriver.chrome.service import Service

driver = webdriver.Chrome(service=Service("C:\\Users\\Saul\\Downloads\\chromedriver_win32\\chromedriver.exe"), options=options)

For the Chrome profile issue, you have to mention the profile path like below:
options.add_argument("--user-data-dir=C:\\Users\\Saul\\AppData\\Local\\Google\\Chrome\\User Data")

options.add_argument("--profile-directory=Default")

A: If your website has MFA enabled, you might be able to use SeleniumBase (a Python framework), which has methods for handling MFA Login:
 An example test with the BaseCase class. Runs with pytest or nosetests. (Learn more)
from seleniumbase import BaseCase

class TestMFALogin(BaseCase):
    def test_mfa_login(self):
        self.open("https://seleniumbase.io/realworld/login")
        self.type("#username", "demo_user")
        self.type("#password", "secret_pass")
        self.enter_mfa_code("#totpcode", "GAXG2MTEOR3DMMDG")  # 6-digit
        self.assert_exact_text("Welcome!", "h1")
        self.assert_element("img#image1")
        self.click('a:contains("This Page")')
        self.save_screenshot_to_logs()

 An example test with the sb pytest fixture. Runs with pytest.
def test_mfa_login(sb):
    sb.open("https://seleniumbase.io/realworld/login")
    sb.type("#username", "demo_user")
    sb.type("#password", "secret_pass")
    sb.enter_mfa_code("#totpcode", "GAXG2MTEOR3DMMDG")  # 6-digit
    sb.assert_exact_text("Welcome!", "h1")
    sb.assert_element("img#image1")
    sb.click('a:contains("This Page")')
    sb.save_screenshot_to_logs()

 An example test with the SB Context Manager. Runs with pure python.
from seleniumbase import SB

with SB() as sb:  # By default, browser="chrome" if not set.
    sb.open("https://seleniumbase.github.io/realworld/login")
    sb.type("#username", "demo_user")
    sb.type("#password", "secret_pass")
    sb.enter_mfa_code("#totpcode", "GAXG2MTEOR3DMMDG")  # 6-digit
    sb.assert_text("Welcome!", "h1")
    sb.highlight("img#image1")  # A fancier assert_element() call
    sb.click('a:contains("This Page")')  # Use :contains() on any tag
    sb.click_link("Sign out")  # Link must be "a" tag. Not "button".
    sb.assert_element('a:contains("Sign in")')
    sb.assert_exact_text("You have been signed out!", "#top_message")

There's a SeleniumBase pytest command-line option, --user-data-dir=DIR, which you can add to set a user data directory to use. Eg:
pytest --user-data-dir=DIR


text:
Q: JavaScript: get words and its indices in a sentence I need to get all the words from a sentence and also their index position within the sentence. The same word can happen multiple times in the sentence.
I was trying to do this using the filter method but the index indicates the position in the array not the position within the sentence.
var sentence = "This is a short sentence, a demo sentence."

sentence.split(" ").filter((word, index) => {

}

A: You can use .reduce:

const sentence = "This is a short sentence, a demo sentence.";
let index = 0;
const nonAlphabeticWithoutSpace = /[^a-zA-Z ]/g;

const res = sentence.split(" ").reduce((acc, item) => {
  // get word without other characters
  const word = item.replace(nonAlphabeticWithoutSpace, "");
  // get prev indices of this word
  const wordIndices = acc[word];
  // create/update the indices list
  acc[word] = wordIndices ? [...wordIndices, index] : [index];
  // increment the index
  const nonAlphabetic = item.match(nonAlphabeticWithoutSpace);
  index += nonAlphabetic
    ? word.length+nonAlphabetic.length+1
    : word.length+1;
  return acc;
}, {});

console.log(res);

If you want to disregard case senstivity, use .toLowerCase().

A: Use map instead of filter, loop the array and find position by calculating the letter count.

...and also their index position within the sentence.

By index I assume the position at which the word starts in the sentence.

var sentence = "This is a short sentence, a demo sentence."
let position = 0;
// the words array
const wordsList = sentence.split(" ");

// get the word and position in sentence
const wordDetails = wordsList.map((word, index) => {
  // +1 to account for space
  position = index && wordsList[index - 1].length + position + 1;
  return {
    word,
    position
  };
});

console.log(wordDetails);

If you need a different output like { <word> : [pos1, pos2] } try below sample

var sentence = "This is a short sentence, a demo sentence."
let position = 0;
// the words array
const wordsList = sentence.split(" ");
let wordDetails = {};

// get the word and position in sentence
wordsList.forEach((word, index) => {
  // +1 to account for space
  position = index && wordsList[index - 1].length + position + 1;

  // check if entry exists
  if (!wordDetails[word]) {
    wordDetails[word] = [];
  }

  // insert the position in array
  wordDetails[word].push(position)
});

console.log(wordDetails);

A:

  // below code will execute an object with key of
  // the index and value

  const sentence = "This is a short sentence, a demo sentence."
        let result = {}
        sentence.split(" ").forEach((word, index) => {
            result = {
                ...result,
                [index]: word
            }
        })
        console.log(result)
        /*
        the result will be like below:
        {
            0: "This"
            2: "a"
            1: "is"
            4: "sentence,"
            3: "short"
            6: "demo"
            5: "a"
            7: "sentence."
        }
        */


text:
Q: Message won't echo So I have in my DB.php
 public function query($sql, $params = array()){
    $this->_error = false;
    if($this->_query = $this->_pdo->prepare($sql)){
        echo "Success";
    }
}

And in my index.php I have this DB::getInstance()->query("SELECT username FROM users"). Why doesn't it echo Success?

A: Try using the double equals... ==
Your code now is an assignment in the if statement with one equals.
The code in question now is: if($this->_query = $this->_pdo->prepare($sql)){
Try changing this line of code to if($this->_query == $this->_pdo->prepare($sql)){
I hope this helps. I do not use the object-oriented style of PHP for the most part, but have used the procedural coding style of PHP quiet a bit.


text:
Q: Custom Module Observer not sending mail My Custom Observer is not sending the email.
public function sendAdminMail(Varien_Event_Observer $observer)
{
    $customer = $observer->getEvent()->getCustomer();

    $customerName = $customer->getFirstname() . ' ' . $customer->getLastname();

    $emailTemplate = Mage::getModel('core/email_template');
    $template = "customer_registration_email_template";
    $sender = array('name' => 'Customer Registration',
                    'email' => 'registrationform@mydomain.com');
    $recipientEmail = Mage::getStoreConfig('contacts/email/recipient_email');
    $recipientName = "Sales";
    $variables = array('customer'=>$customerName);

    $emailTemplate->sendTransactional(
        $template,
        $sender,
        $recipientEmail,
        $recipientName,
        $variables
    );
}

Here is my config.xml (global node)
<template>
        <email>
            <customer_registration_email_template translate="label" module="adminnotification">
                Customer Registration Admin Notification
                <file>schott/customer_registration.html</file>
                <type>html</type>
            </customer_registration_email_template>
        </email>
    </template>

To be complete, here is the system.xml too
<config>
Customer Registration Admin Notification
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_email_template</source_model>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</config>

An email should be sent to the admin when a new customer registers.
What am I doing wrong here? The template is showing in the list of Transactional mails in the backend and it sends when I use it testwise for new orders for example.
Strange is also, that the content of the template does not load in the backend (transactional mails) when I add a new template and want to load its default content (it just loads and stays blank).
Any help appreciated. Thanks in advance!

A:       public function sendAdminMail(Varien_Event_Observer $observer)
      {
      $customer = $observer->getEvent()->getCustomer();

      $customerName = $customer->getFirstname() . ' ' . $customer->getLastname();

      $emailTemplate = Mage::getModel('core/email_template')->loadDefault('customer_registration_email_template');
      $senderName = 'Customer Registration';
      $senderEmail = 'registrationform@mydomain.com';
      $emailTemplateVariables = array();
      $emailTemplateVariables['customer'] = $customerName;
      $processedTemplate = $emailTemplate->getProcessedTemplate($emailTemplateVariables);
      $recipientEmail = Mage::getStoreConfig('contacts/email/recipient_email');
      $recipientName = "Sales";
      $mail = Mage::getModel('core/email')
              ->setToName($recipientName)
              ->setBody($processedTemplate)
              ->setSubject($post_data['subject'])
              ->setFromEmail($senderEmail)
              ->setFromName($senderName)
              ->setType('html')
              ->setToEmail($recipientEmail);

      try{
                   $mail->send();
          }
          catch(Exception $error)
          {
              Mage::getSingleton('core/session')->addError($error->getMessage());
              return false;
          }
      }

Try this code. Not sure other things you have done are correct or not. If you are using any mail senders like mandril then the sender email should be in your domain.


text:
Q: Get PID of the inserted row I am using PHP to insert rows into mysql.
I wanted to know the pid (primary ID) immediately after inserting that row as a return value.
Kindly advice ... how can I do this.
Thanks in advance

A: Depending on the extension you're using:
mysql: mysql_insert_id() (DOCUMENTATION)
mysqli: mysqli::$insert_id (DOCUMENTATION)
PDO: PDO::lastInsertId() (DOCUMENTATION)

A: You can use as below :
$id = mysql_insert_id();

For more details refer This link


text:
Q: CSS to style one line of text I have a single line of text that looks like this:

GIVE US A CALL AT ###.###.###

I want the phone number to be significantly bigger than the text and I want it all bottom aligned within the div.
I can't seem to get this to work... what I am missing?
Current HTML:

GIVE US A CALL AT

###.###.###

Current CSS:
.accessSlogan{
    position: relative;
    float: right;
    display: inline;
}

.access-slogan-text {
    display:inline;
    font-size: 1.2em;
    line-height: 2em;
    padding-right: 6px;
    vertical-align: text-bottom;
}

.access-slogan-number{
    position: relative;
    float: right;
    display:inline;
    font-size: 1.8em;
    line-height: 2em;
    vertical-align: text-bottom;
}

A: Both your markup and CSS seem over-complicated, although without knowing where this is to be positioned on a page it's hard to know if that's necessary or not.
At it's simplest this will achieve it:
.access-slogan {
    float: right;
    text-transform: uppercase;
}
.access-slogan .access-slogan-number {
    font-size: 1.8em;
}

Give us a call at ###.###.###

Note that you can't apply float and display:inline to an element since float applies display:block along with it's own document flow rules. You'll also note I've uppercased the text in CSS rather than in the source HTML, since this is a display artefact.

A: Use the  tag and style accordingly.

   GIVE US A CALL AT ###.###.###

CSS:
.accessSlogan{
   float: right;
}

.accessSlogan strong {
    font-size: 1.8em;
    position:relative;
    bottom:0.4em;
}

The point is to use the existing "semantic" HTML to work with you and avoiding over-complicating things.  The  tag is what you mean,  so use it:-)
The relative position of the strong text will need to be adjusted to align perfectly. 0.4em is a starting point (half of the extra height),  but it depends upon the size of the accessSlogan text.

A: I think there is a much more minimal set of CSS you can use for this. Is this demo here what you were after?

A: use  instead of
. It will solve your problem

 call me at 0000-000

or

 call me at0000-000


text:
Q: ADF Tumbling window trigger - Self Dependency I have created a tumbling window trigger with recurrence as 1 hour and attached it to a pipeline. Whenever the pipeline runs I want to process previous 2 hours after which I want to process current hour.
For Ex: If the pipeline is suppose to process records between 10 AM to 11 AM in that given run I want 8 AM to 10 AM records also to be processed after which I want current window 10 AM to 11 AM to be processed. Similarly when 11 AM to 12 PM window kicks in I want 9 AM to 11 AM to be processed before processing 11 AM to 12 PM.
To achieve this functionality I have created a self dependency with offset as -0.02:00:00 and window size as 0.02:00:00.
But when pipeline is getting triggered it is looking for previous dependency windows (8 AM to 10 AM) from previous runs and only 10 AM to 11 AM records are getting processed.
But my requirement is to even process 8 AM to 10 AM records along with 10 AM to 11 AM in that particular run.
Is the functionality of the self dependency tumbling window limited to check only previous runs but not processing those records? Or am I missing something? How can above scenario be achieved via tumbling window trigger? Is it possible to subtract 2 hours from @trigger().outputs.windowStartTime?
Below is the screenshot of the trigger.
TumblingWindowWithSelfDependency
Any help is appreciated. Thanks!

A: While adding trigger on your pipeline, you should pass trigger parameters in to pipeline parameters,
your pipeline should have two paramters like startTime and endTime to take values from trigger parameters
System parameters of tumbling window trigger:
trigger().outputs.windowStartTime --> 10AM - 2hrs == 8AM// it will process 8AM to 10AM records and the will process records between 10 AM to 11 AM
trigger().outputs.windowEndTime ---> 11AM - 2// Here there is no need of going for -2 hrs
startTime --> trigger start time - 2
endTime --> Trigger end time
There is no need of seeting the offset or dependencies.
To achive -2 hours use addhours() function: addHours()


text:
Q: match occurence of 2 patterns with perl regex Suppose I have 2 regex patterns [\d\d] and [a-zA-Z][a-zA-Z] and i want to check if a string has those patterns in any number and in any order and only those patterns separated by comma how can i do this with perl ?

*

*for example string ex,xy,gf,55,66-> match

*for example string 22,24,25,56,ff ->match

*for example string 2FF,24,25,56,ff -> not match

A: Try this :
^(([A-Za-z]{2}|\d\d),)*([A-Za-z]{2}|\d\d)$

Tested on regexe
Got the following result :

A: #!/usr/bin/perl
use warnings;
use strict;

my $pattern1 = '\d';
my $pattern2 = '[a-zA-Z]';
my $string = ('ex,xy,gf,55,66');
my $warning = 0;

my @split = split(/,/, $string);
foreach (@split){
    unless (($_ =~ /^$pattern1{2}$/) or ($_ =~ /^$pattern2{2}$/)) {
        $warning++;
    }
}

print "$string -> match\n" if ($warning == 0);
print "$string -> no match" if ($warning != 0);

Outputs:
ex,xy,gf,55,66 -> match

Same code, different string:
my $string = ('22,2f,ex,xy,gf,2FF');

Outputs:
22,2f,ex,xy,gf,2FF -> no match

A: Here's an option using /^(?:[a-z]{2},?|\d\d,?)+$/i:
use strict;
use warnings;

while (<DATA>) {
    chomp;
    my @elems = split /,/;
    my @match = grep /^(?:\d{2}|[a-z]{2})$/i, @elems;
    print "$_ -> ", ( @elems == @match ? '' : 'not ' ), "match\n"
}

__DATA__
ex,xy,gf,55,66
22,24,25,56,ff
2FF,24,25,56,ff

Output:
ex,xy,gf,55,66 -> match
22,24,25,56,ff -> match
2FF,24,25,56,ff -> not match

Hope this helps!

A: You can use this:
^((?>[a-z]{2}|[0-9]{2})(?>,(?1)|$))

or this:
^(?>(?>[a-z]{2}|[0-9]{2})(?>,|$))+$

A: After playing around with this in Perl, I came up with this.
I tested all the answers posted in Perl. The problems come from trying to match
very large strings. Mostly ones > 256 K. Perl seems to not find a match, where at
a lesser size, it does. Maybe its a setting I'm not using, I don't know..
The exception was Casimir's recursive regex, which takes like a minute to match a 3 meg bufffer.
So for grins, I put together a regex that matches the negative of what is allowed.
The 15 meg buffer takes max 10 seconds on my machine depending where the failure (match)
was, or  10 seconds if it passes. The notable thing is that there is no accumulation of
capture information, maybe thats why it can handle large buffers.
 $test = "ex,xy,gt,55,66,";
 for (0 .. 19 ) { $test .= $test; }
 $test .= "3a3";

 print "\nlength = ", length($test), "\n------------\n";

 if ( $test =~ m/

     # \d(?:[a-z]|\d{2})|[a-z](?:\d|[a-z]{2})|[^a-z\d,]|,(?:.?,|$)|^,

      \d
      (?: [a-z] | \d{2} )
   |
      [a-z]
      (?: \d | [a-z]{2} )
   |
      [^a-z\d,]
   |
      ,
      (?: .? , | $ )
   |
      ^ ,

 /xg )

 {  print "Found error at pos = ", pos($test), "\n";  }
 else
 {  print "Passed test!\n";  }

 __END__

 Output >>

 length = 15728643
 ------------
 Found error at pos = 15728642


text:
Q: phpmailer Error message The domain.com page isn't working I have placed phpmailer folder into my public_html  folder in my web hosting account, but once i test the code i am not getting any error messages, all i am getting is this message.

The webpage.com page isn't workingwebpage.com is currently unable to handle this request.
  HTTP ERROR 500

here is my code
<?php

require_once("/home/webfolder/public_html/PHPMailer_5.2.0/class.phpmailer.php");

$mail = new PHPMailer(true);

$mail->IsSMTP();
$mail->Host = "mail.example.com";
$mail->SMTPAuth  = true;

$mail->Username = "test@example.com";
$mail->Password ="password";
$mail->From =("sender@mailer.com");
$mail->FromName = "John Smith";
$mail->AddAddress="test@example.com";
$mail->WordWrap="50";
$mail->IsHTML(true);
$mail->SMTPDebug  = 1;
$mail->Port  = 26;
$mail->SMTPSecure = "ssl";

$mail->Subject = "Helloworld of SMTP";
$mail->Body = "This is the first email sent from PHP";
$mail->AltBody = "this is alternative mail";

if(!$mail->Send()){

    echo "Mailer Error: " . $mail->ErrorInfo;

}else{

    echo "Message has been sent";
}

?>

i have placed this code in a file called testmailer.php outside phpmailer folder so i usually test the code in a path like this
http://domain.com/testmailer.php


text:
Q: How to block user-agent nginx Access must be denied to the site from the Firefox and Chrome user agents , but if ip adress = 44.221.341.44 and 44.221.342.33 allow and if http-refer = test.com , test.nl , test.de - allow too
i think that to block the agent i have to :
    if ($http_user_agent ~ (Firefox|Chrome)) {
        return 403;
    }

it works
but I don't know how to allow the necessary IP addresses
so i try
if ($remote_addr != XXX.XXX.XXX.XXX) {
        set $test A;
}

if ($http_user_agent ~* (python-requests)) {
        set $test "${test}B";
}

if ($test = AB) {
        return 444;
}

but how i can add here if http-refer = test.com , test.nl , test.de - allow


text:
Q: star schema database in sql server I create a test1 database in sql server 2008 r2 and then another test 2 db ..
tables
product_info table
Product_id
product_name
unitprice
unitsonorder

user_info table
user_id
user_name
user_pwd
email
city
product_id

and in test 2 db i create star schema erd is

now here i want to select data from test1 db and then execute in test2 db .. like etl.. extract, transform and load...
here is the query
create procedure spinsert1
as
insert into user_dimension ( user_name,email)
select USER_NAME,email from test1.dbo.userinfo

when i execute this uery data is not inserted in table
so how i done this?


text:
Q: Lua string comparison not working Well I am learning Lua at the moment and I wanted to write a little script.
It's just for practice and understanding how Lua is working.
   local name = io.read()

 if name == Test
  then print("Right")
  else print("Wrong")
end

Normally the output should be "Right" if I enter "Test" but it always prints "Wrong". I tried it many times and wrote the code in other forms but didn't get my solution.
Can anyone help me please?

A: You're missing a set of quotation marks.
This:
if name == Test

compares the values of two variables, name and Test.
You want this:
if name == "Test"

Lua doesn't require variables to be declared, so this is an easy mistake to make.


text:
Q: Hibernate Correct Mapping Map I've the following classes in Hibernate
@Entity
@Table(name="MODEL")
public class Model {

    @Id
    @GeneratedValue(generator="increment")
    @GenericGenerator(name="increment", strategy = "increment")
    Long id;

  @ElementCollection(fetch=FetchType.EAGER)
    @CollectionTable
    (
        name="DEVICE_LiCENSE_ATTRIBUTE",
        joinColumns=@JoinColumn(name="DEVICE")
    )
    @MapKeyJoinColumn(name="LICENSE_ATTRIBUTE",nullable=false)
    Map<String,SoftwareLicense> softwareLicenses = new HashMap<String, SoftwareLicense>();

}

And this is my embedded Class
@Embeddable
public class SoftwareLicense {

    @Column(name = "Type", nullable = false)
    @Enumerated(EnumType.STRING)
    private Type type;

    @Column(name = "VALUE", nullable = false)
    private String value;
}

Now when I run Hibernate it trues to build Table
create table DEVICE_LiCENSE_ATTRIBUTE (DEVICE bigint not null, Type varchar(255) not null, VALUE varchar(255) not null, softwareLicenses_KEY varchar(255), primary key (DEVICE, softwareLicenses_KEY))

create table DMS_DEVICE_MODEL (id bigint not null, DESCRIPTION varchar(255) not null, DISPLAYNAME varchar(255) not null, UNIQUENAME varchar(255) not null, primary key (id), unique (UNIQUENAME))

My problem occurs when DEVICE_LICENSE_ATTRIBUTE table created.
Just look at DEVICE_LICENSE_ATTRIBUTE table:
softwareLicenses_KEY varchar(255) is nullable and Hibernate tries to create Composite Primary Key on row which is nullable.
primary key (DEVICE, softwareLicenses_KEY)

It works on some DB (HSQLDB), but switching my code to another environment (MS SQL 2008) gives me an error.
Cannot define PRIMARY KEY constraint on nullable column in table 'DEVICE_LICENSE_ATTRIBUTE'

How can I solve this problem?

A: My Mapping was wrong:
The correct way to map it is to use map column attribute:
 @ElementCollection(fetch=FetchType.EAGER)
 @MapKeyColumn(name = "LICENSE_NAME", insertable = false, updatable = false)
    @CollectionTable
    (
        name="DEVICE_LiCENSE_ATTRIBUTE",
        joinColumns=@JoinColumn(name="DEVICE")
    )
    @MapKeyJoinColumn(name="LICENSE_ATTRIBUTE",nullable=false)
    Map<String,SoftwareLicense> softwareLicenses = new HashMap<String, SoftwareLicense>();

Home it will be helpful for somebody.


text:
Q: Compare memory of two Visual Studio instances I have refactored some code, and now the results are very slightly different, even though the input to the method (which I refactored) seems to be the precisely same.
Now the question I have, I have one Visual Studio open with the old code, one with the new code, is there a way to compare the memory between them? I am working with images, so its not that easy to simply compare if the first 10 bytes are the same, I need to compare the first 100000 bytes, which I cannot do manually.
How can I compare two memory blocks from different Visual Studio instances?


text:
Q: STS 3.7.0 crashes on start-up, Windows 7, 64 bit I recently downloaded the zip file of spring tool suite(3.7.0) from it's official web page(https://spring.io/tools/sts/all). After unzipping it and double clicking the sts.exe file, it asks for the namespace. After that when sts loads, the dashboard appears but after few seconds the application crashes. I'm getting the following error popup..

And also a log file is generated whose first few lines are..
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ILLEGAL_INSTRUCTION (0xc000001d) at pc=0x000007fee5f4ca90, pid=5020, tid=3860
#
# JRE version: Java(TM) SE Runtime Environment (8.0_60-b27) (build 1.8.0_60-b27)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.60-b23 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# C  [msvcr120.dll+0x8ca90]
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

I can't seem to understand where I am going wrong. I installed both 32, 64 bit JDK on my machine just in case but still nothing. Is it because windows did not install properly on my laptop?? Please help..
EDIT 1:
In response to @Pendlimarri's comment below, the different forms of Java installed in my control panel are..

A: I too got the same problem. I fixed by uninstalling the 1.8.0_60 update from Control Panel.
This might be a bug in 1.8.0_60.

A: FWIW, it's probably because STS is 32-bit and your JDK is 64-bit - change one or the other and it should work


text:
Q: Firefox 60.3.0 ESR on Debian 9.5 AMD64 zooming bug? Purpose
I need standard zooming functionality to work properly on Firefox 60.3 ESR.
Problem description
I run Firefox 60.3 ESR. Preferences are default, about:config is default. No extensions in the browser, neither meta-extensions in Debian.
I open a website. I use touchpad to access the "hamburger" menu in Firefox and single click zoom in. Zoom in goes straight to 67% from 100%. When I click zoom out, zoom level goes to 80%, but not higher.
Questions
Is this a bug?
How do I restore proper zoom functionality, e.g. zooming down in single steps and zooming out to a 100+% ?
What is the method/approach how to proceed to find the cause of this problem?


text:
Q: use sum and multiplication of a BigInteger I've come across a situation where I have to perform sum and multiplication of the elements of an ArrayList and for this normally I use:
sum+=a.get(i)*b.get(i);

which gives me the exact output I want, but here in my case I've got to do the same with ArrayList of BigInteger type, I've tried it with the below statement, but it is not working as expected.
sum=(a.get(i).multiply(b.get(i))).add(sum);

please let me know how I can do it.
Thanks.

A: Your question is extremely unclear, and as such shouldn't warrant an answer. However, see if the following might help you.
public static void main(String[] args) {
    BigInteger b1 = new BigInteger("1000"), b2 = new BigInteger("1000");
    System.out.println("b1:      " + b1);
    System.out.println("b1 * b2: "+ b1.multiply(b2));
}

Also ensure that you are not falling into the following pit. BigInteger is immutable.

A: BigInteger sum = new BigInteger("10");
List<BigInteger> list = new ArrayList<BigInteger>();
list.add(new BigInteger("2"));
list.add(new BigInteger("3"));
sum=(list.get(0).multiply(list.get(1))).add(sum);
System.out.println(sum);


text:
Q: Video Slideshow I am trying to figure out why my "Back" Button is not working properly. It seems like the only thing im doing wrong is writing the function for previousSlide. Hoping someone can help. See my code below:
$(document).ready(function() {

 $(function(){
     var counter = 0;
     var videos = [
         {videoURL: 'media/SLIDE1.mp4'},
         {videoURL: 'media/SLIDE2.mp4'},
         {videoURL: 'media/SLIDE3.mp4'},
         {videoURL: 'media/SLIDE4.mp4'},
         {videoURL: 'media/SLIDE5.mp4'},
         {videoURL: 'media/SLIDE6.mp4'},
         {videoURL: 'media/SLIDE7.mp4'},
         {videoURL: 'media/SLIDE8.mp4'},
         {videoURL: 'media/SLIDE9.mp4'}
     ];

     $('#next').click(updateSlide);

     function updateSlide() {
         console.log(counter);
                  console.log(videos[counter]);
       $('video').attr('src', videos[counter].videoURL);

       if (counter < videos.length - 1) {
          counter++;
       } else {
        counter = 0;
       }

       //if you leave this uncommented it always increments counter, regardless of what you did above
       //counter++;

     }

     $('#previous').click(previousSlide);

     function previousSlide() {
         console.log(counter);
                  console.log(videos[counter]);
       $('video').attr('src', videos[counter].videoURL);

       if (counter > 0) {
          counter--;
       } else {
        counter = 0;
       }
     }

     //Enables Left and Right Key Navigation
     $(document).keydown(function(e){

        if ( e.which === 37 ) { //left

            $('#previous').click();

        } else if ( e.which === 39 ) { //right

            $('#next').click();
    }
  });

});

Thanks for your help!
Adam

A: Decrement before:
  function previousSlide() {
      if (counter > 0) {
         counter--;
      } else {
         counter = 0;
      }

      $('video').attr('src', videos[counter].videoURL);

 }

Do something similar for your updateSlide function (increment before) and you should be all set.  Seems like it's just an off-by-one error.
 function updateSlide() {
    console.log(counter);
    console.log(videos[counter]);

    if (counter < videos.length - 1) {
      counter++;
    } else {
    counter = 0;
    }

    $('video').attr('src', videos[counter].videoURL);

}


text:
Q: no such table: LTA_LONG_TABLES (code 1): , while compiling: INSERT INTO LTA_LONG_TABLES(longs,lat) VALUES (?,?)  android.database.sqlite.SQLiteException: no such table: LTA_LONG_TABLES (code 1): , while compiling: INSERT INTO LTA_LONG_TABLES(longs,lat) VALUES (?,?)

How i solve it

This is logcat messages
07-15 04:47:32.778 356-357/? E/SocketStream: readFully was waiting for 161376 bytes, got 14480
07-15 04:47:32.778 356-357/? E/SocketStream: readFully was waiting for 146896 bytes, got 16192
07-15 04:47:32.778 356-357/? E/SocketStream: readFully was waiting for 130704 bytes, got 12768
07-15 04:47:32.778 356-357/? E/SocketStream: readFully was waiting for 117936 bytes, got 16192
07-15 04:47:32.778 356-357/? E/SocketStream: readFully was waiting for 101744 bytes, got 16192
07-15 04:47:32.778 356-357/? E/SocketStream: readFully was waiting for 85552 bytes, got 3816
07-15 04:47:32.782 356-357/? E/SocketStream: readFully was waiting for 81736 bytes, got 16192
07-15 04:47:32.782 356-357/? E/SocketStream: readFully was waiting for 65544 bytes, got 16192
07-15 04:47:32.782 356-357/? E/SocketStream: readFully was waiting for 49352 bytes, got 11056
07-15 04:47:32.782 356-357/? E/SocketStream: readFully was waiting for 38296 bytes, got 16192
07-15 04:47:32.782 356-357/? E/SocketStream: readFully was waiting for 22104 bytes, got 16192
07-15 04:47:33.006 10645-10645/com.womansera.confession.mylatlong E/SQLiteLog: (1) no such table: LTA_LONG_TABLES
07-15 04:47:33.006 10645-10645/com.womansera.confession.mylatlong E/SQLiteDatabase: Error inserting longs=New Latitude: 28.613938333333333 lat=New Longitude: 77.20902

android.database.sqlite.SQLiteException: no such table:
  LTA_LONG_TABLES (code 1): , while compiling: INSERT INTO
  LTA_LONG_TABLES(longs,lat) VALUES (?,?) at
  android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
  Method) at
  android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
  at
  android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
  at
  android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
  at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
  at
  android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:31)
  at
  android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
  at
  android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
  at
  com.womansera.confession.mylatlong.DbHelper.insertData(DbHelper.java:51)
  at
  com.womansera.confession.mylatlong.MainActivity.onLocationChanged(MainActivity.java:41)
  at
  android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:234)
  at
  android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:167)
  at
  android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:183)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:99) at
  android.os.Looper.loop(Looper.java:137) at
  android.app.ActivityThread.main(ActivityThread.java:4745) at
  java.lang.reflect.Method.invokeNative(Native Method) at
  java.lang.reflect.Method.invoke(Method.java:511) at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) at
  dalvik.system.NativeStart.main(Native Method)
      07-15 04:47:33.066 10645-10645/com.womansera.confession.mylatlong E/SocketStream: readFully was waiting for 6528 bytes, got 2896

A: While creating table try to add like,
db.execSQL("create table latlong"+ "(latitude text,longitude text)");
Hope this will help u.


text:
Q: Can the lifespan of a returning temporary variable be extentended by using move/swap c++11 I have a tree which base node is (not all methods are shown):
struct node_base {
    node_base(): _size(0),_parent(NULL) { }
    virtual ~node_base() {}

    virtual node_iterator_base& begin() const =0;
    virtual node_iterator_base& end()  const=0;

protected:
    size_t _size;
    node_base* _parent;
};

From that abstract class you can derive child classes which implement the needed container to hold all child nodes.
As seen I also have a custom iterator node_iterator_base
struct node_iterator_base {
    virtual ~node_iterator_base() {}
    virtual node_iterator_base& operator++()=0;
    virtual node_base* operator->() const =0;
    virtual node_base& operator*() const =0;
    virtual bool operator==(const node_iterator_base& x) const =0;
    virtual bool operator!=(const node_iterator_base& x) const =0;
};
template<It>
struct derived_iterator: public node_iterator_base {
    derived_iterator(It I): ci(I) { }
    ...
    It ci;
}

The idea behind these base classes and their derived classes is to make it able to write something like this:
derived_node n;
for(node_iterator_base it=n.begin(); it!=n.end(); it++) {
    do_something(*it);
}

Now the problem is to implement begin in the derived class
node_iterator_base& derived_node::begin() const {
    return derived_iterator(container);
    //This will not work because a temporary variable is passed to a
    reference
}

What can be done instead? If we change the declaration of begin to
virtual node_iterator_base begin() const =0;

and
node_iterator_base derived_node::begin() {
    return derived_iterator(container);
   //This will not work either because node_iterator_base is an abstract struct
}

Of course I could return a pointer but then my iterator will not look like a STL iterator and will have to destroy it manually.
How can I return a reference? Can move/swap from C++11 help me?
More about my heterogeneous tree here
https://www.facebook.com/A-smart-tree-and-a-simple-parser-i-c-1678796648883396

A: The short answer is no.  You cannot do what you want.
The medium answer is yes.  You can use the pImpl pattern to pass a facade which holds a pointer to an interface within it; it forwards calls to its implementation interface (pImpl).  This permits a seeming value type like an iterator to be polymorphic, at the cost of dynamic allocation and indirection.
The longer answer is that you are attempting to type erase iteration by type erasing iterators.  You can do this with pImpl, or something like any or even std function.  However, the iterator interface of C++ has a large surface and is interacted with frequently during iteration.  Type erasure of iterators has proven expensive.  Boost has any iterators that have rolled this for you; they are not suited for use in performance sensitive code.
It may be better to type erase iteration operation itself instead of the iterators.  You iterate far less often than you interact with an iterator; by type erasing the less frequent operation you can improve performance significantly (or really, waste less).
Finally, consider using variant instead; if you can enumerate the subclasses, you could use that to give the compiler less indirection and more information.
Any and variant are available in boost or C++17 or can be reimplemented yourself.


text:
Q: var mqtt = require('mqtt'); that shows syntax error i am following this tutorial regardign saving data to database using mqtt to mysql sensor to mysql via mqtt where i am at the app_mqtt.js part where i try to follow the exact same thing to create the js file but when i try to run it via python, it shows an error of :
File "app_mqtt.js", line 1
var mqtt = require('mqtt');
   ^
SyntaxError: invalid syntax

I have already the mqtt via npm i mqtt and npm install mqtt --save yet it still have such an error, i really need help in this. Thank you.
var mqtt = require('mqtt');

var Topic = '#'; //subscribe to all topics

var Broker_URL = 'mqtt://192.168.1.123';

var options = {
    clientId: 'MyMQTT',
    port: 1883,
    keepalive : 60
};

var client  = mqtt.connect(Broker_URL, options);
client.on('connect', mqtt_connect);
client.on('reconnect', mqtt_reconnect);
client.on('error', mqtt_error);
client.on('message', mqtt_messsageReceived);
client.on('close', mqtt_close);

function mqtt_connect()
{
    console.log("Connecting MQTT");
    client.subscribe(Topic, mqtt_subscribe);
}

function mqtt_subscribe(err, granted)
{
    console.log("Subscribed to " + Topic);
    if (err) {console.log(err);}
}

function mqtt_reconnect(err)
{
    console.log("Reconnect MQTT");
    if (err) {console.log(err);}
    client  = mqtt.connect(Broker_URL, options);
}

function mqtt_error(err)
{
    console.log("Error!");
    if (err) {console.log(err);}
}

function after_publish()
{
    //do nothing
}

function mqtt_messsageReceived(topic, message, packet)
{
    console.log('Topic=' +  topic + '  Message=' + message);
}

function mqtt_close()
{
    console.log("Close MQTT");
}

A: As per your code , it shows fine.
1) Try to restart the server.
2) check your code to this code
npm i mqtt --save

var mqtt = require('mqtt')
var client  = mqtt.connect('mqtt://{Your connection string}')

client.on('connect', function () {
  client.subscribe('presence', function (err) {
    if (!err) {
      client.publish('presence', 'Hello mqtt')
    }
  })
})

client.on('message', function (topic, message) {
 // message is Buffer
 console.log(message.toString())
 client.end()
})

3) At last , re-install the package.
Note: If still issue , please share your code. So I can debug it.


text:
Q: Deformation of a ball when it falls on a rigid surface Suppose, we drop a rubber ball on the floor. The ball collides with the floor, comes to rest and often bounces back up to lower height. I'm trying to look at this from the force perspective, not energy or momentum.
The ball, on hitting the ground, gets deformed, and being elastic, exerts some force on the ground to get back to its original state. Hence, the ground provides a normal reaction greater than the weight, which gives the ball an upward acceleration causing it to bounce back up.
However, what compresses the ball in the first place ? There is some stress acting on the ball, but where does it originate ?
I like to think of it as, the lower surface of the ball comes to rest first, while the center of mass keeps moving due to inertia. This creates the stress, that deaccelerates the center of mass, till it comes to a halt. Is this the source of the compression stress ? I'm not sure.
There seems to be another explanation : when the ball drops on the ground, even when the reaction matches the weight, the ball has a downward velocity. Hence the ground must provide a force greater than the weight, to stop this velocity. This weight compresses the ball, which tries to retain its shape, and thus apply a greater force on the ground, which in turn leads to greater reaction and more compression until the ball stops. At this point, this total reaction accelerates it backwards i.e. upwards.
Are these two explanations equivalent ? If not, what is the correct explanation ? From a purely force perspective, where does the compressive stress originate. If I consider the ball to be something like a mass on a spring, that suggests the first explanation is correct.
I think the the second explanation is needlessly convoluted, and that the first explanation is the correct one. It is the inertia and the acceleration of the top of the ball relative to the lower half, that creates the compression, that ultimately increases the normal reaction, causing the ball to bounce back up.
Is this correct ?

A: Both of the effects you describe take place. The centre of mass of the ball does continue to move downwards after the lowest point of the ball has hit the ground, which means that the ball is deformed. The reaction force subjected by the ground is greater than the weight of the ball- it has to be in order to accelerate the ball. You should be able to see that intuitively, as it accounts for the fact that a ball simply at rest on the ground is not kicked in to the air by a normal force equal to its weight. The reaction force increases with the speed of incidence of the ball, which accounts for the fact that the height of a ball's bounce will depend upon the height from which it drops.


text:
Q: Print export popup box displaces text on the page In the application, the user can view charts such as the one below. It contains detailed information about what the lines represent:

Here is the code for the legend (text):

      LTD
      YTD

         "data"

         "data"

         "data"

         "data"

The issue is that whenever I use the print function, the print export popup box for some reason distorts the text in the chart. The popup is just the generic one that appears when you try to print anything on a page.

Does anyone know what could possibly be causing this to happen? When the print popup appears as a separate window altogether, so I do not believe that it should be affecting anything on the page.

A: While I did not figure out exactly the cause beyond it, I fixed the issue by doing this:
td { padding:0px; }


text:
Q: ERROR in node_modules/apollo-angular/Apollo.d.ts(26,17) I am working on Angular 7 project and the application is deployed in Azure App Services and Pipeline for the same in on Azure DevOps. It is basically CI/CD. Everything was fine, branch code merging (Code Integration) and deployment (Code Deployment - pipeline) but suddenly I am getting ERROR in node_modules/apollo-angular/Apollo.d.ts(26,17): error TS1086: An accessor cannot be declared in an ambient context this error.
Could somebody help me here to understand and solve the issue?
Apollo Angular version - 1.3.0

A: I encountered the same error.
I was using apollo-angular@1.9.0.
my way was like this
npm uninstall apollo-angular
npm install apollo-angular@1.8.0

i just got the minor version of apollo-angular down


text:
Q: Visual Studio Code - build Windows Phone on mac Is it possible to build Windows Phone projects using the new IDE, Visual Studio Code, for Mac?
Not looking for actual developing at this point, only to build & test the project. Something like a xbuild alternative, maybe. Reason is we already have a cruise control running on a Mac and right now it's a pain to also build Windows Phone projects.

A: No. Visual Studio Code does not include any build tools, only an editor and debugging support for (currently) Node.js applications.
More information here: https://code.visualstudio.com/Docs/languages


text:
Q: FAILED prompting authorization request to Heathkit We are facing an issue in HealthKit permission dialog. it works in IOS 13 but it is not prompt in IOS 14.6. Please help me.
Below is the code
 func requestHealthKitAuthorization() {
    let healthStore = HKHealthStore()
    let workoutType = HKObjectType.workoutType()
    let heartRateType = HKObjectType.quantityType(forIdentifier: .heartRate)
    let heartRateType1 = HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)
    let heartRateType2 = HKObjectType.quantityType(forIdentifier: .stepCount)
    let heartRateType3 = HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)

    //reading
    let readingTypes = Set([heartRateType!,heartRateType1!,heartRateType2!,heartRateType3!, workoutType])
    //writing
    let writingTypes = Set([heartRateType!,heartRateType1!,heartRateType2!,heartRateType3!, workoutType])
    //auth request
    healthStore.requestAuthorization(toShare: writingTypes, read: readingTypes) { (success, error) -> Void in

        if error != nil {
            print("error \(String(describing: error?.localizedDescription))")
        } else if success {
            print("success")
            //                    self.startButton.setEnabled(true)
        } else if !success {
            print("fail")

            //                    self.startButton.setEnabled(false)
        }
    }
}


text:
Q: AWS ECS Zuul routing I'm setting up Spring Cloud on AWS ECS but I have a problem with Zuul/Eureka. When I'm trying to hit endpoint "/api/second/service2" I see this error:
Caused by: com.netflix.client.ClientException: Load balancer does not have available server for client: service2
I'm using Elastic IP for Eureka instance as explained here https://github.com/Netflix/eureka/wiki/Deploying-Eureka-Servers-in-EC2 . I have 2 spring boot applications, and I see both of them in Eureka. I'm able to hit endpoint directly.

This is config for Eureka server:
server:
  port: 8761
eureka:
  client:
    fetchRegistry: false
    registerWithEureka: false
    eurekaServerURLContext: eureka
    region: eu-west-3
    eurekaServerPort: 8761
    useDnsForFetchingServiceUrls: true
    eurekaServerDNSName: my.dns
  datacenter: cloud

Service2:
spring:
  application:
    name: service2
server:
  port: 8882
eureka:
  datacenter: cloud
  instance:
    preferIpAddress: true
  client:
    fetchRegistry: true
    eurekaServerURLContext: eureka
    region: eu-west-3
    eurekaServerPort: 8761
    useDnsForFetchingServiceUrls: true
    eurekaServerDNSName: my.dns

Zuul:
pring:
  application:
    name: api-gateway
server:
  port: 8080
eureka:
  datacenter: cloud
  client:
    fetchRegistry: true
    eurekaServerURLContext: eureka
    region: eu-west-3
    eurekaServerPort: 8761
    useDnsForFetchingServiceUrls: true
    eurekaServerDNSName: my.dns

zuul:
  prefix: /api
  routes:
    first-service:
      path: /first/**
      serviceId: service1
    second-service:
      path: /second/**
      serviceId: service2

Do you have any idea where can be the problem?
EDIT:
It works only if I map my service2 instance port from 8882 to port 80

A: As I can see your service2 is not registered with eureka, like:
eureka:
  client:
    registerWithEureka: true

the rest of config is not needed, those are config for eureka server, and you shouldn't configure eureka server in any service, it is done in eureka service itself.
And it should fetch the registry, so in service2 you will have
spring:
  application:
    name: service2
server:
  port: 8882
eureka:
  client:
    registerWithEureka: true
    fetchRegistry: true

same goes for the rest of the services


text:
Q: Mongoose adding subdocument to array giving error _id: this.ownerDocument(...).model is not a function I have two schemas:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const _ = require("lodash");
const { regex } = require("../config/constants");
const { schemaErrors } = require("../config/errors");
const SiaSchema = require("./SiaModel");

const EmployeeSchema = new Schema(
    {
        first_name: {
            type: String,
            required: true,
            trim: true,
        },
        last_name: {
            type: String,
            required: true,
            trim: true,
        },
        mobile: {
            type: String,
            required: true,
            validate: {
                validator: function (v) {
                    return regex.uk.mobile.test(v);
                },
                message: schemaErrors.INVALID_MOBILE,
            },
            trim: true,
        },
        sia: [SiaSchema],
    },
    { timestamps: { createdAt: "created_at", updatedAt: "updated_at" } }
);

EmployeeSchema.statics.addSia = async function (data) {
    let options = { new: true, upsert: true, runValidators: true };
    let sia = Object.assign({}, data);
    delete sia._id;
    let orQuery = [];
    for (const attribute in sia) {
        orQuery.push({ [`sia.${attribute}`]: sia[attribute] });
    }
    let existing = await this.findOne({ $or: orQuery });
    if (existing) return Promise.resolve(existing);

    return this.findByIdAndUpdate(data._id, { $push: { sia: sia } }, options);
};

module.exports = EmployeeSchema; // I am not exporting mongoose model here because model creation for all schemas is being handled by another module

and
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const _ = require("lodash");
const { regex } = require("../config/constants");
const { schemaErrors } = require("../config/errors");
const SiaSchema = new Schema(
    {
        sia_number: {
            type: String,
            required: true,
            validate: {
                validator: function (v) {
                    return regex.uk.sia.test(v);
                },
                message: schemaErrors.INVALID_SIA_NUMBER,
            },
        },
        issue_date: {
            type: Date,
            required: true,
            validate: {
                validator: function (v) {
                    return v instanceof Date && v.getTime() < Date.now();
                },
                message: schemaErrors.INVALID_ISSUE_DATE,
            },
        },
        expiration_date: {
            type: Date,
            required: true,
            validate: {
                validator: function (v) {
                    return v instanceof Date && v > this.issue_date;
                },
                message: schemaErrors.INVALID_EXPIRATION_DATE,
            },
        },
    },
    { timestamps: { createdAt: "created_at", updatedAt: "updated_at" } }
);

module.exports = SiaSchema; // I am not exporting mongoose model here because model creation for all schemas is being handled by another module

I created an Employee. Then I called another API to add Sia for that Employee using the addSia static method defined in the Employee Schema, but it is giving me the following error:
"Validation failed: sia: Validation failed: _id: this.ownerDocument(...).model is not a function".
This is the body of the API and the data being passed as data param to the addSia method:
{
    "_id": "5f36cde0e4c4163838674219", // ID of the employee for whom I want to add sia
    "sia_number": "0000000000000000",
    "issue_date": "2020-08-01",
    "expiration_date": "2025-08-01"
}

If I remove runValidators: true from options in the addSia method, the function works but the validations are not applied.
I would greatly appreciate any help with this.
Node.js version 11.9.0
Mongoose version 5.9.28
Mongodb version 4.2.3


text:
Q: Looking for a format to improve my logs I have logs which are huge plain text file. In this log each line represent a message logged at a specific time, some message represent the beginning of a process, some other represent the end of the same processes.
thus I could have a log which looks like this.
<lot of lines>
26-01-2016 10:00:00 - START PROCESS XYZ
<lot of lines>
26-01-2016 11:00:00 - END PROCESS XYZ
<lot of lines>

I would like to be able to use a tool which would allow me to expand/collapse what's between "26-01-2016 10:00:00 - START PROCESS XYZ" and "26-01-2016 11:00:00 - END PROCESS XYZ". Of course that tool could rely on a specific format other than the current one.
I bet this pair <format, tool> already exist (maybe even in a lot of different flavours).
Can you suggest me about some?

A: Just use {}
Enclose the <lot of lines> part in brackets like these { }, and editors like notepad++ will allow you to fold up the section enclosed if you set the language of the file to a programming language.
See this picture to set a language in notepad++
https://malalanayake.files.wordpress.com/2013/09/notepad.png
Even better:
You can code-fold by a user-defined keyword,
see here


text:
Q: Why can't a PDO object be serialized? I am making a multi-threaded CLI-PHP application and need to serialize PDO object to pass it between work inside the thread, and wake it up from a sleeping thread using magic methods __sleep() and __wakeup(). However nor the PDO or mysqli extension supports it. The old mysql_*() api did this but it has been deprecated and removed.
<?php
    // Application
    $link = new PDO('mysql:host=localhost;port=3306;dbname=testdatabase', 'root', '');

    $obj = serialize($link);

well generate error

PHP Fatal error:  Uncaught exception 'PDOException' with message 'You
cannot ser ialize or unserialize PDO instances' in
W:\workspace\Sandbox\application.php:5 Stack trace:
#0 [internal function]: PDO->__sleep()
#1 W:\workspace\Sandbox\application.php(5): serialize(Object(PDO))
#2 {main}   thrown in W:\workspace\Sandbox\application.php on line 5

A: What's being done at http://php.net/manual/en/language.oop5.magic.php is creating a wrapper that can be serialized since the PDO link itself cannot be.
<?php
class Connection
{
    protected $link;
    private $dsn, $username, $password;

    public function __construct($dsn, $username, $password)
    {
        $this->dsn = $dsn;
        $this->username = $username;
        $this->password = $password;
        $this->connect();
    }

    private function connect()
    {
        $this->link = new PDO($this->dsn, $this->username, $this->password);
    }

    public function __sleep()
    {
        return array('dsn', 'username', 'password');
    }

    public function __wakeup()
    {
        $this->connect();
    }
}?>

The PDO object apparently does not keep the dsn, user, pwd after connecting, and so cannot be directly serialized.  But if you created a wrapper like in the example above, where you stored this information, you could serialize the wrapper. Then when you unserialize, it will create a new PDO object and reconnect by passing the credentials in from the wrapper to PDO.

A: A PDO object contains state that cannot be represented in the serialization format. For example, the PDO object contains an open connection to a database server.
If you were to try to deserialize a serialized PDO object, the __wakeup() method would have to reconnect to the database server. This would require that authentication credentials be stored in a readable manner in the serialized PDO object, which is a security no-no.
I worked on the Zend Framework's Zend_Db component a long time ago, and I deliberately designed the Zend_Db_Adapter object to not be serializable for this reason. Instances of Zend_Db_Table, Zend_Db_Table_Row, etc. could be serializable, but could not be "live" after deserialization until you assigned it a freshly connected Zend_Db_Adapter instance.
Also, there's no guarantee that the database server would be reachable at the time you deserialize the PDO object. It's unclear whether this means the deserialization would be considered "failed."
The same restrictions on serialization apply to other resources such as sockets or file handles.
See also Why isn't every type of object serializable?


text:
Q: I want to move something out of an initialisation list, how should I do it? Previously I had:
MyClass::MyClass() : myMember(VALUE,this,5,"etc.") { ... }

but I need to do some calculation of the values passed to myMember's constructor. How do I initialise myMember within the constructor body instead? I'm not sure if I should do it like this:
MyMember myMember(calculatedValue,this,5,"etc.");

A: All member initialisation occurs before the constructor body runs.  So if you did this:
MyClass::MyClass()
{
    myMember = MyMember(calculatedValue,this,5,"etc.");
}

it would be assignment, not initialisation.  So it won't work if MyMembers are not assignable (e.g. they have a private assignment operator).  It also won't work if myMember is declared as const.
You could, however, do something like this:
class MyClass {
public:
    MyClass() : myMember(calculate(VALUE),this,5,"etc.") {}

private:
    static int calculate(int x) { return x*3; }
};

or even something like this:
class MyClass {
public:
    MyClass() : myMember(createMember()) {}

private:
    static MyMember createMember(int x) {
        MyMember m;
        m.foo = 5;
        ...
        return m;
    }
};

Note that I've used static helper functions here, because using non-static member functions before the constructor has completed gets a little weird, in the general case.

A: If you assign the myMember member inside MyClass' constructor, you are really invoking MyMember's default costructor, then invoking the assignment operator.
If it's fine for you, then you just need to write:
MyClass::MyClass()
{
    myMember = MyMember(calculatedValue,this,5,"etc.");
}

otherwise, you need a different approach.