text:
Q: Update child state based on parent state react functional components Let's say we have a component Accordion that has an internal state isOpen, so you can close and open this component.
We now want to have a parent component that also has a state isOpen and has button. In this component, we have 2 times Accordion and we are passing to Accordion isOpen and we want that if the parent changes state isOpen Accordion accept this.
All component are functional components
 const Accordion = ({ isOpen: parentIsOpen = false }) => {
    const [isOpen, setIsOpen] = useState(parentIsOpen);
    const handleSetIsOpen = () => setIsOpen(!isOpen);
    return (

        I'm open: {isOpen}
        <button onClick={handleSetIsOpen}>toggle isOpen child</button>

    );
  };

  const MasterComponent = () => {
    const [isOpen, setIsOpen] = useState(false);
    const handleSetIsOpen = () => setIsOpen(!isOpen);
    return (

        <button onClick={handleSetIsOpen}>toggle isOpen parent</button>
        <Accordion isOpen={isOpen} />
        <Accordion isOpen={isOpen} />

    );
  };

In this case above Accordion will take on first render as the initial state parent isOpen prop. In case we press the button toggle isOpen parent we will change the parent state but children will not be updated.
To fix this we can use useEffect
  const Accordion = ({ isOpen: parentIsOpen = false }) => {
    const [isOpen, setIsOpen] = useState(parentIsOpen);
    const handleSetIsOpen = () => setIsOpen(!isOpen);

    useEffect(() => {
      if (parentIsOpen !== isOpen) {
        setIsOpen(parentIsOpen);
      }
    }, [parentIsOpen]);

    return (

        I'm open: {isOpen}
        <button onClick={handleSetIsOpen}>toggle isOpen child</button>

    );
  };

  const MasterComponent = () => {
    const [isOpen, setIsOpen] = useState(false);
    const handleSetIsOpen = () => setIsOpen(!isOpen);
    return (

        <button onClick={handleSetIsOpen}>toggle isOpen parent</button>
        <Accordion isOpen={isOpen} />
        <Accordion isOpen={isOpen} />

    );
  };

in this case, children will be properly updated when a parent changes isOpen state.
There is one issue with this:
"React Hook useEffect has a missing dependency: 'isOpen'. Either include it or remove the dependency array  react-hooks/exhaustive-deps"
So how to remove this issue that esLint is complaining and we do not want to put isOpen in this since it will cause bug.
in case we add isOpen into the array like this:
 useEffect(() => {
      if (parentIsOpen !== isOpen) {
        setIsOpen(parentIsOpen);
      }
    }, [parentIsOpen, isOpen]);

We will have then a situation where we will click on the internal button in accordion and update the internal state then useEffect will run and see that parent has a different state than the child and will immediately set the old state.
So basically you have a loop where the accordion will never be open then.
The question is what is the best way to update the child state based on the parent state?
Please do not suggest to put all-state in parent and pass props without child state. this will not work since both Accordions in this example have to have their own state and be able to open and close in an independent way, but yet if parent says close or open it should listen to that.
Thank you!

A: Actually I would say this is way to do it
 const Accordion = ({ isOpen: parentIsOpen = false }) => {
    const [isOpen, setIsOpen] = useState(parentIsOpen);
    const handleSetIsOpen = () => setIsOpen(!isOpen);

    useEffect(() => {
        setIsOpen(parentIsOpen);
    }, [parentIsOpen]);

    return (

        I'm open: {isOpen}
        <button onClick={handleSetIsOpen}>toggle isOpen child</button>

    );
  };

  const MasterComponent = () => {
    const [isOpen, setIsOpen] = useState(false);
    const handleSetIsOpen = () => setIsOpen(!isOpen);
    return (

        <button onClick={handleSetIsOpen}>toggle isOpen parent</button>
        <Accordion isOpen={isOpen} />
        <Accordion isOpen={isOpen} />

    );
  };

So just remove state check in a child component, let him update the state but since is updated with the same value it will not rerender or do some expensive behavior.
Tested it today and with a check, if states are different or without is the same, react takes care to not trigger rerender if the state that is updated is the same as before.

A: What you're saying not to suggest is in fact the solution I would offer… You'll need state to control isOpen for the parent component. Also, you should have separate methods in the parent that control state for each accordion, passed along to each accordion in props…
Not sure why you want separate state for the child components. I believe something like this would suffice.
const MasterComponent = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [isOpen1, setIsOpen1] = useState(false);
  const [isOpen2, setIsOpen2] = useState(false);

  const handleParentClose = () => {
    setIsOpen(false);
    setIsOpen1(false);
    setIsOpen2(false);
  }

  return (

      <button onClick={handleParentClose}>toggle isOpen parent</button>
      <Accordion isOpen={isOpen1} setIsOpen={setIsOpen1} />
      <Accordion isOpen={isOpen2} setIsOpen={setIsOpen2} />

 );
};

const Accordion = props => {
 return (

    I'm open: {props.isOpen}
    <button onClick={props.setIsOpen}>toggle isOpen child</button>

   );
  }

This doesn't include code for actual visibility toggle, but the state is there, including state that closes accordions on parent close.


text:
Q: FFMPEG: from jpg to avi it's ok, but with bad size and quality I have six .jpg images with a size 350x400 (WxH).
I want to turn them into an avi file of a good quality (but not too heavy) and with same dimensions
I'm doing:
/var/www/html/folder/ffmpeg/ffmpeg -y -r 0.5 -i myfolder/434420image%05d.jpg -vcodec mpeg4 -s qcif -r 0.5 myfolder/434420img_tmp.avi

And I'm having the avi file, but with a size of 127x142 and with a terrible resolution.
What am I doing wrong?
Thanks a lot

A: You could use -vcodec copy in the hope that it correctly sets the fourcc in the AVI header to the one used by MJPEG.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to download clear plot through rstudio? I plot in rstudio, cannot see the number in plot, then I download as bigger size.
Whatever the png or jpeg format, even size is 2048 pixels, still cannot read the number in plot.

How to solve this problem?

A: RStudio has known sizing issue of saving pictures plotted in the "plots" window. What I would do is to save the picture directly in code.
Refer to this SO question
In short, what you can do is:
png(filename = pathToYourOutputPNG)    # create a png device
plot()   # write your plotting functions here
dev.off()    # close the device


text:
Q: How to get facebook public events of a specific user? I want to fetch all events of my account or any specific user by its userid.. The below query returns null array.. What is the problem ? If any permission is required, from where i can change it ?
SELECT eid, name, pic, creator FROM event WHERE eid IN (SELECT eid FROM event_member WHERE uid=12345) AND creator=12345

A: Permissions

*

*To get events of the connected user: user_events,

*To get events of a friend of the connected user: friends_events,

*To get events of a random user: there is no permission, which means that you can't get his events.

The query
SELECT eid, name, pic, creator
  FROM event
 WHERE eid IN (SELECT eid FROM event_member WHERE uid=12345)
      AND creator=12345

What are you trying to get? This query fetches the events of a user who created an event AND participates to it. The thing is, when a user creates an event, he automatically participates to it.
Let me suggest you two queries:

*

*Get the events which a user participates to. This will include the events that the user has created.
SELECT eid, name, pic, creator
FROM event
WHERE eid IN (SELECT eid FROM event_member WHERE uid=12345)

*Only get the events which a user created:
SELECT eid, name, pic, creator
 FROM event
 WHERE creator=12345


text:
Q: Optimizing indexes for a dependent subquery in MySQL I have a query with dependent subqueries and would like to know Which fields should be indexed for maximum performance? The query (below) shows all orders of anyone with "smi" in their name, for example. The query is grabbing the customer name from the customer table by shared cust# in the orders and customer tables. I am pretty much stuck with this query as it is mostly auto-generated from a php development tool. So, given those constraints, which fields should be indexed to get the best performance?
SELECT *, (SELECT CONCAT(customers.last, ', ', customers.first)
FROM customers WHERE customers.cust_num = orders.cust_num) AS c_lastname
FROM orders WHERE (SELECT CONCAT(customers.last, ', ', customers.first)
FROM customers WHERE customers.cust_num = orders.cust_num) LIKE '%smi%'
ORDER BY order_id DESC LIMIT 0, 20

EXPLAIN gives me:
"1" "PRIMARY"   "orders"    "index" \N  "PRIMARY"   "4" \N  "20"    "Using where"
"3" "DEPENDENT SUBQUERY"    "customers" "eq_ref"    "PRIMARY"   "PRIMARY"   "4" "orders.cust_num"   "1" ""
"2" "DEPENDENT SUBQUERY"    "customers" "eq_ref"    "PRIMARY"   "PRIMARY"   "4" "orders.cust_num"   "1" ""

A: I would start by rewriting the query as:
SELECT o.*, c.last_name
FROM (SELECT cust_name, CONCAT(c.last, ', ', c.first) as c_lastname
      FROM customers c
      HAVING c_lastname LIKE '%smi%'
     ) c JOIN
     orders o
     ON o.cust_num = c.cust_num
ORDER BY order_id DESC
LIMIT 0, 20;

I don't think there is much you can do about the like, unless you really mean liike 'smi%' instead.
But, you can then create an index on orders(cust_num) for the join.  There isn't much you can do about the outer order by.

A: Seems like the query would be more straightforward like this:
SELECT o.*, CONCAT(c.`last`, ', ', c.`first`) AS cName
FROM orders AS o
INNER JOIN customers AS c ON o.cust_num = c.cust_num
WHERE c.`last` LIKE '%smi%' OR c.`first` LIKE '%smi%'
ORDER BY order_id DESC
LIMIT 0, 20

or, similar to Gordon's:
SELECT o.*, c.Name
FROM orders AS o
INNER JOIN (
    SELECT cust_num, CONCAT(`last`, ', ', `first`) AS Name
    FROM customers
    WHERE `last` LIKE '%smi%' OR `first` LIKE '%smi%'
) AS c ON o.cust_num = c.cust_num
ORDER BY order_id DESC
LIMIT 0, 20;

The first avoids a subquery, but the latter will reduce redundant CONCAT operations on orders for the same customer; which performs better may depend on the actual data in the table.
...and to echo Gordon, there is not much you can do about "%smi%"; MySQL doesn't index strings from the middle, so that leading wildcard basically eliminates the possibility of index use.


text:
Q: QuickLook/QLPreviewController PDF Text Annotation background becomes black and font becomes small I am Using QLPreviewController for editing the PDF. Everything is working properly but
if I add text annotation from the QLPreviewController and click on the done button it is working as expected I am getting the URL with edited PDF and if I do other changes for example add image annotation from outside of QLPreviewController and save that pdf using the code
   self.pdfDocument.write(to: self.pdfUrl)

and if I open that pdf in the QLPReviewController and tap on the previously added text then the text annotation background becomes Black and the font becomes small.
I have attached the video please check.
**Video Link : ** https://www.dropbox.com/s/m0ql1csr8pars3t/Issue_video.mov?dl=0
I have used the below code for pdf mark up
    func openPreview(_ url : URL){
        let previewController = QLPreviewController()
        previewController.isEditing = true
        previewController.delegate = self
        self.pdfUrl = url
        previewController.dataSource = self
        previewController.modalPresentationStyle = .overFullScreen
        self.present(previewController, animated: true, completion: nil)
    }

    extension ViewController : QLPreviewControllerDataSource,QLPreviewControllerDelegate{
    func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
        return 1
    }

    func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
        return self.pdfUrl as QLPreviewItem
    }

    func previewController(_ controller: QLPreviewController, editingModeFor previewItem: QLPreviewItem) -> QLPreviewItemEditingMode {
        return .updateContents
    }

    func previewControllerWillDismiss(_ controller: QLPreviewController) {

    }

    func previewController(_ controller: QLPreviewController, didUpdateContentsOf previewItem: QLPreviewItem) {
        DispatchQueue.main.async {
            self.pdfUrl = previewItem.previewItemURL
            self.setPDFFile()
            self.pdfDocument.write(to: self.pdfUrl)
        }
    }
}

func setPDFFile(){
    if let doc = PDFDocument(url: self.pdfUrl){
        self.pdfDocument = doc
        self.pdfView.document = doc
    }
}


text:
Q: How to update multiple Service References by creating a batch file? I have a project in VS 2010  which has multiple service references.
I want to update all of them at once using a batch file.
please help!!

A: As an alternative to using service references, you could consider configuring WCF services at runtime.
Some examples include:

*

*http://weblogs.asp.net/manishdalal/archive/2009/02/23/silverlight-servicereferences-clientconfig-alternatives.aspx

*Dynamic service reference in Silverlight


text:
Q: how to return a string from a function which is listening some stream in dart? i have a function called foo which is listening to the stdout, what i want is to return some string which i got from stdout. here is my function;
    dynamic foo(process) {
  return (
    process.stdout.transform(UTF8.decoder).listen((data) {
    String s = data.toString();
    // print(s);
    if (s.contains("received event of")) {
      var s1 = s.split(":");

      print("${s1[1]}");
      return s1[1];
    }
  }));
}

I want to return s1 to the calling function

A: here a callback function do the trick
 foo(process, callback) {
    process.stdout.transform(UTF8.decoder).listen((data) {
      String s = data.toString();
      if (s.contains("received event of")) {
        String message = s.split(":")[1];
        callback(message);
      }
    });
  }

and here i am calling the method and printing the data which i get get from stream.
foo(process,(data){print(data);})

A: This should do what you want
Future<String> dynamic foo(process) {
  return process.stdout.transform(UTF8.decoder).map((data) {
    String s = data.toString();
    // print(s);
    if (s.contains("received event of")) {
      var s1 = s.split(":");

      print("${s1[1]}");
      return s1[1];
    } else {
      return null;
    }
  }).where((val) => val != null).first;
}

Your custom code either returns a valid value or null.
I changed listen to map to be able to use additional stream methods.
where filters invalid values (null) and returns the first non-null value.
The caller of the foo method needs to handle the returned Future (using for example async/await) to get the value when it becomes available.
Use it like
bar() async {
  ...
  var input = await foo(proc);
  print(input);
}

A: I think that everybody wants this:
import 'dart:io';
import 'dart:convert';

// Using system encoding:
var outputStr = await process.stdout.transform(systemEncoding.decoder).join();

// Using UTF-8 encoding:
var outputStr = await process.stdout.transform(utf8.decoder).join();


text:
Q: Raw access of SPI Master in Linux Driver for SPI-device access I am in process of writing a Linux Driver that is required to control two SPI devices (on separate SPI masters) and one I2C device. For the I2C Device, I was able to abstract out the I2C-slave access by using equivalent of below code and control it in my Driver,
struct i2c_adapter *adap;
struct i2c_msg msg;

adap = i2c_get_adapter(<bus-ID>);
<define 'msg'>
i2c_transfer(adap, &msg, 1);
i2c_put_adapter(adap);

Are there any equivalent routines for getting the handle to SPI master and for performing Read/Write access on a connected SPI-slave? I know how to get one SPI handle in the driver using struct spi_device_id and struct spi_driver, but I do not know how to get access to two SPI devices belonging to different SPI masters in a single Driver.
I know that I may be missing something fundamental. Getting some code references will help a lot.


text: Q: Текущее время в WPF Надо выводить текущее время на экран, чтобы оно менялось в реальном времени. Единственный способ реализации, который я вижу — реализация через таймер. Конечно можно для этого также добавить свойство и реализацию INotifyPropertyChanged, но это никак не отменят того факта, что в недрах всё равно будет использоваться таймер. Есть ли варианты получше?


text:
Q: Split list by ID and store results into separate vectors Given a list, which I converted to a dataframe, providing the following structure:
df <- data.frame(list('value' = c(3.166667,3.166667,3.416667,3.291667,3.00,2.75), 'ID' = c(511,511,532,532,556,556)))

$value
[1] 3.166667 3.166667 3.416667 3.291667 3.000000 2.750000

$ID
[1] 511 511 532 532 556 556

I need to split my observations by ID into vectors. However, my attempt
X <- split(myList, myList$ID)

Results in the following structure:
$`511`
     value  ID
1 3.166667 511
2 3.166667 511

$`532`
     value  ID
3 3.416667 532
4 3.291667 532

$`556`
  value  ID
5  3.00 556
6  2.75 556

Whereas, I was hoping to get this structure (each row in the original df is a distinct variable)
$1
     value    ID
1    3.166667 511
3    3.416667 532
5    3.00     556

$2
     value    ID
2    3.166667 511
4    3.291667 532
6    2.75     556

How do I accomplish this? Thanks in advance

A: We can do this easily with rowid from data.table
library(data.table)
split(df, rowid(df$ID))
#$`1`
#     value  ID
#1 3.166667 511
#3 3.416667 532
#5 3.000000 556

#$`2`
#     value  ID
#2 3.166667 511
#4 3.291667 532
#6 2.750000 556


text:
Q: Sbt / javaAgents / force jar-with-dependencies I want to add "org.kohsuke" % "file-leak-detector" % "1.13"  java agent to my sbt configuration.
//plugins.sbt
addSbtPlugin("com.lightbend.sbt" % "sbt-javaagent" % "0.1.5")

//build.sbt
enablePlugins(SbtWeb, PlayScala, DebianPlugin, JavaAgent)
javaAgents += "org.kohsuke" % "file-leak-detector" % "1.13"

but this failed at runtime.
Failed to find Premain-Class manifest attribute in /usr/share/someApp/bin/../file-leak-detector/file-leak-detector-1.13.jar
Error occurred during initialization of VM
agent library failed to init: instrument

I've found that i need jar with dependencies to run it as javaAgent but event if I theoretically could download it from https://repo1.maven.org/maven2/org/kohsuke/file-leak-detector/1.13/
I don't know how to use it with sbt-javaagent plugin.
I have tried also:
javaAgents += ("org.kohsuke" % "file-leak-detector" % "1.13") from "https://repo1.maven.org/maven2/org/kohsuke/file-leak-detector/1.13/file-leak-detector-1.13-jar-with-dependencies.jar"

but without luck. Any ideas how to force sbt-javaagent plugin to use file-leak-detector-1.13-jar-with-dependencies.jar instead of file-leak-detector-1.13-jar?

A: I think you are doing the right thing using from to provide explicit URL

If your project requires a dependency that is not present in a
  repository, a direct URL to its jar can be specified as follows:
libraryDependencies += "slinky" % "slinky" % "2.1" from "https://slinky2.googlecode.com/svn/artifacts/2.1/slinky.jar"

It seems to work on my machine when I provide explicit scope like so
javaAgents += JavaAgent(
  "org.kohsuke" % "file-leak-detector-1.13-jar-with-dependencies" % "1.13" % Runtime from "https://repo1.maven.org/maven2/org/kohsuke/file-leak-detector/1.13/file-leak-detector-1.13-jar-with-dependencies.jar",
  arguments = "help"
)

Note % Runtime. I think it works because arguments = "help" is honoured and sbt run outputs
sbt:sbt-javaagents-leka> run
[info] running (fork) example.Hello
[error] File leak detector arguments (to specify multiple values, separate them by ',':
[error]   help          - show the help screen.
[error]   trace         - log every open/close operation to stderr.
[error]   trace=FILE    - log every open/close operation to the given file.
[error]   error=FILE    - if 'too many open files' error is detected, send the dump here.
[error]                   by default it goes to stderr.
[error]   threshold=N   - instead of waiting until 'too many open files', dump once
[error]                   we have N descriptors open.
[error]   http=PORT     - Run a mini HTTP server that you can access to get stats on demand
[error]                   Specify 0 to choose random available port, -1 to disable, which is default.
[error]   strong        - Don't let GC auto-close leaking file descriptors
[error]   listener=S    - Specify the fully qualified name of ActivityListener class to activate from beginning
[error]   dumpatshutdown- Dump open file handles at shutdown
[error]   excludes=FILE - Ignore files opened directly/indirectly in specific methods.
[error]                   File lists 'some.pkg.ClassName.methodName' patterns.

Also if I set arguments = "threshold=1" it outputs
[info] running (fork) example.Hello
[error] File leak detector installed
[error] 2 descriptors are open
[error] #1 /private/var/folders/y7/33z7gnqn1nl2vwzn26j59xy9rwcgwx/T/sbt_412c7765/target/edca7f33/f7a642d3/scala-library-2.13.1.jar by thread:main on Mon Apr 20 11:51:20 BST 2020
...


text:
Q: WindowManager animation with "WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY" property in accessibility service I am developing an application which has Accessibility service. With this service I will do my back end functionality(button clicks and navigating to other screens) by showing a window manager screen on top. In this window manager screen I need to add any animation(in worst case, I have to add a simple progress bar). My issue is,
1) If I add WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY (For Lollipop and below) OR WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY (For Marshmallow and above) property to window manager, I am successfully completing back end functionality but animation is hanging. It is occurring for simple progress bar also.
2) If I add WindowManager.LayoutParams.TYPE_PHONE to window manager, I am successfully showing animation but back end functionality is not working.
Any minor help is appreciable. Thanks in advance.

A: The difficulty in accessibility services with adding views is getting the correct permissions. Your approach on approach one is correct. The performance issues in such animations area an unrelated issue. Once a view has been successfully added to the window manager any concerns with view performance are similar to concerns as if you were in the context of an activity. Unless, you have some type of memory leak, view leak, etc. Adding overlay views to the window manager directly is prone to mismanagement, because you also have to remove those views yourself. Otherwise old instances of overlays will stick around forever and bog down performance.
Stick with option one from your services point of view and figure out your performance issues outside of the scope of this decision. They are only indirectly related. Your performance problem is not directly caused by this decision, but rather mistakes elsewhere. What these could be I can only provide a speculative answer on.


text:
Q: Export to .CSV in Node.js I have an app that takes information from an indeed.com search result. The code returns each url from the search result and makes an array of all the information in each url. At least I think it does. The result is supposed to be a .CSV file with the result from the query. here is the code.
const axios = require('axios')
const cheerio = require('cheerio')
const express = require('express')
const app = express()
const articles = []
const articlesB = []
const url1 = 'https://www.indeed.com/jobs?q=biotechnology&l=Frederick%2C%20MD&from=searchOnHP&vjk=35cd4f4f40383593'

const fastCsv = require("fast-csv");
const fs = require("fs");
const ws = fs.createWriteStream("data.csv");

getUrl()
function getUrl() {
        axios(url1)
            .then(response => {
                const html = response.data
                const $ = cheerio.load(html)

                $('.jcs-JobTitle', 'li', html).each(function () {
                    let Title = $(this).attr('href')
                    Title = 'https://www.indeed.com'+Title
                    articles.push({
                        Title,
                    })
                })
                getJobs(articles)
            }).catch(err => console.log(err))
}

function getJobs(urls){
    let num = 1
    urls.forEach(element => {
        axios(element.Title)
            .then(response => {
                const html = response.data
                const $ = cheerio.load(html)

                $('h1', html).each(function () {
                    const Text = $(this).text()
                    articlesB.push({
                        Text,
                    })
                })
                $('h2', html).each(function () {
                    const Text = $(this).text()
                    articlesB.push({
                        Text
                    })
                })
                $('p', html).each(function () {
                    const Text = $(this).text()
                    articlesB.push({
                        Text
                    })
                })
                let jsonData = []
                console.log(num++ +'-'.repeat(99)) // Separator
                articlesB.forEach(items=>{
                    jsonData = ((items.Text))
                    console.log(jsonData)
                })
                console.log('-'.repeat(100)) // Separator
                writeToCsv(JSON.stringify(jsonData))

            }).catch(err => console.log(err))

    })

}

function writeToCsv(jsonData){
    fastCsv
        .write(jsonData, { headers: true })
        .on("finish", function() {
            console.log("Write to CSV successfully!");
        })
        .pipe(ws);
}

app.listen(PORT, () => console.log("server running on PORT " + PORT))

however it returns this error:
TypeError: rows.reduce is not a function
I believe the problem is that I am not making a proper array. Please enlighten me on what I am doing wrong.
Edit, this is what the code is currently like.
const PORT = 8000
const axios = require('axios')
const cheerio = require('cheerio')
const express = require('express')
const app = express()
const articles = []
const articlesB = []
const url1 = 'https://www.indeed.com/jobs?q=biotechnology&l=Frederick%2C%20MD&from=searchOnHP&vjk=35cd4f4f40383593'

const fastCsv = require("fast-csv");
const fs = require("fs");
const ws = fs.createWriteStream("data.csv");

getUrl()
function getUrl() {
        axios(url1)
            .then(response => {
                const html = response.data
                const $ = cheerio.load(html)

                $('.jcs-JobTitle', 'li', html).each(function () {
                    let Title = $(this).attr('href')
                    Title = 'https://www.indeed.com'+Title
                    articles.push({
                        Title,
                    })
                })
                getJobs(articles)
            }).catch(err => console.log(err))
}

function getJobs(urls){
    let num = 1
    urls.forEach(element => {
        axios(element.Title)
            .then(response => {
                const html = response.data
                const $ = cheerio.load(html)

                $('h1', html).each(function () {
                    const Text = $(this).text()
                    articlesB.push({
                        Text,
                    })
                })
                $('h2', html).each(function () {
                    const Text = $(this).text()
                    articlesB.push({
                        Text
                    })
                })
                $('p', html).each(function () {
                    const Text = $(this).text()
                    articlesB.push({
                        Text
                    })
                })
                let jsonData = []
                console.log(num++ +'-'.repeat(99)) // Separator
                const data = articlesB.map(el => el.Text);
                /*articlesB.forEach(items=>{
                    jsonData = ((items.Text))
                    console.log(jsonData)
                })*/
                console.log('-'.repeat(100)) // Separator
                writeToCsv(data)

            }).catch(err => console.log(err))

    })

}

function writeToCsv(jsonData){
    fastCsv
        .write(jsonData, { headers: true })
        .on("finish", function() {
            console.log("Write to CSV successfully!");
        })
        .pipe(ws);
}

app.listen(PORT, () => console.log("server running on PORT " + PORT))


text:
Q: plugin-based applications with plugins that modify other plugins I am taking a look at how to build modular, plugins-based applications in C#.
I am reading about Prism and MEF (that I've already used in some projects of mine).
All examples and articles that I found talk about discrete modules. My question is just about this. Let's say that one of the modules doesnt provide new views, but it "simply" needs to alter an existing view, which is provided by a different module, by adding one or more fields and some further logic. How would you do that?
Would it be a good approach to check at the composition-time which other parts are present in the catalog, and programmatically modify them?
I can think of this as a possible solution if there is a "module 1" and a "module 2" that changes something in "module 1". But if the scenario gets far more complex? for example if we have a basic "module 1" that has to be modified by "module 2" and "module 3", but also it exists a "module 4" that modifies the UI and logic provided by "module 2", and so on... ?
Could you advice me on how this can be realized?
Thanks in advance,
Cheers,
Gianluca

A: From your example I infer that you have exports that look a little bit like this, for which you do an [ImportMany] somewhere:
[Export(typeof(IView))]
public class BarView : IView
{
    ...
}

Suppose one particular view implementation needs to be pluggable itself. Then you could do something like this:
[Export(typeof(IView))]
public class FooView : IView
{
    [ImportMany(IFooViewPlugin)]
    public IEnumerable<IFooViewPlugin> Plugins { get; set; }

    ...
}

Of course, it is still up to you to shape IFooViewPlugin and decide how FooView invokes it to customize itself. That depends on what kind of customizations you had in mind.

A: You can have the host application expose the collection of plugins via say a "Plugins" property. Then your plugin can iterate through the plugins collection till you find one of the right type and then modify it.
For security, you may want to add some test code in the plugin being modified (say set a password) to prevent modifications by unwanted plugins.


text:
Q: Facebook plugin - Recommendations images Is it possible to display only the images from the Facebook recommendations plugin?
Thanks,
Uli
P.S. Why the down vote?

A: no it is not possible as I don't see that option currently for the Facebook recommendations plugin.


text:
Q: What is this notation called; $[\vec v]_B$? Let us say we have a vector $\vec v$, I have seen in numerous places the notation $[\vec v]_B$ used to  denote the vector $\vec v$ written in a particular basis $B$. With analogous notation been used for matrices. Does this notation have a particular name?

A: I would say it's just "coordinates with respect to a basis".


text:
Q: How to install Emgu.cv xamarin forms My question is simple i want to install emgu.cv in xamarin forms via nuget package but it return me error.
Error   NU1202  Package ZedGraph 5.1.7 is not compatible with xamarinios10 (Xamarin.iOS,Version=v1.0) / win-x64. Package ZedGraph 5.1.7 supports: net35-client (.NETFramework,Version=v3.5,Profile=Client)  App19.iOS

Error   NU1202  Package ZedGraph 5.1.7 is not compatible with monoandroid90 (MonoAndroid,Version=v9.0). Package ZedGraph 5.1.7 supports: net35-client (.NETFramework,Version=v3.5,Profile=Client)   App19.Android   C:\Users\bonka\source\repos\App19\App19\App19.Android\App19.Android.csproj  1


text:
Q: In a given series, counting the number of times a value appear before and after, a given number Editing Question that it May be helpful to others in future.
In a given series of Numbers, Values appearing before and after a given number is to be allocated to their respective Tables as can be seen in the Images attached.
The Number Series is as follows. I.e. 5 Being the first number to be inputted, and 3 Being the last. Hence 4 Is Before 2 and 3 Is after 2.

Series
      3
      2
      4
      8
      0
      8
      7
      3
      8
      7
      0
      0
      4
      9
      6
      3
      9
      7
      4
      5

A Gist of Code that was being used:
'Private Sub CommandButton1_Click()

  Dim cell As Variant

  myrange = Range("B1:B30").Value

  For each cell in myRange

  if (cell=range("H2")) then

  'save the value of current cell if it matches

   range("h3")=cell.offset(1,0)

  if (cell.offset(1,0) = range("h3"))

     'Count offset value (Value in cell.offset(1,0)) each time it appears before current cell (cell as in cell in my range)
 endif

     end if
    next cell
     end sub

The example is a shortened version of what was being done. A more efficient method is welcomed.

Thanks in advance. :)
Edit: added Expected Output Snippet

A: Sub Tester()
Dim arr, r, b, a

    arr = Range("A1:A20").Value
    Range("D4").Resize(10, 10).ClearContents
    Range("D17").Resize(10, 10).ClearContents

    For r = 1 To UBound(arr, 1) - 1
        b = arr(r, 1)
        a = arr(r + 1, 1)

        With Range("D4")
            .Offset(b, a).Value = .Offset(b, a).Value + 1
        End With

        With Range("D17")
            .Offset(a, b).Value = .Offset(a, b).Value + 1
        End With

    Next r

End Sub

A: Now that I know 'before & after' are defined the opposite of what I assumed, I changed the code to generate the correct results.
Option Explicit

Private Sub CommandButton1_Click()
Dim ws          As Worksheet
Dim lLastRow    As Long
Dim lRow        As Long

    Set ws = ActiveWorkbook.Sheets("BefAfter")
    ws.Activate

    ' Get last row number
    lLastRow = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

    ' Clear BEFORE counts
    Range("H3:Q12").Select
    Selection.ClearContents

    ' Clear AFTER counts
    Range("H18:Q27").Select
    Selection.ClearContents

    For lRow = 2 To lLastRow
        ' Get all the after #'s
        If lRow > 2 Then
            ws.Cells(18 + ws.Cells(lRow, 2), 8 + ws.Cells(lRow - 1, 2)) = ws.Cells(18 + ws.Cells(lRow, 2), 8 + ws.Cells(lRow - 1, 2)) + 1
        End If

        ' Get all the before #'s
        If lRow < lLastRow Then
            ws.Cells(3 + ws.Cells(lRow, 2), 8 + ws.Cells(lRow + 1, 2)) = ws.Cells(3 + ws.Cells(lRow, 2), 8 + ws.Cells(lRow + 1, 2)) + 1
        End If
    Next lRow

    'MsgBox "Finished"
End Sub


text:
Q: Build a dynamic nav bar that reads from array using Angular2+? I have a top nav and a side nav. Every side nav tab has a different set of top navs that all follow the same format. Instead of making a new top nav component page for each side nav tab, how do I populate the top nav based off an id or something that is respective to an array of values?
I know how to manually make a top nav, but I want the template to be the same, looping through the array creating a top nav element for each element in the array.
I am using angular5, so no jquery please :) Typescript would be great!
Thanks!

A: What you should to do is passing the right data on every click of the side nav, so the top nav will be updated with the correct data.
Your parent component  should contain all arrays and you should pass these arrays to the top nav on every click of the side nav.
you can intercept the click of the side nav by using event emitter and @Output annotation
home-page.component.ts
     export class HomePageComponent implements OnInit {

                  private navbartitles :string[];
                  private navbarlinks :string[];

                  sideNavClicked(sideNavId) {
                    // You should make a list of data for every side nav
                    // You have also to make a condition using the sideNavId and pass the correct
                    // data on every side nav click
                    // the data below will be passed to the top nav bar component
                  if(sideNavId === 'firstSideNav') {
                  this.navbartitles= ['title1','title2','title3'] ;
                  this.navbarlinks= ['link1','link2','link3'] ;}
                    }
                }

the home page html should contain both top nav and side nav components and side nav should emit click events.
home-page.component.html
<app-my-side-bar (sideNavBarClicked)='sideNavClicked($event)'></app-my-side-bar>
<app-my-top-bar [navbartitles]="navbartitles" [navbarlinks]="navbarlinks"></app-my-top-bar>

And finally your top nav bar should just display the data passed by HomePageComponent
my-top-bar.component.ts
export class MyTopBarComponent implements OnInit {
  @Input() private navbartitles :string[];
  @Input() private navbarlinks :string[];
}

my-top-bar.component.html
nav class = "navbar navbar-default" role = "navigation">

     {{title}}


text:
Q: IE webpage you are viewing is trying to close the window message I have 3 webpages. They use the same ascx. I have a button on ascx called "send message". When I click that out of 3 pages 2 pages close up without the message. The other one shows up this warning. There is nothing majorly different in 3 pages except the properties I pass to ascx. When I test in chrome,firefox and safari the 3 pages close without warning . On IE 2 close without warning and 1 shows up warning. What is going on?

A: Nevermind found the solution.
   function closeWindow() {
        window.open('', '_self', ''); //added this line and it worked
        window.close();
    }

It now closes after sending message without the warning message


text:
Q: Как редактировать элемент QComboBox? Всем,привет! Подскажите, пожалуйста, как  я могу отредактировать элемент из списка QComboBox? Я подумал что можно было бы обработать событие клика на какой нибудь
из элементов внутри списка, но как это сделать и можно ли вообще так делать не знаю


text:
Q: Speed up deepcopy for new type Question: I have a new type type MyFloat; x::Float64 ; end. I want to perform a deepcopy on a Vector{MyFloat}. Using Julia v0.5.0 on Ubuntu 16.04, the operation runs roughly 150 times slower than a deepcopy call on an equivalent length Vector{Float64}. Is it possible to speed up a deepcopy on my Vector{MyFloat}?
Code snippet: The 150 times slowdown can be seen with the following code snippet which can be pasted to the REPL:
#Just my own floating point type
type MyFloat
    x::Float64
end

#This function performs N deepcopy operations on a Vector{MyFloat} of length J
function f1(J::Int, N::Int)
    v = MyFloat.(rand(J))
    x = [ deepcopy(v) for n = 1:N ]
end

#The same as f1, but on Vector{Float64} instead of Vector{MyFloat}
function f2(J::Int, N::Int)
    v = rand(J)
    x = [ deepcopy(v) for n = 1:N ]
end

#Pre-compilation step
f1(2, 2);
f2(2, 2);

#Timings
@time f1(100, 15000);
@time f2(100, 15000);

On my machine this produces:
julia> @time f1(100, 15000);
  1.944410 seconds (4.61 M allocations: 167.888 MB, 7.72% gc time)

julia> @time f2(100, 15000);
  0.013513 seconds (45.01 k allocations: 19.113 MB, 78.80% gc time)

Looking at the answer here it sounds like I can speed things up by defining my own copy method for MyFloat. I've tried things like:
Base.deepcopy(x::MyFloat)::MyFloat = MyFloat(x.x);
Base.deepcopy(v::Vector{MyFloat})::Vector{MyFloat} = [ MyFloat(y.x) for y in v ]
Base.copy(x::MyFloat)::MyFloat = MyFloat(x.x)
Base.copy(v::Vector{MyFloat})::Vector{MyFloat} = [ MyFloat(y.x) for y in v ]

but this doesn't make any difference.
Final note: Letting a = MyFloat.([1.0, 2.0]), I could just use b = copy(a) and there is no speed penalty. This is fine, as long as I am careful to only ever do operations like b[1] = MyFloat(3.0) (which will modify b but not a). But if I get sloppy and accidentally write b[1].x = 3.0, then this will modify both a and b.
By the way, it is entirely possible that I do not have a deep understanding of the differences between copy and deepcopy... I have read this great blog post (thanks @ChrisRackauckas), but I'm certainly a bit fuzzy about what is happening at a deeper level.

A: Try changing type MyFloat in the definition to immutable MyFloat or struct MyFloat (the keyword changed in 0.6). This makes the times almost equal.
As @Gnimuc mentioned, a mutable, which is not a bitstype, makes Julia keep track of a lot of other stuff. See here and in the comments.


text:
Q: Using A Different Regex Engine in Python Python uses the "Python" regex engine re; this implementation is very slow.  I want to try and use the ECMAScript implementation of regex in my python code... is there a way to do this?  Here's my regex that finds IPv4 and IPv6 addresses:
(?:(?:(?:[0-9A-Fa-f]{1,4}:){6}[0-9A-Fa-f]{1,4})|(?:[0-9A-Fa-f]{1,4}::(?:[0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(?:(?:[0-9A-Fa-f]{1,4}:){2}:(?:[0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(?:(?:[0-9A-Fa-f]{1,4}:){3}:(?:[0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(?:(?:[0-9A-Fa-f]{1,4}:){4}:(?:[0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(?:(?:[0-9A-Fa-f]{1,4}:){5}:(?:[0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(?:(?:[0-9A-Fa-f]{1,4}:){6}:(?:[0-9A-Fa-f]{1,4}:){0}[0-9A-Fa-f]{1,4})|(?:(?:[0-9A-Fa-f]{1,4}:){1,6}[0-9A-Fa-f]{1,4}::)|(?:(?:[0-9A-Fa-f]{1,4})::)|(?:::(?:[0-9A-Fa-f]{1,4}:){1,6})[0-9A-Fa-f]{1,4}|(?:::(?:[0-9A-Fa-f]{1,4})))(?!\:)|(?<!\.)(?:(?<![0-9])(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?![0-9]))(?!\.)

It may be able to be optimized further (suggestions are welcome) but, when I put it into regex101.com with some beefy test data, it becomes quickly apparent that EMCAScript is much faster than the Python version...

Implementing the Python flavor in Python is as simple as "import re"
What are the steps to implementing the ECMAScript (JavaScript)  flavor that is fast enough (505.2ms) to run my code
The Python version takes around 3 seconds to run!
I am trying to implement the ECMAScript version into python


text:
Q: Fused Location Provider with PRIORITY_HIGH_ACCURACY returns locations with low accuracy I am developing an app that tracks the locations of the device. Everything was fine and working as expected. Google now recommends using the new Fused Location Provider.
With this I now from time to time get Positions with an accuracy > 500m that also are fairly off the track. This in an urban area with good visibility to the sky - so GPS is usable (and works with the android location provider without problems).
So my question is:
How to limit the location-updates to results with the requested accuracy?

A: If you want high accuracy location to your application, you should create a location request with setPriority(int) set to PRIORITY_HIGH_ACCURACY and setInterval(long) to 5 seconds. Make sure also that your phone's location priority is high accuracy. FusedLocation API may be accurate for general location applications but it is not accurate enough for real time tracking.
Check this SO question which might help.


text:
Q: Returning Nothing in Oracle Function I created function in oracle and I've noticed that its returning nothing/empty string.
Oracle Function
CREATE OR REPLACE function UDF_GET_STATUS(P_ID in NUMBER)
return NVARCHAR2 is

  l_status NVARCHAR2(25);

begin

select case
             when exists(select ID, STATUS
                         from  Transaction
                         where ID = P_ID AND STATUS = 1)
             then 'APPROVED'
             else 'FOR  APPROVAL'
             end into l_status
             from Transaction WHERE ID = P_ID;

  return l_status;

end;

Did I missed something? Please advice..
Thanks,

A: This is most likely caused by you having no result that matches your query. Oracle will allow your function to return but will return a NULL result.
A NO_DATA_FOUND exception is raised in PL/SQL but it's not propogated through to your SQL. I would guess that the ID you're passing to your function does not exist in your table. Please see my answer here for an explanation.
You function is a little strange anyway. You're doing two scans of TRANSACTION, which isn't required. As you're not returning any data from your table I would use an aggregate query, which always returns one row and so doesn't exhibit the same behaviour:
create or replace function UDF_GET_STATUS( P_ID in number
      ) return nvarchar2 is

  l_status number;

begin

   select count(*) into l_status
     from transaction
    where id = P_ID
      and status = 1
      and rownum < 2
          ;

   if l_status = 0 then
      return 'FOR  APPROVAL';
   else return 'APPROVED';
   end if;

end;
/

As your query is an EXISTS you only need one row that fulfills the condition so you can use ROWNUM to limit the results you might get.
It's also a little curious that you're returning a NVARCHAR2 here...


text:
Q: derivative of a blured function to blur a function $f(x)$ you convolve it with $e^{-x^2}$
so the convolution = $f(x) * e^{-x^2}$
then I want to find its derivative so
derivative of convolution = $f(x) * (-2xe^{-x^2})$
derivative of convolution = $\int f(y)(-2(x-y)e^{-(x-y)^{2}})dy$
and $f(x) = e^{ae^{cx+d}+b}$ so the final equation to solve is
$\int e^{ae^{cx+d}+b}(-2(x-y)e^{-(x-y)^{2}})dy$
is there a way to solve or get an aproximate solution?
I want to solve various integrals with longer f(x) but similar
some tips on how to solve this will help me find a general solution to those problems


text:
Q: Magento brand page based on attribute I want to be able to have a page on Magento which will be a sub category of the parent category. This page needs to be a brand page but based on the brand attribute with my configuration.
It will need to work kind of the same way the layered navigation would on a normal category page. However I need the page to only show the brands attribute that are assigned to products within the parent category and all other sub categories with images that I will assign to each attribute.
Once you click on one of the brands it would act the same as clickng the brand on a normal category page in the layered navigation.
I have been looking around for a way to do this but can't seem to find any so hoping someone can help out.

A: Solution 1:

*

*add a new attribute to categories : brand_to_display where you can
save the brand value

*add all products to said categories

*find where the product collection is loaded for the category view
and chack if brand to display is set, if so add an
"addAttributeToFilter" on your collection

Solution 2 (better shop performance):

*

*add a new attribute to categories : brand_to_display where you can
save the brand value

*add an event listener for saving product data in admin area and before save find the categories that have brand_to_display = product->getBrand() and attach product to said categories


text:
Q: Customise action bar of tabbed page to put search bar in xamarin.forms (Android). I am working in xamarin.forms. I want to put search button with search Entry in the action bar. I found one link which is perfect for the Content page but In my case, There is a tabbed page and its not working.
http://blog.xhackers.co/xamarin-forms-contentpage-with-searchbar-in-the-navigation-bar/
can anyone help me to find the solution?
I need to implement in Android


text:
Q: macOS terminal login user name is a sequence of alphabets&numbers Every time when you login to the terminal, at the most lefthandsside, you should see your login name with YOUR_NAME@BLABLA $
However, when I am at home, it will be yuminsMBP:~ and every time when I am at university, the login name is a sequence of alphabets,number and special characters. And I can always see, every time I open the terminal, the first line need about 1 second to show up, it seems like terminal try to compute something or are running some process.
I don't understand why, and can not remember what I have done. Maybe it is because I installed anaconda last year? It is too far away, until today my friend said my login looks super weird, I started to think about this problem.
Do you know what I have done to my mac?
My .bashrc looks like:
Add RVM to PATH for scripting. Make sure this is the last PATH variable change.
export PATH="$PATH:$HOME/.rvm/bin"
My .bash_profile looks like:(I only provide things I think weird.)
blabla...
source ~/.rvm/scripts/rvm
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"
Load RVM into a shell session as a function
blablabla....
MacPorts Installer addition on 2017-12-03_at_18:01:33: adding an appropriate PATH variable for use with MacPorts.
export PATH="/opt/local/bin:/opt/local/sbin:$PATH"
Finished adapting your PATH environment variable for use with MacPorts
blablabla...
Best,
Yumin

A: The most likely cause is that you have something in your bash_profile that is causing the change. To check this open the .bash_profile file in your user home directory. One way of doing this is by opening terminal and running cat ~/.bash_profile you might also need to check your .bashrc file if your bash_profile sources it.
Without further information there is no real way tell what your specific issue is.


text:
Q: Solution to a problem I came across a question in a book titled "An introduction to Generalized Linear Models" which is given below

By adding $-\mu$ and + $\mu$, I found the solution to (b) as $S^2 = \frac{1}{n-1}[ \sum_{i=1}^{n}(Y_i-\mu)^2 + n(\bar Y - \mu )^2]$
The only difference is +. What do you think I am doing wrong?
Here is my work

Hint: $\sum_{i=1}^n (Y_i -\mu)=0$


text:
Q: Is it not possible to set expectations on a lazy property? The following test yields a NullPointerException. Is it not possible to set expectations on a lazy property?
class GarbTest {
    @Test
    fun xx(){
        val aa = Mockito.mock(AA::class.java)
        Mockito.`when`(aa.bb).thenReturn("zz")
    }

    open class AA(){
        val bb by lazy { "cc" }
    }
}

A: In your example, AA.bb is final. final/private/equals()/hashCode() methods cannot be stubbed/verified by Mockito. You need to mark bb as open:
open class AA(){
    open val bb by lazy { "cc" }
}

You might also consider using nhaarman/mockito-kotlin: Using Mockito with Kotlin. e.g.:
class GarbTest {
    @Test
    fun xx() {
        val aa = mock<AA>() {
            on { bb } doReturn "zz"
        }
    }

    open class AA() {
        val bb: String = "cc"
    }
}


text:
Q: "java.lang.ClassNotFoundException" when executing Java code when running in terminal I am trying run a basic code for Jdbc on my linux terminal.I have sqlplus installed.The version is Oracle 11.2.0.2.Everytime i run the code i get the following errors:
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at jdbcdisplay.main(jdbcdisplay.java:17)

Now i have seen the other questions asked here and most of them are connecting to Jdbc drivers using Eclipse and downloading the the jar file seems enough.But if i had to run it in the terminal how would i do it?Would i have to download http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html or is other any other way i can do it.My code is as follows:
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.Date;
import java.sql.SQLException;

class jdbcdisplay
{
public static void main(String[] args)
{
    Connection conn=null;

    try
    {
        String driver="oracle.jdbc.driver.OracleDriver";
        Class.forName(driver);

        System.out.println("Connecting to database...");
        String jdbcUrl="jdbc:oracle:thin:@localhost:1521:orcl";
        String user="Sourajyoti";
        String password="Sourajyoti7";

        conn=DriverManager.getConnection(jdbcUrl,user,password);
        Statement stmt=conn.createStatement();
        String sql="SELECT ENAME,SAL,HIREDATE FROM EMP";
        ResultSet rs=stmt.executeQuery(sql);

        while (rs.next())
        {
            String name=rs.getString("ENAME");
            double salary=rs.getDouble(2);
            Date date=rs.getDate("HIREDATE");
            System.out.print("Name: "+name);
            System.out.print("Salary: "+salary);
            System.out.println("Hiredate: "+date);
        }

        rs.close();
        stmt.close();
        conn.close();
    }
    catch(SQLException se)
    {
        se.printStackTrace();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            if (conn!=null)
                conn.close();
        }
        catch(SQLException se)
        {
            se.printStackTrace();
        }
    }
    System.out.println("GoodBye!!");
}
}


text:
Q: Simple update mechanism for C/GTK app on Windows I am developping a C/GTK application. I will soon be releasing a new version, and I thought it would be useful to include some update mechanism to it so that the application will be able to update itself.
I really only need something simple; it is sufficient if it only worked on Windows, since on Linux the application is in the repo so users can update it easily.
So I wanted to ask, is there some easy and simple way to do this (like some small library), or would I have to implement it myself?
Thanks.
P.S.
I really want something very simple, for example, let's say the application would download a webpage from a server which would contain the latest version number. If the applications version number!=server version number, it would fetch a setup.exe, somehow check its authenticity and run it.

A: This might not be a full answer to the question, but they're some things you might want to take into account if you're to implement it yourself:
For the "checking for update" part, without actually downloading it, you may download a text file from an online location, containing the latest version string (e.g. 1.24). This code snippet should do the job for the Windows version (although I have not tested it):
#include <wininet.h>

_Bool CheckForUpdate() {
    DWORD flags = 0; // Not really used. DWORD == unsigned long

    if (!InternetGetConnectedState(&flags, 0)) {
        // The user is not connected to the Internet. Finished?
    }

    // Open the connection (HINTERNET == void *):
    HINTERNET connection = InternetOpen("User Agent", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
    if (http == NULL) {
        // Error.
        ...
    }

    HINTERNET updateFile = InternetOpenUrl(connection, "URL", NULL, FLAGS, 0);
    if (updateFile == NULL) {
        // Something went wrong.
        ...
        InternetcloseHandle(connection); // Close the handle.
        ...
    }

    // Reached here, we have the connection up, reading the file:
    char latestVersion[10] = {0};
    DWORD bytesRead = 0;
    if (InternetReadFile(updateFile, latestVersion, sizeof(latestVersion), &bytesRead) == FALSE) {
        // Error.
        ...
        InternetCloseHandle(updateFile);
        InternetCloseHandle(connection);
        ...
    }

    // Internet stuff is finished, so the handles can be closed now:
    InternetCloseHandle(updateFile);
    InternetCloseHandle(connection);

    // Check if there's a new version available:
    if (strcmp(latestVersion, CURRENT_VERSION) > 0) {
        // An update is available.
        return 1;
    } else {
        // No new updates available.
        return 0;
    }
}

There are links to the docs on the Wininet functions I used in the end of the answer, where you can see what's each parameter for.
When calling InternetOpen() the user agent string may be your application name for example. I wrote INTERNET_OPEN_TYPE_DIRECT as it's the most common setup, no proxy configuration is specified.
In the InternetOpenUrl() call the second parameter should be the URL to the text file as a NULL terminated string. For the FLAGS parameter in that call check the online docs on the different ones you have (checkout the links at the bottom of the post). For example, a possible flags combination would be the following:
INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_NO_UI

The strcmp() call should work well with letters among the versions too, so following the above example "1.24c" should be a newer version than "1.24" or "1.24a".
In case you have several release paths (like beta versions for example) you may use several fields on the text file or have several files. This might be useful if you don't want to push unstable releases to all users but only the ones willing to use such builds.
If there's no error when reading the file you can also add a check to see if the HTTP status code was 200 (OK) using the HttpQueryInfo() function with the HTTP_QUERY_STATUS_CODE flag.
Anyway, all this is only to get acknowledged of new versions, you may just notify of that to your users via a message or use a similar scheme to download the new setup application. For the authentication phase you can add to the version file a checksum of the setup file and calculate it once the file is downloaded.
Links to the online documentation on the Wininet API:

*

*InternetGetConnectedState()

*InternetOpen()

*InternetOpenUrl()

*InternetReadFile()

*InternetCloseHandle()

*HttpQueryInfo()

*All of the Wininet functions
Hope that helps.

A: omaha is pretty cool, if you have the resources to set up the corresponding server side.


text:
Q: Gitlab CI/CD stages doesn't use same workspace I'm new to Gitlab pipelines. Coming from Jenkins, where all stages share the same folder workspace, here I noticed that at every news stage the workspace was resetted.
I simply want to do a build and a publish in two different stages, but the second stage doesn't find artifact built.
Is there a way to share the entire workspace across all pipeline?

A: Jobs can use artifacts from previous stages, if any of the jobs in the previous stage declare artifacts. Later stages automatically import artifacts from previous stages. What you need to do is declare the files/folders you want to include in later stages.
The documentation for artifacts is here. Basically, you'll want to set your build folder as an artifact in your build job. Then, your publish job will have access to that folder (assuming it's in a later stage).


text:
Q: Links (relations) to REST resources in AngularJS I have a REST API, which returns User object, where its roles are specified via link to another object. So at localhost/project/api/users/27/ is JSON object:
{
    "id": 42,
    "name": "John",
    "prijmeni": "Doe",
    "login": "johndoe",
    "nickname": null,
    "grade": 1.3,
    "roles": {
        "href": "http://localhost/project/api/users/1716/roles/"
    }
}

What I'm trying to do is to get roles in controller. My User service looks like this:
projectServices.factory('User', ['$resource', 'UserRoles',
    function($resource, UserRoles, Role) {
        var User = $resource('http://localhost/project/api/users/:id', {}, {
            'query': {
                method: 'GET',
                isArray: true
            }
        });
        return User;
    }
]);

and I tried to add (to that resource code block):
User.prototype.roles= function(){
   return UserRoles.get({id:42});
};

this one freezes browser when called in ngRepeat. So I tried
User.prototype.roles = UserRoles.get({id:42});

this works. Then I tried
User.prototype.roles = $resource(this.roles.href, {}, {
   'get': {
      method: 'GET',
      isArray: true
   }
});

says, that roles is undefined. I also tried to add transformResponse param to User service GET action, but that function was never called.
The second option works just perfectly fine - except, that I have to hardcode the user ID. Suitable solution would be with somehow getting the user ID for me (i tried this.id, but that didn't work).
Perfect solution would be creating resource from given href, but as I can't access roles in prototype, I don't know how.
Thanks for any advice.

A: This should do the trick
projectServices.factory('UserRoles', function(){
    return $resource('http://localhost/project/api/users/:id', {id: @id},
        {'query': {
            method: 'GET',
            isArray: true
        })
}

Now you can call it with
UserRoles.get({id:42})
// this makes the request :     http://localhost/project/api/users/42

The @id tells angular to use the id key from the parameter passed.


text:
Q: change in the ordering of xml attributes I am using an xslt transformation to transform some xml files. In order to format the output, what i am using is two tags in the xsl style sheet.
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>

But the problem is , in windows i am getting a kind of output , and when i run the program in a unix machine, i am getting a different kind of output.
eg:
<Book name="Godfather" author="MarioPuzo"/>
But in unix, what i am getting is ,
<Book  author="MarioPuzo" name="Godfather" />
it is kind of a weird problem. Any help is appreciated.

A: In XML there is no standard ordering defined in the set of the attributes of an element -- this can be different from implementation to implementation.
Also, in case the only difference between two XML documents is the order of attributes, they are considered "equal" -- for example the XPath 2.0 function deep-equal($doc1, $doc2) produces true().
This is analogous to a class definition -- two class definitions in which the only difference is the ordering of the properties (or methods) are the same class definition and can be substituted with each other without causing different result from any program that uses instances of this class definition.
Here is a demo of the fact that two documents are considered "equal" if the only differences are ordering of attributes:
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>

    <xsl:variable name="vDoc2">
     <t y="2"   x="1" />
    </xsl:variable>

 <xsl:template match="/">
     <xsl:sequence select="deep-equal(/, $vDoc2)"/>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the following XML document:
<t x="1" y="2"/>

the result is:
true

Even if some hack is found for the attributes to appear in a particular order for a given implementation both of an XML parser and of an XSLT processor), this hack is not guaranteed to work with the next version of this implementation.


text:
Q: When using Ruby, is there a way not to use $ for global variables, or structure the program to put the globals as some locals within a main method? That is, possibly structuring it so that it is like an IIFE in JavaScript so that all those variables are visible only within a function scope?
When converting some Go programs into Ruby to compare their running speed, I had to convert all the Go global variables from width to $width in Ruby, so that inside any function, these global values can be used.
But if there are 15 or 20 of these variables, then it becomes very troublesome to convert.  In Ruby, is there a way to not use $ for global variables?  I tried to define a main method first, and hoping it is local inside of main:
def main

  foo = 1

  def another
    p foo
  end

  another()

end

main()

but it won't work.  Inside of another(), it still won't recognize foo and all the foo have to be changed to $foo for it to work.
As per request, this is some sample of the Go code:
var palette = []color.Color{color.White, color.Black}

const (
    whiteIndex = 0
    blackIndex = 1
    width, height = 800, 400
    viewAngle = math.Pi / 9
)

it actually is quite typical for some small Go program (or C program), to have some global variables at the very top, and then the main and some functions down below.  Since the whole program is not very big, there usually is not so much concern for some global variables such as the color, width, height, etc.

A: It is quite naive to expect concepts of one language to be present in another. Direct translation is not possible here.
However, I think that you'll get quite the same structure if you make a class out of original go code. Check it out:
class Program
  # your constants
  WHITE_INDEX = 0
  BLACK_INDEX = 1
  WIDTH = 800
  PALETTE = ['white', 'black'] # or something

  # your mutable data
  attr_accessor :foo

  # constructor and initialization of mutable data
  # (if it has default values, that is)
  def initialize
    self.foo = 1
  end

  # your other methods/functions
  def another
    p foo
  end

  # or main or whatever you want to call it
  def run
    another
  end
end

# finally, run the damn thing!
Program.new.run

You don't have to use global variables for emulating constants (or, for that matter, for any other purpose). Ruby has constants (they're not really constants at the moment, but this is what you're supposed to use).

A: I think a relevant answer is this: a lot of times, the globals are really just constants for the whole program.  In that case, just use WIDTH, PALETTE, etc in your Ruby program, and Ruby treats any name that begins with a capital letter as constants, and will let you use that in the global scope or local scope inside of any function.  The convention to name constants are all caps, with underscore separating the words, such as TILTING_FACTOR.
If you do really need to use a global variable, the recommendation is still to use a name such as $foo, to signal that this is a global and be very careful.  Typically, a good program, in Ruby or Go, will not use global variables or will try not to use it as much as possible.
Based on Sergio's suggestion, this will be the form, with the use of Class constants:
class Program

  FOO = 1
  VIEWING_ANGLE = Math::PI / 6     # so don't have to calculate again and again
  TILTING_FACTOR = Math.cos(VIEWING_ANGLE)
  COLOR_PALETTE = ['beige', 'darkgrey']

  def some_helper_function
    p "inside of helper function", FOO, VIEWING_ANGLE, TILTING_FACTOR, COLOR_PALETTE
  end

  def run
    p "inside of run", FOO, VIEWING_ANGLE, TILTING_FACTOR, COLOR_PALETTE
    some_helper_function()
  end

end

Program.new.run()

and actually, you can use global constants and any function can access it:
FOO = 1
VIEWING_ANGLE = Math::PI / 6     # so don't have to calculate again and again
TILTING_FACTOR = Math.cos(VIEWING_ANGLE)
COLOR_PALETTE = ['beige', 'darkgrey']

def some_helper_function
  p "inside of helper function", FOO, VIEWING_ANGLE, TILTING_FACTOR, COLOR_PALETTE
end

p "in global scope", FOO, VIEWING_ANGLE, TILTING_FACTOR, COLOR_PALETTE
some_helper_function()

And some more ways:
We actually can write it in a functional way, because a method is not a first class value, and is not something you can operate on (we can create a Method object out of it, but a method itself is not an object), as described in the book The Ruby Programming Language by David Flanagan and Matz.  A method is always tied to an object, and is intended for OOP. The book also said:

One important difference between Method objects and Proc objects is that Method objects are not closures.  Ruby's methods are intended to be completely self-contained and they never have access to local variables outside of their own scope.

So I think that implies that lambda, which is one type of Proc objects, is a closure and therefore have access to the scope outside of its own local scope.
This is how in a functional way:
foo = 1

some_helper_function = -> {
  p "inside of helper function", foo
}

p "in global scope", foo
some_helper_function.()

and if you don't want to contaminate the global space, there really is a way similar to JavaScript's IIFE:
-> {

    foo = 1

    some_helper_function = -> {
      p "inside of helper function", foo
    }

    p "inside the IIFE", foo
    some_helper_function.()

}.()

# outside of the IIFE, cannot access foo here

A: It's bad style to use global variables in Ruby, use local variables var or instance variables @var instead.
main() is not needed in Ruby. You can just add that code inside main after all the function definitions.


text:
Q: Referencing equations \[\] in LaTeX To write equations online I use the $$ notations, to do it offline I use \[\]. Having the code:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Neque egestas congue quisque egestas diam in arcu cursus euismod.

\[((3+2) \times (4+(-2)))\]

Nisl vel pretium lectus quam id leo. Iaculis at erat pellentesque adipiscing commodo elit at imperdiet.

Eget arcu dictum varius duis. Augue neque gravida in fermentum. Vitae purus faucibus ornare suspendisse sed nisi lacus sed.

I would like to refer several times to the equation in other parts of the text. I know I can use equation to reference easily, as specified here. Can I reference it using \[\] and not equation? Am I required to use equation for it? What is the use of the equations with \[\]?

A: \[ is an un-numbered equation, so has no equation number to \label or reference.

A: Replace \[ by \begin{equation}\label{foo} and \] by \end{equation}.


text:
Q: How can I use keystore.jks and truststore.jks files for Kafka Python SSL Authentication after converting to .pem? I have 2 certificate files, truststore.jks and keystore.jks. keystore.jks contains a full  certificate chain for the kafka endpoint I'm using as well as a private key for my application. According to the group who gave me truststore.jks it contains "a new root CA chain" and is essential for getting my application to connect with the kafka endpoint.
I have tried using this script to generate 3 .pem files that I use in my Python code.
#!/bin/bash
srcFolder=$1
keyStore=$1/$2
password=$3
alias=$4
outputFolder=$5

echo $keyStore
echo "Generating certificate.pem"
keytool -exportcert -alias $alias -keystore $keyStore -rfc -file $outputFolder/certificate.pem -storepass $password

echo "Generating key.pem"
keytool -v -importkeystore -srckeystore $keyStore -srcalias $alias -destkeystore $outputFolder/cert_and_key.p12 -deststoretype PKCS12 -storepass $password -srcstorepass $password
openssl pkcs12 -in $outputFolder/cert_and_key.p12 -nodes -nocerts -out $outputFolder/key.pem -passin pass:$password

echo "Generating CARoot.pem"
keytool -exportcert -alias $alias -keystore $keyStore -rfc -file $outputFolder/CARoot.pem -storepass $password

I use the generated CARoot.pem, certificate.pem, and key.pem files in my code like so.
>>> from kafka import KafkaProducer
>>> producer = KafkaProducer(bootstrap_servers='kafka-dev.kafka.com:port', security_protocol="SSL",
... ssl_check_hostname=True,
... ssl_cafile="CARoot.pem",
... ssl_certfile="certificate.pem",
... ssl_keyfile="key.pem",
... ssl_password="")

It gives this error:
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1131)

I have tried combining truststore.jks and keystore.jks like so:
keytool -importkeystore -srckeystore truststore.jks -destkeystore keystore_copy.jks

I then put keystore_copy.jks through the same .pem conversion process as before, but it produces the same error.
For some context, this is how the Kafka endpoint owners suggest to configure the ssl certs in Java, unfortunately I am the first to connect with Python so they haven't been able to help me with it.
props.setProperty(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
props.setProperty(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, "<kafka-truststore.jks>");
props.setProperty(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "<password>");
props.setProperty(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, "<client-keystore.jks>");
props.setProperty(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "<password>");
props.setProperty(SslConfigs.SSL_KEY_PASSWORD_CONFIG, "<password>");

Is there something I'm missing? I believe I need to utilize both .jks files in my code somehow but the only approach I can think of taking failed.
Additional things I have tried:
pip install --upgrade certifi based on reports of the same error due to that library being out of date.

A: The following properties which KAFKA endpoint owners are asked you is correct, but looks like the issue with your keystore/truststore having a self signed certificate. It appears ssl.verify or hostName verification is enabled at the server level.
props.setProperty(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
props.setProperty(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, "<kafka-truststore.jks>");
props.setProperty(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "<password>");
props.setProperty(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, "<client-keystore.jks>");
props.setProperty(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "<password>");
props.setProperty(SslConfigs.SSL_KEY_PASSWORD_CONFIG, "<password>");

This is one give you better clarity on this error.
https://community.ibm.com/community/user/ibmz-and-linuxone/blogs/sheng-jie-han/2021/06/03/how-to-fix-certificate-verify-failed-self-signed-c

A: I managed to figure out the solution on my own. The key here was realizing that I needed to have the entire cert chain from my truststore.jks file present in CARoot.pem for the code to work. Here are the steps that I took:
Generate CARoot.pem from the trust store:
keytool -importkeystore -srckeystore <<truststore-name.jks>> -destkeystore keystore.p12 -srcstoretype jks -deststoretype pkcs12

openssl pkcs12 -in keystore.p12 -out CARoot.pem

Generate certificate.pem from keystore
keytool -exportcert -alias <<alias>> -keystore ./<<keystore—name.jks>> -rfc -file ./certificate.pem -storepass <<password>>

Extract private key and generate RSAkey.pem from keystore:
keytool -importkeystore -srckeystore <<keystore-name.jks>> -destkeystore keystore.p12 -deststoretype PKCS12

openssl pkcs12 -in keystore.p12 -nodes -nocerts -out RSAkey.pem

Example with Kafka-Python Producer:
producer = KafkaProducer(bootstrap_servers='kafka-dev.kafka.com:port', security_protocol="SSL",
ssl_check_hostname=False,
ssl_cafile="CARoot.pem",
ssl_certfile="certificate.pem",
ssl_keyfile="RSAkey.pem",
ssl_password=<<password>>)


text:
Q: Torch / Lua, how to edit an original abstract file of a known package? I tried to add a function to the Module.lua abstract file in the Torch package called nn, but my main program does not find it.
Suppose my function is simply:
function printTry()
  print("printTry()");
end

I added this function at the end of the Module.lua file and I was supposed to use it in my Torch terminal:
require 'nn';
perceptron = nn.Module();
perceptron:printTry()

But the system generates:
string "perceptron.printTry();"]:1: attempt to call field 'printTry' (a nil value)
stack traceback:
    [string "perceptron.printTry();"]:1: in main chunk
    [C]: in function 'xpcall'
    /home/davide/torch/install/share/lua/5.1/trepl/init.lua:668: in function 'repl'
    ...vide/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:199: in main chunk
    [C]: at 0x004064d0

Probably the system is not aware of this new function that I added... what should I do to use this new method?

A: Use torch.getmetatable:
require 'nn'
torch.getmetatable('nn.Module').printTry = function() print('PrintTry') end

perceptron = nn.Sequential()
perceptron:printTry()

A: You simply defined a global function printTry, but you call it as a method on perceptron. You need to define it as a field of Module (in that Module.lua file, assuming this is what nn.Sequential returns):
function Module:printTry()
  print("printTry()")
end


text:
Q: Changing UITableView height with animateWithDuration causing UITableViewCell weird basically I make a view that nest on the bottom, on pressing the orange button, I make the view slide up (changing the height). The view contains a UITableView that anchored to the top and bottom of the view, to the UITableView also got resized in the process.
All behaves correctly except the UITableViewCell inside the UITableView is layouting weirdly. (screenshoot attached).
I suspect calling the UIView animateWithDuration make the UITableView generate new cell due to height change and the UITableViewCell adjusting it's layout on a duration that make it weird
Is there any way to prevent UITableViewCell behave like that?


text:
Q: Keeping data object after filtering Small Background intro
I´m currently working the User Administration page of my project and running into a small problem here. I have a table which contains some material-ui`s Usercard. For Each user that uses my System exist´s one card. The card´s are generated from data that comes from my database and then written into a redux store.
The Admin can do several interactions with the database that changes some Userdata. To provide an easy way to find a specific user a <TextField /> was implemented that filter´s the table of Usercards.
All of the things mentioned here works!
The Problem
As mentioned in the Intro the data are stored in a redux store. When I filter the data, an action is dispatched
    export const FILTER_ALL_USER_BY_NAME = "FILTER_ALL_USER_BY_NAME"
    export const FILTER_ALL_USER_BY_DEPARTMENT = "FILTER_ALL_USER_BY_DEPARTMENT"

    export default function filterAllUser(filter, filterOption){
        return (dispatch, getState) => {
            if(filterOption === 'name'){
                return dispatch (filterUserByName(filter))
            }else{
                return dispatch (filteUserByDepartment(filter))
            }
        }
    }

    function filterUserByName(filter){
        return {
            type: FILTER_ALL_USER_BY_NAME,
            filter: filter
        }
    }

    function filteUserByDepartment(filter){
        return {
            type: FILTER_ALL_USER_BY_DEPARTMENT,
            filter: filter
        }
    }

The Reducer
Even if the reducers works, it is the main reason for my problem.
Why?
It is because, when I filter the data I was not able to really filter the state, rather then return a new state object which leads me to the problem that the allUserData and filteredUserData get out of sync after the userdata are changed.
Let me explain this in code
    function allUser(state = {allUserData: []}, action){
        switch (action.type){
            case 'REQUEST_ALL_USER':
                return Object.assign({}, state, {
                    isFetching: true
                });
            case 'RECEIVE_ALL_USER':
                return Object.assign({}, state, {
                    isFetching: false,
                    allUserData: action.items
                });
            case 'FILTER_ALL_USER_BY_NAME':
                return Object.assign({}, state, {
                    filteredUserData: state.allUserData.filter(user => user.userNameLast.toLowerCase().indexOf(action.filter.toLowerCase()) >= 0)
                });
            case 'FILTER_ALL_USER_BY_DEPARTMENT':
                return Object.assign({}, state, {
                    filteredUserData: state.allUserData.filter(user => user.departmentName.toLowerCase().indexOf(action.filter.toLowerCase()) >= 0)
                });
            default:
                return state
        }
    }

But when I´m trying to filter the original state and the user removes the filter, the data that didn´t matched the filter are gone.
    case 'FILTER_ALL_USERS': return allUsers.filter(user => user.userNameLast.toLowerCase().indexOf(action.filter.toLowerCase()) >= 0);

How can I filter the state, but keep the data ?

A: Best for these cases is to some selector library, example reselect. Instead of editing the original state create selectors for sorting and filter and pass the result to component.
There's also a quite similar example in reselect documentation https://github.com/reactjs/reselect#selectorstodoselectorsjs.

A: As requested, I have put together some code for you. It would be something like below.
As a side note, I would pass the filter as { field: 'userLastName', text: your filter text} as the filter criteria. Or to make it even more scalable, you can pass a filter-handler instead of text above. That way you can have any type of filter, and not just text filters.
export default function allUser(state = {allUserData: [], filters: {}, filteredUserData: []}, action){
  switch (action.type){
    case 'REQUEST_ALL_USER':
      return {
        ...state,
        isFetching: true
      };
    case 'RECEIVE_ALL_USER':
      return {
        ...state,
        isFetching: false,
        allUserData: action.items,
        filteredUserData: filterData(action.items, state.filters),
      };
    case 'FILTER_ALL_USER_BY_NAME':
    {
      const updatedFilters = {
        ...state.filters,
        userNameLast: action.filter
      }
      return {
        ...state,
        filteredUserData: filterData(state.allUserData, updatedFilters),
        filters: updatedFilters
      };
    }
    case 'FILTER_ALL_USER_BY_DEPARTMENT':
    {
      const updatedFilters = {
        ...state.filters,
        departmentName: action.filter
      }
      return {
        ...state,
        filteredUserData: filterData(state.allUserData, updatedFilters),
        filters: updatedFilters
      };
    }
    default:
      return state
  }
}

const filterData = (users, filters) => {
  return users.filter(filterFn(filters));
};

const filterFn = filters => item => Object.keys(filters).reduce((res, filter) => {
  return res && item[filter].toLowerCase().indexOf(filters[filter].toLowerCase()) >= 0;
}, true);

Unit tests
import usersReducer from './users';

describe('usersReducer', () => {
  describe('RECEIVE_ALL_USER', () => {
    const RECEIVE_ALL_USER = 'RECEIVE_ALL_USER';
    it('should replace users in state', () => {
      const initialState = { isFetching: false, allUserData: [{ name: 'A' }], filters: {}};
      const newUsers = [{ name: 'B' }];
      const newState = { ...initialState, allUserData: newUsers, filteredUserData: newUsers};
      expect(usersReducer(initialState, { type: RECEIVE_ALL_USER, items: newUsers })).toEqual(newState);
    })
  })
  describe('FILTER_ALL_USER_BY_NAME', () => {
    let FILTER_ALL_USER_BY_NAME = 'FILTER_ALL_USER_BY_NAME';
    it('should filter users by name', () => {
      const initialState = { isFetching: false, allUserData: [{ userNameLast: 'Doe' }, { userNameLast: 'Smith' }], filters: {}};
      const filterText = 'd';
      const finalState = { isFetching: false,
        allUserData: [{ userNameLast: 'Doe' }, { userNameLast: 'Smith' }],
        filters: { userNameLast: filterText },
        filteredUserData: [{ userNameLast: 'Doe' }]
      };

      expect(usersReducer(initialState, { type: FILTER_ALL_USER_BY_NAME, filter: filterText})).toEqual(finalState);
    })
  })
  describe('FILTER_ALL_USER_BY_DEPARTMENT', () => {
    let FILTER_ALL_USER_BY_DEPARTMENT = 'FILTER_ALL_USER_BY_DEPARTMENT';
    it('should filter users by department', () => {
      const initialState = { isFetching: false, allUserData: [{ departmentName: 'IT' }, { departmentName: 'Human Resources' }], filters: {}};
      const filterText = 'it';
      const finalState = {
        ...initialState,
        filters: { departmentName: filterText },
        filteredUserData: [{ departmentName: 'IT' }]
      };

      expect(usersReducer(initialState, { type: FILTER_ALL_USER_BY_DEPARTMENT, filter: filterText})).toEqual(finalState);
    })
  })
});


text:
Q: What does "type Task x a = Task" mean in the Elm implementation of Task? In this Github example, Task type is defined as follow:
type Task x a = Task
And then follow several functions that make use of this type.
How the Task type is supposed to be understood?
What does it mean when we define a type as:
type Foo a b = Foo
Is Task a specific case where we rely on the native javascript implementation of Task?

A:
Is Task a specific case where we rely on the native javascript implementation of Task?

Exactly. You'll notice that Task the type but not Task the tag (thing on the right) are exported from the module, so you can't actually access the latter. It's a placeholder to make the type system happy.
Instead, the Native JavaScript implementation knows what tasks really are, which is a JS object. Any native module dealing with Tasks (either the Task module or any third-party library like elm-http) is in on the secret. However, the Task module exports a good number of helper functions that you can have a lot of control over tasks using only the already published libraries.
Clarification Edit: Yes, you need to use a third-party library to get a task that actually does some effect in the outside world. To actually run that task, you need to send it out a port; until you do that a Task is just a description of the work to do.

A: Seems that it's creating a kind of wild card.
In the following code:
import  Html exposing (..)

type Dog a = Fido

myFunc: Dog Int -> String
myFunc myDog =
  "Wouf Wouf"

main = text (myFunc Fido)

myFunc expects a Dog Int. You can then send Fido to the method.


text:
Q: Is there a way to replace anomalies with the mean of the two rows between them? I have a column that I'm trying to smooth out the results. Most of the data creates a smooth chart but sometimes I get a random spike. I want to reduce the impact of the spike.
My thought was to take the outlier and just make it the mean of the values between it but I'm struggling and not getting the result I want.
Here's what I'm doing right now:
df = pd.DataFrame(np.random.randint(0,100,size=(5, 1)), columns=list('A'))
def aDetection(inputs):
  median = inputs["A"].median()
  std = inputs["A"].std()
  outliers = (inputs["A"] - median).abs() > std
  print("outliers")
  print(outliers)
  inputs[outliers]["A"] = np.nan #this isn't working.
  inputs[outliers] = np.nan #works but wipes out entire row
  inputs['A'].fillna(median, inplace=True)
  print("modified:")
  print(inputs)
print("original")
print(df)
aDetection(df)

original
    A
0   4
1  86
2  40
3  99
4  97
outliers
0     True
1    False
2     True
3    False
4    False
Name: A, dtype: bool
modified:
      A
0  86.0
1  86.0
2  86.0
3  99.0
4  97.0

For one, it seems to change all rows not just the single column. But the bigger problem is all the outliers in my example are using 86. I realize this is because I set the mean for the entire column, but I would like the mean between the previous column with the missing data.

A: For a single column, you can do your task with the following one-liner
(for readability folded into 2 lines):
df.A = df.A.mask((df.A - df.A.median()).abs() > df.A.std(),
    pd.concat([df.A.shift(), df.A.shift(-1)], axis=1).mean(axis=1))

Details:

*

*(df.A - df.A.median()).abs() > df.A.std() - computes outliers.

*df.A.shift() - computes a Series of previous values.

*df.A.shift(-1) - computes a Series of following values.

*pd.concat(...) - creates a DataFrame from both the above Series.

*mean(axis=1) - computes means by rows.

*mask(...) - takes original values of A column for non-outliers
and the value from concat for outliers.

The result is:
      A
0  86.0
1  86.0
2  92.5
3  99.0
4  97.0

If you want to apply this mechanism to all columns of your DataFrame,
then:

*

*Change the above code to a function:
def replOutliers(col):
    return col.mask((col - col.median()).abs() > col.std(),
        pd.concat([col.shift(), col.shift(-1)], axis=1).mean(axis=1))

*Apply it (to each column):
df = df.apply(replOutliers)


text:
Q: Slider step rate based on speed of moving the slider I have a UWP XAML app that is using a slider as a volume control for a piece of audio hardware on the network. My issue is there is a 50ms+ required delay between sending volume changes, so if I quickly move the slider from minimum to maximum, it takes the hardware a few seconds to catch up as the app is sending a new +1 level each valuechanged event of the slider.
I don't want to change the step of the slider because I want precise control as well. Smallstep/largestep don't really help. Is there built-in functionality that will change the step based on the velocity you're moving the slider, i.e. slow movement, step =1, medium movement step =5, fast movement step= 10?
If not, does anyone have any suggestions on how this can be implemented? I think I can do something with the manipulation events.

A: There is a way you can change the slider's step based on drag velocity.
You have to subscribe to the ManipulationDelta event (don't forget to set the ManipulationMode of the slider to something other than System or None).
Then in the handler get the Velocities from the ManipulationDeltaRoutedEventArgs arguments. Something like that
public void MySlider_ManipulationDelta(object sender,
  ManipulationDeltaRoutedEventArgs e)
{
    var velocities = e.Velocities
    var slider = sender as Slider;
    if(slider != null)
    {
        //Create a fomula based on the velocities to fit your needs.
    }

}

You should also remember to reset the step of the slider on the ManipulationCompleted event.
Having said that, I don't see how changing the step based on drag velocity would help you achieve the desired result. From my understanding, due to parameters outside your control (network, hardware etc), there is a 50ms delay between the time your app sends data and the time the hardware reflects the change. And that's that.


text:
Q: Firebase JobDispatcher-Scheduled jobs are lost on device reboot I am using Firebase-JobDispatcher.I have scheduled some jobs and its working fine if i keep the device switch on.But if i reboot my device then  the scheduled jobs doesn't execute or it doesn't get rescheduled?I have used setLifetime(Lifetime.FOREVER).Still jobs are lost on device reboot.Below is the code i m using-
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("DataSend")
.setRecurring(false)
.setLifetime(Lifetime.FOREVER)
.setTrigger(Trigger.executionWindow(0, 0))
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
.setConstraints(Constraint.ON_ANY_NETWORK)
.setExtras(myExtrasBundle)
.build();

A: After setting Lifetime.FOREVER you have add the following permission in AndroidManifest.xml file
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

And below is the code to schedule a job
Job job = jobDispatcher.newJobBuilder()
    .setService(MyJobService.class)
    .setTrigger(Trigger.executionWindow(windowStartTime, 3600))
    .setTag(PENDING_AUTH_JOB) //identifier for the job
    .setRecurring(false) // should not recur
    .setLifetime(Lifetime.FOREVER) // should persist device reboot
    .setReplaceCurrent(false) // no need to replace previous job
    .setConstraints(Constraint.ON_ANY_NETWORK) // set network availability constraint
    .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
    .build();
try {
  jobDispatcher.mustSchedule(job);
} catch (FirebaseJobDispatcher.ScheduleFailedException e) {
  if (retryCount-- > 0) {
    scheduleJob(0);
  }
}

One more thing to check is not set execution window to 0,0. always set a  windowEnd greater that windowStart

A: I think in your MyJobService should return false so that the job can be rescheduled after executing;
  public boolean onStartJob(final com.firebase.jobdispatcher.JobParameters jobParameters) {

        //Offloading work to a new thread.
        new Thread(new Runnable() {
            @Override
            public void run() {
                realm=Realm.getDefaultInstance();

                codeYouWantToRun(jobParameters);
            }
        }).start();

        return true;
    }

 public void codeYouWantToRun(final JobParameters parameters) {
 Log.d(TAG, "completeJob: " + "jobStarted");
//bla bla super code doing its linga linga ling
                Log.d(TAG, "completeJob: " + "jobFinished");

                    //Tell the framework that the job has completed and doesnot needs to be reschedule. Set jobFinished false so that it can rescheduled on a change of network
                    jobFinished(parameters, false);
    }

A: Try setPersisted(boolean) method.


text:
Q: Understanding multi-touch on android I'm trying to track multi touch events on android (I need to track "touch down" and "touch up" for each finger). The problem is the PointerId does not seem to be consistent or somehow I'm having problems linking "down" events to "up" ones and as a result I'm missing some "up" events.
Here is the code I use to process MotionEvents:
int pointerIndex = me.getActionIndex();
int pointerId = me.getPointerId(pointerIndex);
final int action = me.getActionMasked();

switch (action)
{
case MotionEvent.ACTION_POINTER_DOWN:
{
    if (action == MotionEvent.ACTION_POINTER_DOWN)
    {
        System.out.println("ACTION_POINTER_DOWN Index: " + pointerIndex + ", ID: " + pointerId);
    }
}
case MotionEvent.ACTION_DOWN:
{
    if (action == MotionEvent.ACTION_DOWN)
    {
        System.out.println("Initial ACTION_DOWN Index: " + pointerIndex + ", ID: " + pointerId);
        pointerIndex = 0;
        pointerId = me.getPointerId(pointerIndex);
        System.out.println("ACTION_DOWN Index: " + pointerIndex + ", ID: " + pointerId);
    }
    if (!idPressed[pointerId])
    {
        idGenerator++;
        idOffset[pointerId] = idGenerator;
        mView.DoTouchEvent(0, mePos[pointerId * 2] - location[0], mePos[pointerId * 2 + 1] - location[1], idOffset[pointerId]);
        idPressed[pointerId] = true;
        //System.out.println("ACTION_DOWN Index: " + pointerIndex + ", ID: " + pointerId + " Gen: " + idOffset[pointerId]);
    }
    break;
}
    case MotionEvent.ACTION_POINTER_UP:
    {
        if (action == MotionEvent.ACTION_POINTER_UP)
        {
            System.out.println("ACTION_POINTER_UP Index: " + pointerIndex + ", ID: " + pointerId);
        }
    }
    case MotionEvent.ACTION_UP:
    {
        if (action == MotionEvent.ACTION_UP)
        {
            System.out.println("Initial ACTION_UP Index: " + pointerIndex + ", ID: " + pointerId);
            pointerIndex = 0;
            pointerId = me.getPointerId(pointerIndex);
            System.out.println("ACTION_UP Index: " + pointerIndex + ", ID: " + pointerId);
        }
        if (idPressed[pointerId])
        {
            mView.DoTouchEvent(1, me.getX(pointerIndex) - location[0], me.getY(pointerIndex) - location[1], idOffset[pointerId]);
            idPressed[pointerId] = false;
            //System.out.println("ACTION_UP Index: " + pointerIndex + ", ID: " + pointerId + " Gen: " + idOffset[pointerId]);
        }
        break;
    }

Here is the log recorded with the above code:
    08-24 12:13:32.603: I/System.out(3570): Initial ACTION_DOWN Index: 0, ID: 0
08-24 12:13:32.603: I/System.out(3570): ACTION_DOWN Index: 0, ID: 0
08-24 12:13:32.943: I/System.out(3570): ACTION_POINTER_DOWN Index: 1, ID: 1
08-24 12:13:32.943: I/System.out(3570): ACTION_POINTER_DOWN Index: 1, ID: 1
08-24 12:13:33.013: I/System.out(3570): ACTION_POINTER_UP Index: 1, ID: 1
08-24 12:13:33.013: I/System.out(3570): ACTION_POINTER_UP Index: 1, ID: 1
08-24 12:13:33.103: I/System.out(3570): ACTION_POINTER_DOWN Index: 1, ID: 1
08-24 12:13:33.103: I/System.out(3570): ACTION_POINTER_DOWN Index: 1, ID: 1
08-24 12:13:33.174: I/System.out(3570): ACTION_POINTER_UP Index: 1, ID: 1
08-24 12:13:33.174: I/System.out(3570): ACTION_POINTER_UP Index: 1, ID: 1
08-24 12:13:33.174: I/System.out(3570): ACTION_POINTER_UP Index: 1, ID: 1
08-24 12:13:33.214: I/System.out(3570): ACTION_POINTER_DOWN Index: 1, ID: 1
08-24 12:13:33.214: I/System.out(3570): ACTION_POINTER_DOWN Index: 1, ID: 1
08-24 12:13:34.115: I/System.out(3570): Initial ACTION_UP Index: 0, ID: 0
08-24 12:13:34.115: I/System.out(3570): ACTION_UP Index: 0, ID: 0
08-24 12:13:34.115: I/System.out(3570): Initial ACTION_UP Index: 0, ID: 0
08-24 12:13:34.115: I/System.out(3570): ACTION_UP Index: 0, ID: 0
08-24 12:13:34.115: I/System.out(3570): Initial ACTION_UP Index: 0, ID: 0
08-24 12:13:34.115: I/System.out(3570): ACTION_UP Index: 0, ID: 0
08-24 12:13:34.115: I/System.out(3570): Initial ACTION_UP Index: 0, ID: 0
08-24 12:13:34.115: I/System.out(3570): ACTION_UP Index: 0, ID: 0
08-24 12:13:34.115: I/System.out(3570): Initial ACTION_UP Index: 0, ID: 0
08-24 12:13:34.115: I/System.out(3570): ACTION_UP Index: 0, ID: 0

At the end of this log I had no finger on the screen, but as you can see there is no "up" event for ID: 1. (also I don't know why I get multiple events of the same type one after the other).
Am I missing something ? Anyone has any idea ?
Thanks,
/COsmin

A: I finally found the problem to this and I'm posting here for others that may have the same problem, so: the problem was that I was not processing the MotionEvent right when it was receives, instead I was placing it in a queue and process everything on the next update loop. The problem was that I was actually holding a pointer to the MotionEvent and in some cases with fast/many touches, the content of those objects was replaced before the processing loop (most likely there is a pool of MotionEvent objects used by the system and so an object will be reused from time to time).