text:
Q: A script to automatically rename a file after it's saved to the local computer? I want the user of my page to :

*

*browse a movie file from his local computer

*get an image from the movie he just input it in step 1

*name the image file exactly the same with the movie file name

*upload to the server this image file

Thanks to the link from codepen here, I can pass step 1 and step 2 above.
(Please have a look to the link above for the complete codes), The HTML :

Select a video or image file

Supported browsers (tested): Chrome, Firefox, Safari, Opera, IE10, IE11, Android (Chrome), iOS Safari (10+)

So, I copy/paste the codes to my page. After this I can just go to the next steps "manually" by telling the user to

*

*(3a) right click the image and choose "Save image as..."

*(3b) rename the file in the "Save image as" dialog box exactly the
same with the movie file name and put a .jpg extension instead of the
default one which is .png

*(3c) from the form I provide, browse his local computer and select
this jpg file

*(4) push the "Submit" button to upload the jpg file to the server

Suppose I'm the user, I click the "Browse" button and select SinCity.mp4 movie. Then I saw the page showing a still image from the movie. Without doing 3a, 3b and 3c, I just click another button - which is the "Submit" button to upload SinCity.jpg
My question is : will it be possible to "auto" step 3 so the user doesn't have to do 3a, 3b and 3c ?. I mean the process of 3a 3b 3c are taken over by a script. If possible, would somebody help me for the script ?
FYI, my page is in .php extension file.
Thank you in advanced.
=====================================================================
EDIT : I found the answer.
Thank you to all user who submit a codes in the internet and thank you also to Douwe de Haan who help me on how to do it. I'm sorry since I can not put more than two links in my post, I will just copy/paste the codes which come from 3 different sources, in case there is someone who face the same case with me.
First, the CSS :
div {
  line-height: 200px;
}

img {
  padding: 5px;
  vertical-align: middle;
  text-align: center;
}

@supports (object-fit: cover) {
  img {
    object-fit: cover;
  }
}

The css above I got it from anon/pen in codepen.
The HTML :
<input type="file" accept=".jpg,.jpeg.,.gif,.png,.mov,.mp4" onchange="document.getElementById('file').value =
this.value.split('\\').pop().split('/').pop()" />

Select a video or image file

Supported browsers (tested): Chrome, Firefox, Safari, Opera, IE10, IE11, Android (Chrome), iOS Safari (10+)

<input type="button" onclick="uploadEx()" value="Upload" />
<form method="post" accept-charset="utf-8" name="form1">
<input name="hidden_data" id='hidden_data' />
<input type="text" name="file" id='file' type="hidden"/>
</form>

The html above is a combination which I got from

*

*anon/pen in codepen

*the onchange="document.getElementById('file').value I got it from
shijin/4EnRQ/ in jsfiddle and

*the onclick="uploadEx()" I got it from
"upload-html-canvas-data-to-php-server" in codepool.

The SCRIPT :

The script above I got it from anon in codepen, the last function uploadEX() I got it from "upload-html-canvas-data-to-php-server" in codepool and the document.images[0].src;I got it from W3School.
Finally the upload_data.php
<?php
$upload_dir = "uploads/";
$img = $_POST['hidden_data'];
$file_name = substr($_POST['file'],0,-4);
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . $file_name . ".jpg";
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>

The php above I got it from "upload-html-canvas-data-to-php-server" in codepool.
Thank you very much, All.

A: If you'll accept that the user doesn't download anything and the flow is changed to this:

*

*User selects a movie

*Script gets a still to upload

*User presses upload button and still is uploaded

Then yes, it just takes a few steps:
Create a hidden input in the form named something like snapshot_base64
<input type="hidden" name="snapshot_base64" id="snapshot_base64">

Next, in the codepen you provided is a line that says var image = canvas.toDataUrl(). After that line, put the following code:
snapshot_input = document.getElementById('snapshot_base64');
snapshot_input.setAttribute('value', image);

This loads the base64 data into the hidden input.
What you still need to to yourself is grabbing the name of the uploaded movie and add that to a hidden input as well, so you'll know what name to give to the file.
After this you'll need to submit the form and read the base64 in the php files you are using.
Converting base64 to an image is described here.


text:
Q: Implementing Newton's Method? For an assignment, I have to implement Newton's method using
Module and a For loop. So far, I have
newtMethod[guess_, fun_] :=
 ( Module[{k, x0, x1},
   x0 = guess;
   For[k = 1,
    Abs[x1 - x0] >= .0001,
    k = k + 1,
    x1 = (x0 - fun[x0]/fun'[x0]);
    If[Abs[x1 - x0] < 0, x0 = x1, x1 = x1];
    x1]; Print[x1]])

When I run this, a strange message appears.
f[x_] := Sin[E^x];
newtMethod[2.5, f]
x1$5709

If I remove the
Print[x1]
part of the code, there's NO output entirely. What am I doing wrong here? Is there any meaning to the weird output? I think my error has to do with what I included in the
For loop and what I defined x1 to be, but I'm not sure. Any tips?

A: The main reason is that x1 is not assigned a value before entering the for loop:
newtMethod[guess_,
  fun_] := (Module[{k, x0, x1}, x0 = guess;
   x1 = (x0 - fun[x0]/fun'[x0]);
   For[k = 1, Abs[x1 - x0] < .0001, k = k + 1,
    x1 = (x0 - fun[x0]/fun'[x0]);
    If[Abs[x1 - x0] < 0, x0 = x1, x1 = x1];
    x1]; Print[x1]])

f[x_] := Sin[E^x];
newtMethod[2.5, f]
FindRoot[Sin[E^x] == 0, {x, 2.5}]

A: Worth putting it out there that the For loop is not your friend. This does the same
newtonOneLine // Clear
newtonOneLine[fun_, x0_, tol_ : .0001, maxIters_ : 1000] :=

 Module[{fp = fun'},
  FixedPoint[# - (fun[#]/fp[#]) &,
   x0,
   SameTest -> (Abs[#1 - #2] < tol &)
   ]
  ]

A: Well, since interest in Newton's method never seems to fade on this site, here's a Iterator[] based approach:
Needs@"GeneralUtilities`";

(*
 * fixedPointIterator
 *   Returns x = f[x] unless x == f[x]
 *)
ClearAll[fixedPointIterator];
fixedPointIterator[f_, x0_, sameQ_ : SameQ] :=
 GeneralUtilities`NewIterator[
  fixedPointIterator,  (* name *)
  {x = x0},            (* state variables *)
  With[{xx = f[x]},    (* iterator action *)
   If[sameQ[x, xx],
    GeneralUtilities`IteratorExhausted,
    x = xx]]
  ]

newtonIterator[f_, x0_, sameQ_ : Equal] :=
 fixedPointIterator[# - f[#]/f'[#] &, x0, sameQ]

ff[x_] := Sin[E^x];
rootIt = newtonIterator[ff, 2.5];

ReadList[rootIt, 100 (* max iterations *)]
ff[%] (* check *)

(*
  {2.53316, 2.53103, 2.53102, 2.53102}
  {0.0268055, 0.0000221047, 1.94364*10^-11, -4.89859*10^-16}
*)

Note: Equal compares real numbers with tolerance (equal up to their last seven bits). SameQ compares real numbers with smaller tolerance (equal up to their last bit).  Pass a custom comparator to use a different tolerance.
Also, the overhead of Iterator[] makes it fairly slow compared to, say, FixedPoint[].

A: First, let me just cleaning up the orignal code and the answer from https://mathematica.stackexchange.com/a/234969/148:
newtMethod[guess_, fun_] :=
  Module[{k, x0 = guess, x1},
  x1 = x0 - fun[x0]/fun'[x0];
  For[k = 1, Abs[x1 - x0] < .0001, k++,
   x1 = x0 - fun[x0]/fun'[x0];
   If[Abs[x1 - x0] < 0, x0 = x1, x1 = x1]];
  x1]

This returns the most recent value of x1 rather than printing it; initializes x0 within the first argument to Module; and elides superfluous parentheses.
Note 1: For serious work, you'd want to use a fixed limit on the number of steps, either through hard-coding into the body of newtMethod or as an additional, argument to newtMethod. (For that matter, it would be more generally useful to make the tolerance .0001 another argument to newtMethod.)
Note 2: It is dangerous to use as stopping criterion just closeness of successive x-values to each other, and essential for some functions &meash; those that are fairly flat — to use in addition closeness of the value of f at the current x to the desired value 0.

A: Not at all sure what is going on here.

*

*The For loop test seems backwards. In the test example the logic test is initially not true so the loop isn't executed.

*In the If statement the test for Abs[anything]<0 doesn't seem to make sense?

redpajama_set_name: RedPajamaStackExchange


text:
Q: ffmpeg speed up video - Windows In manual it says:
ffmpeg -i input.mkv -filter:v 'setpts=0.5*PTS' output.mkv

But when I run:
ffmpeg -i input.mp4 -filter:v 'setpts=0.5*PTS' speedup.mp4

I get an error:
[AVFilterGraph @ 0000000002500600] No such filter: 'setpts=0.5*PTS'
Error opening filters!

Not sure if it means that filter can't be opened at all or simply this filter is not available.
How do I run it correctly? Or maybe my release does not support it, then where can I get the release that would work right? Win32/x64 binary

A: if you have your ffmpeg.exe (mine for  windows) for ex you can list all the available filters with this command line, you can edit the  txt file c:\filters.txt to see them.
ffmpeg -filters > c:\yfilters.txt
in mine i can se the filter SETPS (VIDEO TO VIDEO only):
setpts           V->V       Set PTS for the output video frame.
your command line is correct and work with the ffmpeg version that have this filter(try to download the latest version)
this command line works also  for me :
ffmpeg -i video_input -vf  "setpts=factor*PTS"  video_output
the factor can be :
1.for speeding the video 0.2,0.4,0.6,0.8..(<1)
2.for slowing the video:1.2,1.4,1.6,1.8,2.0,3.0,4.0,5.0,10.0... (>1)

A: Use both setpts and atempo to speed up both video and audio:
ffmpeg -i input-video.mp4 -vf "setpts=0.68*PTS" -filter:a "atempo=1.467" output-video.mp4

From: https://trac.ffmpeg.org/wiki/How%20to%20speed%20up%20/%20slow%20down%20a%20video
You'll have to do the right math for the numbers, of course.  The setpts needs to be smaller to make the video go faster, but atempo needs to be larger to speed up the audio.
Audio value needed = 1 / Video value

A: Try using double quotes. e.g. ffmpeg -i input.mp4 -filter:v "setpts=0.5*PTS" speedup.mp4


text:
Q: Online Math Degree Programs Are there any real online mathematics (applied math, statistics, ...) degree programs out there?
I'm full-time employed, thus not having the flexibility of attending an on campus program. I also already have a MSc in Computer Science. My motivation for a math degree is that I like learning and am interested in the subject. I've studied through number of OCW courses on my own, but it would be nice if I could actually be able to have my studying count towards something.
I've done my share of Googling for this, but searching for online degrees seems to bring up a lot of institutions that (at least superficially) seem a bit shady (diploma mills?).

A: I would recommend against getting a degree from any online-only university. Even if you happen to find one that's not shady, everyone else who hasn't heard of it will assume it is some kind of diploma mill without bothering to do much research. Instead, I think you'd be better off going to a nearby university you're interested in, and ask them if they would be willing to make some kind of special arrangement for you. Many universities allow reduced course loads for students that have families or work full time, and aren't very good about advertising it.

A: The University of Washington offers an online masters degree. Their brick-and-mortar programme might make the online diploma more credible.

A: Original author's note: I am deleting my profile and would appreciate it if someone could maintain this answer going forward.

I know this post is very old but I'd like to contribute my likely-too-late response in case it'll help someone else in the future.  Plus I'm in a similar position so I have a few relevant things to say, and I'm sure the landscape has changed significantly since 2010.
First, I see in the comment thread on the question that you were planning on a bachelor's with a potential future interest in a graduate degree.  Since you already have the MSc in comp sci and a clear interest in math then I imagine you have at least a decent math background.  Getting a bachelor's might not be the best idea, especially if you end up being unable to transfer a lot of previously earned credits.  If ultimately you're wanting to pursue a graduate degree then I'd recommend at least trying to start with a graduate program.  It's possible you'd need to take some prerequisite courses but surely this would be better than going through an entire bachelor's program again.  But if you're thinking a bachelor's is all you want then by all means go for it.
I completely understand the feeling of wanting to pursue a degree rather than just self-studying, because I feel the same way and I'm in the same position as you right now.  I do a lot of self-studying and it is certainly enjoyable and fulfilling.  But I share the feeling of wanting to have something to show for it, even if that doesn't mean anything to anybody else.  At the very least, having that degree is a mark of completion.  And with that mark comes that sense of satisfaction from having successfully completed something challenging.  And for me, that's all the motivation I need.  It shows that you individually put yourself on a difficult path and successfully navigated through it.  What would successful completion of an independent study even be?  Finish reading the book?  Work every problem in the book?  Correctly work every problem in the book?  Yes, we can all try to do this navigation with independent studying but there's no accountability there and no clear definition of successful completion.  If you fail at independently studying something (e.g., gave up halfway through, or finished the book and learned nothing, etc.) then no one ever needs to know you tried.  If you fail out of a graduate program then it's quite the blemish on your record and could be difficult/impossible to hide.  My opinion is that pursuing an actual degree, especially if it's just for fun, shows a level of dedication higher than independent studying.  Some may wonder what's the point of showing this level of dedication, especially if it's a just-for-fun pursuit.  I address this in the next paragraph.
As I mentioned, I'm currently in a similar position.  I have two bachelor's (math and computer science) and two master's (math and applied math) degrees and I've been tossing around the idea of getting more graduate degrees, possibly in statistics, computer science, electrical engineering, and even more in math.  Some may (and some already did) scoff and condescendingly tell me the degrees are useless, I'm wasting my time, etc.  Depending on their level of derision, to them I would say something to the effect of, "Cry me a river!  I'm not living my life for you and I'm not obligated to make decisions about my life based on what's appropriate for your own personal world view."  It really surprises me how many people there are who can't comprehend the idea of another person following pursuits and interests that don't line up with their own.  Also, who's to say the degree is completely useless?  We don't know what the future holds.  Maybe you'll find during your studies that you enjoy it more than you ever thought you would, and you want to make a career change.  Maybe you won't want to make a career change but at some point you unexpectedly find yourself in a situation where you need a new job in the same field.  Having pursued a graduate degree from a respectable institution (i.e., not a diploma mill and preferably a regionally accredited school if in the U.S.) while holding down a full-time job should look great to any prospective employer.  And as long as you left your old job on good terms, why shouldn't it look great?  Sure, independently studying while working full time is also challenging and rewarding, but anyone can say they independently studied something, and even if they did we come back to the issue of how to measure success with independent studying.
A more legitimate question I get is, "Why get more math degrees?"  And my answer to that is (1) because I love it and I want to, (2) different schools have different programs and curricula, so doing the same degree at different places doesn't mean I'm doing all of the same courses over and over again, and (3) I have been contemplating pursuing a PhD and I believe I've been out of formal academia too long for that to be possible otherwise.
I'll put the soap box away and go get the list of online programs in math that I've found.
Links are valid as of July 9, 2020.  In no particular order:

*

*The Open University, based in the UK.  As of the time I write this, they take online students overseas and they're actually regionally accredited in the USA.  I may be mistaken but I believe this program doesn't require recommendation letters.  That could be helpful for people who have been out of academia for a while.

*Applied math at Columbia if you've got that kind of cash.

*Texas A&M.  This one has a few options.  There's "traditional" which I guess is like a standard pure math sequence, and I think recently they also put their computational track and math for teachers track online.

*University of Washington.

*Emporia State University.  This program doesn't require recommendation letters, and of course that's subject to change.  I took 2 classes here for fun and they were both very well run; I recommend this for anyone interested in an online MS in math.

*University of Houston MA in math.

*University of Texas Rio Grande Valley.  If I understood correctly, UT Brownsville "merged" into this school and this program is what Brownsville's was.

*University of West Florida.

*Johns Hopkins University Engineering for Professionals.  There's an Applied & Computational Math option and a Financial Math option.

*University of Idaho MA in Teaching that's focused on math.

*Shawnee State University MS in Math, seems pretty well rounded and very affordable.

Updating this post to also include statistics programs, again in no particular order.  Links are valid as of July 9, 2020.

*

*Texas A&M

*Penn State World Campus

*Rochester Institute of Technology

*California State University Fullerton

*University of South Carolina

*Colorado State University

*University of Idaho

*Oklahoma State University

*North Carolina State University

*Stanford University

*University of Delaware

*University of Louisville (Biostatistics)

*University of Kentucky

*Michigan Technological University
I haven't looked for statistics programs as thoroughly as I did with math programs so I'm sure there are at least a few others out there that aren't from online-only schools.
I should also point out that a lot of these schools, and many others not listed here, also have certificate programs which usually have more lax entry requirements.  Most of these certificate programs don't require letters of recommendation.  This is a good way to get back into academia if you've been gone for a while but need letters to get into the program of your choice.  A lot of schools (like Texas A&M as of the time I write this) will also allow people to take courses as a non-degree student and you can even transfer a certain amount of credits if you get accepted into a degree program later.
[Added on 14/10/2020(DD/MM/YYYY)]

*

*List of colleges offering M.Sc Mathematics through Distance Education/Correspondence in India

*Another list of the unis providing distance learning in India

*Uni Birkbeck: MATHEMATICS BY DISTANCE LEARNING (GRADUATE CERTIFICATE)

*Certificate of Pure Mathematics

*University of North Alabama: M.S. in Mathematics Program

*University of Houston Downtown: Certificate in Graduate Mathematics

A: For my experience, the Open University is well-respected internationally.
[Note this is different to Open Universities, such as this in Australia, which is a collaboration of several universities.]

A: The Rochester Institute of Technology offers a MS in applied statistics that is completely online (I think, I'm not enrolled yet.)
http://www.rit.edu/emcs/ptgrad/_program_detail.php?id=441
It's pretty expensive, since it combines the increased out-of-state tuition with the extra online cost. However an online degree such as this is good for working professionals who
1) Can't take classes during the day and
2) Can get their employer to pay for most of the degree.

A: *

*Penn State has a Master of Applied Statistics.

*Stanford has
Computational and Math Engineering.

From what I've read, many universities will not make a distinction on the degree stating whether it was earned online or not.

A: I don't know if you're still looking, but I found this page in my own search for an online math program.
http://www.onlinecollege.org/bachelors/mathematics/

A: Southern New Hampshire Unviersity offers a BA in Math both on campus and online. This is a traditional, not-for-profit university.

A: For future readers: If you happen to speak German, by far the best option is the "Fernuniversität in Hagen", which offers a fully accredited mathematics bachelor and masters programme, full or part time. These are both more affordable and more rigorous (at least the bachelor) than comparable programmes offered by American universities and are just as trustworthy and high quality as those offered by any other German university (even more so if you ask me because the quality of the material they provide is excellent).

A: 'Are there any real online mathematics (applied math, statistics, ...) degree programs out there?' That's real as opposed to imaginary, right? Heh, heh.  :)
No, but seriously, I think you should just pursue your interests privately, without worrying about getting more pieces of paper than you need- your MSc is already proof of your academic proficiency and ability to complete challenging assignments correctly.
I reckon most employers, and other people, would be convinced that you take your maths hobby seriously and study it as carefully as you studied for your MSc.
I am also studying mathematics as a solo enthusiast and I just show people some of the proofs I am studying that week, if they are interested in finding out more. I am sure that's what the likes of Ramanujan would have done, so that'll do for me too!


text:
Q: Publish files in open splice DDS I have successfully created a publisher and subscriber with primitive types. Now I have a problem when trying to publish a file (like xml, txt, video, audio etc) to DDS. I don't know how to specify the types in IDL file and how to publish the whole file to DDS (also how to receive the file on the subscriber side).
And one more question: "Are there any memory limitations to publishing in DDS?"

A: There are several routes you can go for distributing a file using DDS. The most straightforward (but not necessarily the best) is using a sequence of octets (bytes) to capture the contents of the file. This can be achieved by an IDL definition like this:
const long MAX_NAME_LEN = 128;
const long MAX_FILE_SIZE = 100000;

typedef string<MAX_NAME_LEN> NameType;
typedef sequence<octet,MAX_FILE_SIZE> BinaryContentsType;

struct BinaryFile {
    NameType name; //@key
    BinaryContentsType contents;
};
#pragma keylist BinaryFile name

Since your question is not specific for OpenSplice DDS, but could be applied to any DDS implementation, I have included syntax for defining the key attribute such that it works with several implementations.
In your application, you will have to instantiate the type and fill the values of the members. This will look something like
BinaryFile instance = new BinaryFile();
instance.name = "SomeFileName";
// fill instance.contents by reading file into array of bytes.

The contents attribute will be an array of bytes. After the contents have been filled, just invoke the write method on a BinaryFileDataWriter, similar to what other examples do.
There is no real limit to the size of the file distributed this way other than the limits of the shared memory as configured. However, it is good practice to impose a limit on the size, which is why the sequence in the BinaryContentsType type is bounded.
You have not mentioned what programming language you are using, so it is hard to give any coding details. But since you mentioned that you did get started with basic types, it should be easy to figure out how to publish the BinaryFileType type, especially if you take a look at the provided documentation and examples and apply that to your own type.
As a note on the side, are you sure that you want to distribute complete files? Depending on the situation, a better approach might be to analyse the structure of the contents of the file and create a data-model that matches that. You would be reading the file on the publisher side and translate it into meaningful data-items as opposed to a blob. That way, subscribers can take advantage of more advanced data management features, like subscribing to a subset of the contents by subscribing to a subset of the available Topics only, or by using a filter based on content. Whether this makes sense all depends on your use case though.

A: But the real question is -- why?  Transporting opaque data via DCPS is one thing, but entire files?  Aren't there several protocols much better suited to this?  Do you keep lots of files in memory such that you consider file transfers akin to IPC?  My answer to you is to seek out FTP, NFS, SSHFS, SMB, or HTTP.  All of these can peacefully coexist with your DDS traffic, and you would likely see no net benefit to using DDS for the file transfer.
Reinier's answer is correct, per the question. (BTW you should really consider accepting some of the answers -- you have two outstanding!  You might not get anyone on SO to answer your next question).

A: One benefit that DDS can bring to sending files is for the case where you want to send a file to multiple recipients.  Through the use of a reliable protocol built on top of UDP with Multicast enabled, you can then send the file to several recipients at the same time without incurring the bandwidth usage to perform multiple file transfers.


text:
Q: Shell script csv to german readable excel I have a UTF-8 encoded csv which uses , as delimiter and . for decimals.
To make it work with German excel, I think I need latin1 encoding ; as delimiter and , for decimals.
Here is my shell script I have so far. (I am working on a Mac and it is supposed to work on Mac, no other os needed)
#!/bin/bash
FILE=$1

# replace , to ; and . to ,
tr , ';' < $FILE > de1$FILE
tr '.' ',' < de1$FILE > de2$FILE

# change encoding
iconv -f UTF-8 -t LATIN1 < de2$FILE > de3$FILE
open de3$FILE

My Problem:
If I open with excel ö and other German special characters are still messed up.
This is the input csv
Göttingen, ä,
ü, pü

This is the output when I open with excel

or here in plain text:
Gˆttingen  ‰
¸ p¸


text:
Q: Salvar o carrinho de compras quando uma transação é negada e página redirecionada O meu gateway de pagamento tem um problema quando um transação é negada, ele redireciona para uma outra página de pagamento que está toda bugada, então criei uma segunda página de checkout e estou tentando redirecionar o pagamento negado para essa página (redireciono para uma duplicata do meu checkout porque fiz algumas modificações nela, informando que o pagamento foi negado, etc), criei a seguinte função:
function redirect_after_failed( $order_id, $order ) {
    global $wp;
    if ( is_wc_endpoint_url( 'order-pay' ) ) {
        $woocommerce->cart->empty_cart( false );
        wp_redirect( '/finalizar-2' );
        exit;
    }
}
add_action( 'wp', 'redirect_after_failed');

Funciona corretamente quando o usuário está logado em uma conta, porém em minha loja os compradores não criam contas, ou seja, funciona só para mim na conta de administrador.
O problema que encontrei é que o carrinho só é salvo e não apagado quando está com uma conta conectada, quando são visitantes o carrinho não é salvo e é apagado.
Estou a dias tentando encontrar uma solução para salvar os carrinhos de visitantes e quando serem redirecionados os carrinhos see manterem, para poderem ir ao segundo checkout.
Desde já agradeço.


text:
Q: Struts2 jQuery Plugin issue with Double Select I have a little (I hope) issue trying to use Doubleselect element from Struts2 jQuery plugin  and after searching the internet I found nothing about it so I come here to get your help.
I have a jsp with two struts2 jQuery Plugin selects to get the second select (Modelo) loaded based of the item selected from the first one (Fabricante).  When the jsp is loaded, the first select is loaded; but when I select an item from this first select, the value of this selected item does not arrive (is value is null) to the action so there is no way to query the values for the second select from database; consequently, second select is never loaded.
I have followed the sample from the struts2-jquery-showcase.
Some info about my app:

*

*struts2 2.3

*tiles

*Spring 3.1 (I have struts2-spring integration)

Following the code snippets from some files
JSP code for the tiles layout

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
<tiles:importAttribute/>

<...>

        <sj:head jqueryui="true" />

             <tiles:insertAttribute name="header" />
             <tiles:insertAttribute name="menu" />

<...>
             <tiles:insertAttribute name="content" />

JSP code

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="display" uri="http://displaytag.sf.net"%>
<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
<...>
<s:form action="nuevaReparacion2" validate="true" onsubmit="return checkSubmit();" name="formulario" method="post">
<...>

             Fabricante:
            <s:url id="remoteurl" action="nuevaReparacionCargaModelo"/>
            <sj:select
                    href="%{remoteurl}"
                    id="selectFab"
                    onChangeTopics="reloadModelos"
                    name="idFabricante"
                    list="listFabricantes"
                    listKey="id"
                    listValue="nombre"
                    emptyOption="false"
                    headerKey="-1"
                    headerValue="Seleccione un fabricante"
                    indicator="indicator"
                />

            Modelo:
            <sj:select
                    href="%{remoteurl}"
                    id="selectMod"
                    formIds="formulario"
                    reloadTopics="reloadModelos"
                    name="idModelo"
                    list="listModelos"
                    listKey="id"
                    listValue="nombre"
                    emptyOption="false"
                    headerKey="-1"
                    headerValue="Seleccione un modelo"
                    indicator="indicator2"
                />

<...>

web.xml

<...>
 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/classes/spring-context.xml</param-value>
  </context-param>

  <context-param>
    <param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
    <param-value>/WEB-INF/classes/tiles.xml</param-value>
  </context-param>

  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>

   <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/struts/*</url-pattern>
    </filter-mapping>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>*.action</url-pattern>
  </filter-mapping>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
  </listener>

  <listener>
    <listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
  </listener>
<...>

struts.xml
<...>
      <interceptor-stack name="authenticationMinimalStack">
        <interceptor-ref name="exception" />
        <interceptor-ref name="servletConfig" />
        <interceptor-ref name="securityInterceptor" />
        <interceptor-ref name="prepare" />
        <interceptor-ref name="checkbox" />
        <interceptor-ref name="multiselect" />
        <interceptor-ref name="chain" />
        <interceptor-ref name="fileUpload">

            <param name="maximumSize">80000000</param>
        </interceptor-ref>
        <interceptor-ref name="modelDriven"/>
        <interceptor-ref name="staticParams" />
        <interceptor-ref name="params"/>
        <interceptor-ref name="workflow" />
      </interceptor-stack>
<...>
<...>
   <action name="nuevaReparacionCargaModelo" method="cargaModeloFabricante" class="nuevaReparacionAction">
      <interceptor-ref name="authenticationMinimalStack" />
      <result name="pajax" type="json"></result>
    </action>
<...>

Action class code

public class NuevaReparacionAction extends AbstractAction<NuevaReparacionForm> {
<...>
public String init() throws Exception {

        if (model.getListFabricantes() == null) {
            List<Fabricante> listFabricantes = referenceDataService.getAllFabricantes();
            model.setListFabricantes(listFabricantes);

        }
<...>
}
<...>
    public String cargaModeloFabricante()  throws Exception {

        if(StringUtils.isNotEmpty(idFabricante)){
            List<Modelo> listModelos = referenceDataService.getAllModelosPorFab(idFabricante);
            model.setListModelos(listModelos);
        }

        String res = "pajax";
        return res;
    }
<...>
}

Form class code

public class NuevaReparacionForm extends AbstractActionForm {
<...>
private List<Fabricante> listFabricantes;
    private String idFabricante;
    private List<Modelo> listModelos;
    private String idModelo;
<...>
public List<Fabricante> getListFabricantes() {
        return listFabricantes;
    }

    public void setListFabricantes(List<Fabricante> listFabricantes) {
        this.listFabricantes = listFabricantes;
    }

    public String getIdFabricante() {
        return idFabricante;
    }

    public void setIdFabricante(String idFabricante) {
        this.idFabricante = idFabricante;
    }
    public List<Modelo> getListModelos() {
        return listModelos;
    }

    public void setListModelos(List<Modelo> listModelos) {
        this.listModelos = listModelos;
    }

    public String getIdModelo() {
        return idModelo;
    }

    public void setIdModelo(String idModelo) {
        this.idModelo = idModelo;
    }

<...>

The Fabricante bean

public class Fabricante extends AbstractObject<Long> {

    private static final long serialVersionUID = -3767216824782509270L;

    private boolean indRepara;

    public boolean isIndRepara() {
        return indRepara;
    }

    public void setIndRepara(boolean indRepara) {
        this.indRepara = indRepara;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }

        if (obj == null) {
            return false;
        }

        if (!obj.getClass().equals(getClass())) {
            return false;
        }

        Fabricante castedObj = (Fabricante) obj;
        return ObjectUtils.equals(getId(), castedObj.getId());
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                   .append("id", getId())
                   .append("nombre", getNombre())
                   .toString();
    }
}

The Modelo bean
public class Modelo extends AbstractObject<Long> {

    private static final long serialVersionUID = -5167217040308921281L;

    private Fabricante fabricante;

    public Fabricante getFabricante() {
        return fabricante;
    }

    public void setFabricante(Fabricante fabricante) {
        this.fabricante = fabricante;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }

        if (obj == null) {
            return false;
        }

        if (!obj.getClass().equals(getClass())) {
            return false;
        }

        Modelo castedObj = (Modelo) obj;
        return ObjectUtils.equals(getId(), castedObj.getId());
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                   .append("id", getId())
                   .append("nombre", getNombre())
                   .toString();
    }
}

The superclass for the beans

public class AbstractObject<T>  {

    /**
     *
     */
    private static final long serialVersionUID = 7717102673045778131L;
    /**
     * The object id
     */
    private T id;
    private String nombre;

    /**
     * Setter for attribute "id"
     * @param id the object id
     *
    public void setId(T id) {
        this.id = id;
    }

    /**
     * Getter for attribute "id"
     * @return the object id
     *
    public T getId() {
        return id;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

}

Thanks in advance.


text:
Q: python : refer to different pip directory I have a user account (named tamtam) on a remote server, and therefore I do not have permissions to /usr/bin/.
Current situation
$which -a python3
/usr/bin/python3                    #no permission
$which -a pip
/usr/prakt/tamtam/.local/bin/pip   #have permission, "local pip"
/usr/bin/pip                       #no permission, "system pip"

Basically, I am able to install python packages to my local pip but not my system pip. But because my python3 interpreter is linked to the system pip, it can't access the python packages that I installed thru my local pip.
What I would like
I would like to install and run my own python packages. Can I link my system python3 to my local pip instead of the system pip?
If not, what are some workarounds? Thank you.

A: This will force Python to run that pip:
python -m /usr/prakt/tamtam/.local/bin/pip install <package>
Then later (I recommend):
$ cd /usr/prakt/tamtam/.local/bin # first change the dir to where your pip is
$ python -m ./pip install virtualenv
$ cd /path/to/prj
$ virtualenv env
$ source env/bin/activate
(env) $ pip install <package>
(env) $ deactivate

Thus the pip you have access to will create ANOTHER pip that is isolated with an environment. You should have complete control over that pip and python from there on; more here.


text:
Q: Will Angular reevaluate identical $watch expressions in the same $digest cycle? If I have a template in the form of:

will the ngController scope call exFn twice per $digest, or will the scope remember that the exFn() expression's new value and use it instead of reevaluating the expression?

A: It will call exFn four times. Twice to find out the original value for each watch, then twice again to see if they are stable. This makes sense: the function could depend on external state.


text:
Q: Merge two MySQL tables I have two tables: data and comments
data:
-------------------
id | name | email |

pics:
-------------------
msg_id | pic |

The data is assosiated by id and msg_id. How I can merge this two tables into final one?
Edit: some rows in data don't have associated a pic, and i need to keep them.

A: You may want to use the INSERT INTO ... SELECT syntax:
INSERT INTO final_table
SELECT id, name, email, pic
FROM   data
JOIN   pics ON (pics.msg_id = data.id);

Example:
Your current data:
CREATE TABLE data (id int, name varchar(20), email varchar(100));
INSERT INTO data VALUES (1, 'name1', 'a@example.com');
INSERT INTO data VALUES (2, 'name2', 'b@example.com');
INSERT INTO data VALUES (3, 'name3', 'c@example.com');
INSERT INTO data VALUES (4, 'name4', 'd@example.com');

CREATE TABLE pics (msg_id int, pic varchar(100));
INSERT INTO pics VALUES (1, 'pic1.jpg');
INSERT INTO pics VALUES (1, 'pic2.jpg');
INSERT INTO pics VALUES (2, 'pic3.jpg');
INSERT INTO pics VALUES (2, 'pic4.jpg');
INSERT INTO pics VALUES (3, 'pic5.jpg');

Your new table:
CREATE TABLE final_table (
  id int, name varchar(20), email varchar(100), pic varchar(100)
);

INSERT INTO final_table
SELECT      id, name, email, pic
FROM        data
LEFT JOIN   pics ON (pics.msg_id = data.id);

Result:
SELECT * FROM final_table;
+------+-------+---------------+----------+
| id   | name  | email         | pic      |
+------+-------+---------------+----------+
|    1 | name1 | a@example.com | pic1.jpg |
|    1 | name1 | a@example.com | pic2.jpg |
|    2 | name2 | b@example.com | pic3.jpg |
|    2 | name2 | b@example.com | pic4.jpg |
|    3 | name3 | c@example.com | pic5.jpg |
|    4 | name4 | d@example.com | NULL     |
+------+-------+---------------+----------+
6 rows in set (0.00 sec)

A: Probably you need to fetch data from both table and join them into a single one? So you could use the following query:
SELECT D.*, P.* FROM data D, pics P WHERE D.Id=P.msg_id


text:
Q: Parsing a folder moving files depending on file name I am trying to create a batch file.
It should let specify a source and destination folder. The source folder will be parsed and depending on part of the file name the file will be moved to the destination folder. There will be multiple files in the source folder to be parsed.
The files will be something like file-1-tmp.txt,  file-2-tmp.txt, file-3-tmp.txt etc.
I looked at using the FOR /F command using tokens and delims of - - but can't get it to recourse all of the files in the folder
If the file has -1- it will be moved to destination if a file has -2- it will be moved to another destination.
ps: Please help before I loose all my hair

A: Can you just do multiple commands, one for each type of file?:
for %%i in (*-1-*.*) do move "%%i" dir1\.
for %%i in (*-2-*.*) do move "%%i" dir2\.
for %%i in (*-3-*.*) do move "%%i" dir3\.
...etc...

UPDATE
Based on @Andriy M's suggestion, a simpler approach would be:
for %%n in (1 2 3 <...etc...>) do move *-%%n-*.* dir%%n\.

A: There may be various approaches to this problem.
For instance, you could use a separate command for every set of files that need to be moved to the same destination, like in @Loadmaster's answer.
A rather different approach would be to iterate over all the files, determining each one's destination as you go. The implementation of this approach might look like this:
@ECHO OFF
FOR %%I IN ("D:\path\to\source\file-*-tmp.txt") DO (
  FOR /F "tokens=2 delims=-" %%C IN ("%%C") DO (
    IF %%C == 1 (
      MOVE %%I D:\path\to\destination\1
    ) ELSE IF %%C == 2 (
      MOVE %%I D:\path\to\destination\2
    ) ELSE IF ...
    ...
  )
)

That is, you iterate over the files stored in a specific folder and matching a specific mask using a simple FOR loop. In the loop body, you use another loop, a FOR /F one, to split the name and get to the part that determines the destination. Once you've got that part, you compare it individually to all possible values using a set of nested IF commands, and for each match you specify a MOVE command to place the file accordingly.
You could also modify the above script in a way that would allow you to specify destination paths more conveniently. In particular, you could prepare a set of variables containing all possible destination paths, at the beginning of the script. In the inner loop's body, instead of multiple IFs you would use just one that determines whether a "destination variable" corresponding to the extracted part exists. If it does, you just use the path stored in that variable to move the file to. Here's how this variation might be implemented:
@ECHO OFF
SETLOCAL
SET "dest1=D:\path\to\destination\1"
SET "dest2=D:\path\to\destination\2"
...
FOR %%I IN ("D:\path\to\source\file-*-tmp.txt") DO (
  FOR /F "tokens=2 delims=-" %%C IN ("%%C") DO (
    SETLOCAL EnableDelayedExpansion
    IF DEFINED dest%%C MOVE %%I !dest%%C!
    ENDLOCAL
  )
)


text:
Q: What are the compiled costs of each Formula function Each formula function has a compiled cost that contributes towards the hard 5000 compiled character formula limit.
What are the current compiled costs associated with each formula function?

A: Notes:

*

*There are a lot of functions to check, so building a complete list will take a bit of work. I've made this a community post so others can contribute if they like.

*Salesforce changes the implementation of functions over time, so the exact costs can change.

*Determining the compiled formula cost currently relies of comparing the compiled size of a formula that includes the function with one that doesn't. There may be other factors that affect the compiled size of a function. For instance, some functions cost depends on the argument values.

Math Operators

*

*+: 3

*-: 3

**: 3

*/: 3

*^: 9

*(): 1 each (each pair costs 2)

Logical Operators and Logical Functions

*

*AND/&&: 7 for two parameters, 6 for each extra parameter

*CASE: 27 for minimum 4 parameters, 12 for each extra pair of parameters

*

*In Spring '21 using a picklist field, 84 minimum for 4 parameters, 64 for each extra pair of parameters

*IF: 26

*ISNULL: 10

*ISNUMBER: 81

*NOT, !: 6

*OR/||: 6 for two parameters, 5 for each extra parameter

*<, >, =: 3

*>=, <=, <>: 4

*ISCHANGED: ?

*ISNEW: ?

Text Operators

*

*&, +: 4

Date and Time Functions

*

*+: 3

*DATE: ?

*DATEVALUE: 30

*DATETIMEVALUE: ?

*DAY: 19

*MONTH: 21

*NOW: 7

*TODAY: 9

*YEAR: 20

*ADDMONTHS: 15

Informational Functions

*

*BLANKVALUE

*ISBLANK

*ISNULL

*NULLVALUE

*PRIORVALUE

Math Functions

*

*ABS: 5

*CEILING: 112

*EXP: 5

*FLOOR: 112

*LN: 4

*LOG: 9

*MAX: 12 for two parameters, plus 2 per extra parameter

*MIN: 9 for two parameters, plus 2 per extra parameter

*MOD: 7, plus length of second parameter

*ROUND: 9, plus length of second parameter

*SQRT: 6

Text Functions

*

*BEGINS - 57 + length of length parameter

*BR - 18

*CASESAFEID ~ 2073. Depends on Reference & Object.  CASESAFEID(Foo__c) takes less than CASESAFEID(Foo__r.Id). Standard Objects seem to take less than custom - Idea to reduce size

*CONTAINS - 58 +length of length parameter

*FIND - 46

*GETSESSIONID - 13

*HYPERLINK - Base of 88, increases by 1 for each url and friendly_name character.

*IMAGE - Base of 19, increases by 1 for each image_url and alternative_text character

*INCLUDES

*ISPICKVAL - ~ 51-53, no cost/optimized out if the test value is not one of the active or inactive picklist values

*LEFT - 26+length of length parameter

*LEN - 15

*LOWER - 37

*LPAD

*MID - 38+length of length parameters.

*RIGHT - 45+length of length parameter

*RPAD

*SUBSTITUTE - 29

*TEXT - 42 for Number field, 64 for DateTime field

*TRIM - 18

*UPPER - 37

*VALUE - 23

Summary Functions

*

*PARENTGROUPVAL

*PREVGROUPVAL

Advanced Functions

*

*GETRECORDIDS

*INCLUDE

*LINKTO

*REGEX

*REQUIRESCRIPT

*URLFOR

*VLOOKUP

Encoding Functions

*

*HTMLENCODE

*JSENCODE

*JSINHTMLENCODE

*URLENCODE

Other Notes
Some optizations exist in the compiler engine. For example, mathematical operations that do not involve fields are "solved" to their final value. For example, 1+5 compiles to just 1 character, because the result is always 6. Similarly, functions like NULLVALUE use no extra characters if the field is required (e.g. NULLVALUE(Name,'No Name') uses 12 characters).


text:
Q: Executing a cURL request to an background remover API from PHP throws file not found error I am new to cURL from PHP. I am trying to send file URL as post field and API Key as header to the background remover API to retrieve the background removed image. The error says:

{"errors":[{"title":"No image given","code":"missing_source","detail":"Please provide the source image in the image_url, image_file or image_file_b64 parameter."}]}

My code:
<?php
    $url='https://api.remove.bg/v1.0/removebg';
    $ch = curl_init($url);
    $data = array('image_url'=> 'https://www.requestingservicebyme.com/upload/imageexample.jpg');
    $headers1=['X-API-Key:xxxxxxxxxxxxxxx',
    'Content-Type:application/json'];
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    $buffer = curl_exec($ch);

      if (empty($buffer)) {
         echo " buffer is empty ";
      } else{
         echo $buffer;
      }
      curl_close($ch);
?>

A: I was also working on it using the curl I got success in that ..!
Change your headers
Remove the application type json from headers as this api returns the data in Image content format.
$x = curl_init();

$headers=['X-API-Key:xxxxxxxxxxxxxxxxx'];
$data = array (

'image_url' => "https://amblin.com/wp-content/uploads/2019/09/castaway_2000_photo_29.jpg",
'size' => "auto",
);
$url = 'https://api.remove.bg/v1.0/removebg';
// $post = http_build_query($data);
$x = curl_init($url);
curl_setopt($x, CURLOPT_POST, true);
curl_setopt($x, CURLOPT_RETURNTRANSFER, true);
curl_setopt($x, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($x, CURLOPT_HTTPHEADER, $headers);
curl_setopt($x, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($x, CURLOPT_POSTFIELDS, $data);
$y = curl_exec($x);
curl_close($x);

//And then save it using this code
$fp = fopen("result.jpg", "wb");
fwrite($fp, $y);
fclose($fp);


text:
Q: error writing in a file in json format.Stream closed       HttpGet getRequest=new HttpGet("/rest/auth/1/session/");
          getRequest.setHeaders(headers);
          HttpHost target = new HttpHost("localhost", 8080, "http");
          HttpPost postRequest = new HttpPost("/rest/auth/1/session/");
          System.out.println("executing request to "+target +getRequest);
          HttpResponse httpResponse = httpclient.execute(target,postRequest);
          HttpEntity entity = httpResponse.getEntity();
          if (entity != null) {
            System.out.println(EntityUtils.toString(entity));
          }

the response from servers is in Json format is stored in httpresponse and we get the entity and put it in httpentity
 File fJsonFile = new File("C:\\Users\\Ashish\\Desktop\\filename.json");
              try {
                    // if file doesnt exists, then create it
                    if (!fJsonFile.exists()) {
                        fJsonFile.createNewFile();
                    }
                    FileWriter fw = new FileWriter(fJsonFile.getAbsoluteFile());
                    BufferedWriter bw = new BufferedWriter(fw);
                    bw.write(EntityUtils.toString(entity));
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

Output of EntityUtils.toString(entity) is in JSON format
{"self":"http://localhost:8080/rest/api/latest/user?username=vgupta","name":"vgupta","loginInfo":{"loginCount":55,"previousLoginTime":"2014-12-01T11:39:43.883+0530"}}

and following exception at line bw.write(EntityUtils.toString(entity));
java.io.IOException: Stream closed
at java.util.zip.GZIPInputStream.ensureOpen(Unknown Source)
at java.util.zip.GZIPInputStream.read(Unknown Source)
at org.apache.http.client.entity.LazyDecompressingInputStream.read(LazyDecompressingInputStream.java:74)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.Reader.read(Unknown Source)
at org.apache.http.util.EntityUtils.toString(EntityUtils.java:244)
at org.apache.http.util.EntityUtils.toString(EntityUtils.java:288)
at jira.JiraGetPostDeleteReq.main(JiraGetPostDeleteReq.java:68)

how to get rid of this error.
If I want to write JSON in a file.

A: This doesn't seem to be specified in the javadoc, but EntityUtils.toString(HttpEntity) closes the HttpEntity's InputStream. Since you're invoking the method twice with the same HttpEntity, the second time it is already closed.
Instead of invoking it twice, store the result
String content = null;
if (entity != null) {
    content = System.out.println(EntityUtils.toString(entity));
}

and reuse content everywhere else.


text:
Q: InDesign Import I want to create a folder on my desktop. I want to be able to drop in there, maybe 10-20 sized and prepped PDFs. As soon as they go in that folder, I want them to open in Indesign into a SINGLE document, but as separate image boxes, with the path to the graphic connected. Would this be Indesign scripts, automator, both, or more? Some help would be greatly appreciated.

A: Since you are considering Automator, I'm assuming you're working with OS X.
You can set up a folder action with Automator for your watch folder that sits on the desktop, in this folder action, the only thing it needs to do is run an applescript. Here is how the script could look (for InDesign CS6 in my case):
on run {input, parameters}

    tell application "Adobe InDesign CS6"

        activate

        do script "#include ~/desktop/myScript.jsx" language javascript

    end tell

    return input
end run

This will run the script myScript (sitting on the desktop) in InDesign.
Additionally you could add some Automator action after the script to remove the files from the Watchfolder again.
In the .jsx you can access all the files currently in the watch folder like this:
var watchFolder = Folder("~/Desktop/InDesignWatchFolder");
var filesArray = watchFolder.getFiles();

The import procedure itself totally depends on your needs and on your PDFs (single page, multi page, placement options etc.) it can be rather simple or become really complex.
Scott Zanelli has developed a rather sophisticated free script that you could have a look at. You can download it here:
http://indesignsecrets.com/zanelli-releases-multipageimporter-for-importing-both-pdf-and-indd-files.php


text:
Q: Express js caching the index page I have created a authentication system in node using express.js. It works fine but when I try to logout, I am redirecting to the index page. "localhost:3100/". When I go there, Sometime it shows the cached with status as logged-in and some time the new-refreshed page. If referesh the page, every thing goes back to normal. If I redirect to a different page then it works fine.
Is it something especial with index page, that app is rendering the cached version.
This is mainly happening when I am changing the content based on res.locals.currentUser. currentUser is being set in the middleware. In Navbar I am using this <% if(currentUser)% >  <%}else{%> <%}%>. So on redirect, sometime it refreshes and some time it uses the cached view.
Also I am using express.js 3.

A: For your / route you want to add a middleware that will force it to always load without caching. Add this:
app.use(function noCacheForRoot(req, res, next) {
    if (req.url === '/') {
      res.header("Cache-Control", "no-cache, no-store, must-revalidate");
      res.header("Pragma", "no-cache");
      res.header("Expires", 0);
    }
    next();
});

Place this middleware high up on the list, before your app.use(app.router) and  app.user(express.static(...)) statements.


text:
Q: Azure B2C Graph API : Set Account lock for User Wrong login attempts Is there's way to lock Azure B2C Account by sending API call from the code base? I need to write a function for following requirement
After 3 failed login attempts with a wrong password the account should be locked until user unlocked. it should be locked for defined time.
public async Task<string> LockUserAccount(string api, string query)
{

  AuthenticationResult result = authContext.AcquireToken("https://graph.windows.net", credential);

  HttpClient http = new HttpClient();

        **Here I need your help what kind of URL do i need to call here**
        > // string url = "https://graph.windows.net/" + tenant + api + "?" +

        >
        >    //HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);

     request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
     HttpResponseMessage response = await http.SendAsync(request);

        if (!response.IsSuccessStatusCode)
            {
               string error = await response.Content.ReadAsStringAsync();
               object formatted = JsonConvert.DeserializeObject(error);
               throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented));
            }

    return await response.Content.ReadAsStringAsync();
}

I have gone though with this Documentation and it says the lockout interval increases after further failed login attempts: https://learn.microsoft.com/en-us/azure/active-directory/authentication/howto-password-smart-lockout#manage-azure-ad-smart-lockout-values

A: It seems that there is no related api to lock the user for defined time.
You also could give your feedback to Azure team.
My workaround is that we could count the number of attempts. If the 3 failed login attempts then send the user information to servicebus scheduled messages. Then update user to set accountEnabled false.
Afer that we could use the Azure function servicebus trigger to update user to set accountEnabled true


text:
Q: Android SearchView usage example I am trying to implement SearchView in my android app to open an Activity and perform a search task in that activity. For some reason, the activity that SearchView opens gets paused after starting, causing it's onCreate method to be called twice which in turn performs the search twice. Obviously not optimal since this means hitting the backend twice for every request.
I can't figure out why this is happening, so I start to belive this is intended behavior. Can anyone provide a small know working example project that uses SearchView? I looked everywhere for a working example to see if this is indeed the intended behavior, but I had no luck.
Thanks in advance!


text:
Q: EF Core Code First - Create Relational Model in Visual Studio? I created a database by using Entity Framework Core Code First. Now I can view all my tables in my SQL Server Objekt Explorer which kind of looks like this:

Now I would like to create a Relational Model in Visual Studio so I can see all my relationships between my tables. But I can't figure it out how to do it. Is there a way Visual Studio can create a Model with my existing tables or do I need a Relational Database Management System?
I want my Model to look like this:


text:
Q: GTM, Query Strings and Meta Refresh I am trying to get a meta refresh added dynamically to a page using GTM.
<script>
var m = document.createElement('meta http-equiv');
m.name = 'refresh';
m.content = '0;URL='http://google.com?affkey={{affkey}}'';
document.head.appendChild(m);
</script>

When I use the GTM variable tag I get an illegal use error. When I use just the URL with the 0 timer GTM tells me there is a syntax error.
I am not versed well enough to correct it. Is there any help on this? Or pointers to help me correct it?
Thank you!


text:
Q: canvas draw - change rotation axis without clearing old state I'm using html5 canvas to create a simple 3d polygon program. the program allows to change the rotation of each axis - x,y,z. on the event of change x/y/z angle, a corresponding call to the drawing function is done. the problem is every time I make a new call to the draw function it clears the older position and the result is it jumps. basically each function works on its own but they do not work together.
example code:
var Perspective = function(rotate){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
//clear
...
switch(rotate){
case "x" : {
var transform = Mat3.rotationX(Math.radians(rotateX.getValue())); //rotation x
break;
}
case "y" : {
var transform = Mat3.rotationY(Math.radians(rotateY.getValue())); //rotation y
break;
}
case "z" : {
var transform = Mat3.rotationZ(Math.radians(rotateZ.getValue())); //rotation Z
}
...
draw(...settings..)
}

set a listener to each slider change event (also for Y and Z). AngleX makes the call to Perspective, passing the string "x" as rotate param.
var angleX = $('#AngleX').slider()
            .on('slide change', AngleX)
            .data('slider');

how can i make the changes if different axis more dynamic ?

A: anyway i'v solved it no thanks to you QBM5 .. the switch case was a mistake, i had to multiply all axis transformation matrixs like this :
 var transform = Mat3.rotationX(-Math.radians(rotateY.getValue())) .multiply(Mat3.rotationY(Math.radians(rotateX.getValue())));


text:
Q: QRegExp non-capturing parentheses I'm trying to extract "246" from this text:
Responsible: John Doe
Number: 246
Date: 24-12-2005

Using QRegExp, the pattern:
(?:Number: )\d+

I expected to get:
246

But instead I've got:
Number: 246

I'm trying to avoid capturing groups.

A: You probably want a regexp like Number: (\d+) -- this will explicitly capture the digits in group 1, which you can get back with cap(1).  cap(0) will return the whole match including any non-capturing groups like (?:Number: ).

A: You can try this:
(?=Number: (\d+))

In this case the whole pattern is not matched cause it is embedded in a zero-length lookahead, the only result is the capturing group


text:
Q: Nested structure with array of structure pointer Main structure
typedef struct {
   uint8 u8Status;
   uint8 u8NeighborTableEntries;
   uint8 u8StartIndex;
   uint8 u8NeighborTableListCount;
   /* Rest of the message is variable length */
   ZPS_tsAplZdpDiscNtEntry* pNetworkTableList;
                                              //pNetworkTableList is a pointer to
                                              //the first
                                              //entry in the list of reported
                                              //Neighbour table entries
 } ZPS_tsAplZdpMgmtLqiRsp;

typedef struct
{
   uint64 u64ExtPanId;
   uint64 u64ExtendedAddress;
   uint16 u16NwkAddr;
   uint8 u8LinkQuality;
   uint8 u8Depth;
   union
   {
     struct
     {
       unsigned u2DeviceType:2;
       unsigned u2RxOnWhenIdle:2;
       unsigned u2Relationship:3;
       unsigned u1Reserved1:1;
       unsigned u2PermitJoining:2;
       unsigned u6Reserved2:6;
    } ;
    uint8 au8Field[2];
 } uAncAttrs;
} ZPS_tsAplZdpDiscNtEntry;

i have defined ZPS_tsAplZdpMgmtLqiRsp *pointer;
this seems to be okay..
pointer->u8Status
pointer->u8NeighborTableEntries
pointer->u8StartIndex
pointer->u8NeighborTableListCount

but how can i access those values inside the ZPS_tsAplZdpDiscNtEntry structure

A: you get access to the array with: pointer->pNetworkTableList
so from there you can access all elements of the structure..
e.g. access to the u64ExtPanId of the the element with index 0:
pointer->pNetworkTableList[0].u64ExtPanId = 1232;

A: You have the pointer, but you haven't the instance of the structure itself.
Do the next:
ZPS_tsAplZdpMgmtLqiRsp *pointer = (ZPS_tsAplZdpMgmtLqiRsp *)malloc(sizeof(ZPS_tsAplZdpMgmtLqiRsp));

... and yes you should allocate the memory for pNetworkTableList as well:
pointer->pNetworkTableList = (ZPS_tsAplZdpDiscNtEntry *)malloc(sizeof(ZPS_tsAplZdpDiscNtEntry));

then you may
do
 pointer->pNetworkTableList->u8Status = 12;

and so on.
don't forget to do
free(pointer->pNetworkTableList);
free(pointer);

in the end of work.


text: Q: Change the format from [author, year] to (author year) at the end of the citation Now my format is [Bauer et al., 2007], by using the \citep. But I want use the (Bauer et al., 2007). And I tried the method provided by the thread How to change citation style for specific sentence?. It did not work. Could any one help me?


text:
Q: c# using alert box. how to prevent even from happing On button click my input data is sent of to my MySQL server, if the Data is input in wrong in this case if the two drop down list selections do not mathc you get a message sayings its wrong.
problem is the data is still sent to my database.
how can i prevent this?
if (!ddlcountry.SelectedItem.ToString().Equals(ddlcountry_Res.SelectedItem.ToString()))
        {
            Response.Write(@"<script language='javascript'>alert('You are trying to adoped a pet from anouther country !!');</script>");
        }
        else
        {
            Response.Write(@"<script language='javascript'>alert('Congratulations for adopting a pet.');</script>");
        }

My apologies guys, a more comprehensive explanation.
My problem is I have in my on click event a list of insert statements that insert data from text boxes and drop down lists and more, then this if else statement is underneath to check that two drop down selections match.
Problem begin the data input via the text boxes is still getting through to the database, so I would like to stop the data begin sent to the database if the two drop downs do not match.

A: Problem : if i understand it correctly you have written statements after if-else {} block which are getting executed irrespective of the situation (true or false).
Solution:  if that is the case you should reconsider your logic, as you should come out from the executing database queries if your expression/condition evaluates to false.
you can use return keyword to return from the invalid case.
if you return from invalid case further statements( after return ) won't get executed.
try this:
          if (!ddlcountry.SelectedItem.ToString().Equals(ddlcountry_Res.SelectedItem.ToString()))
            {
                Response.Write(@"<script language='javascript'>alert('You are trying to adoped a pet from anouther country !!');</script>");
                return;//return if you don't want to execute further statements
            }
            else
            {
                Response.Write(@"<script language='javascript'>alert('Congratulations for adopting a pet.');</script>");
            }


text:
Q: Object creation R starting with dot (.) and underscore ( _ ) I can able to create object in R which starts with dot (.) but not able to do the same with underscore (_).
Why we can't create object starting with underscore ( _ ) in R?
How it is possible that we can assign object which starts with dot ( . )?
Reason behind object creation which starts with _ and . in R.

A: you can create an object starting with underscore but you need to use quotes or backticks.
`_a` <- 1
"_a" <- 1

You can create the objects in above two ways but access it only via backticks.
`_a`
#[1] 1


text: Q: post-authorize redirect url I am no longer able to edit the post-authorize redirect url field in my app settings and as it still has the old settings it no longer works and no matter what I do with the fields that I can edit it still keeps the old settings and will not work.


text:
Q: Kivy position line based on other widget position I'm trying to draw the orbit groundtrack of the ISS on a map and I think I know how I'll do that once I figure out how to position the line on the map.
To figure out line positioning I'm trying to draw a line from the bottom left of the map to the top right, using the following code (minus extra widgets):
#:import kivy kivy
#:import win kivy.core.window
<Orbit_Screen>:
    name: 'orbit'
    FloatLayout:
        id: orbit_layout
        Image:
            id: OrbitMap
            source: 'C:/Users/Sam/PycharmProjects/Mimic-Development/Pi/imgs/orbit/map.jpg'
            pos_hint: {"center_x": 0.5, "center_y": 0.56}
            size: (500,300)
            #size_hint_y: 0.598
            size_hint: (None,None)
            allow_stretch: False
            keep_ratio: True
        Widget:
            id: TDRS10
            col: (1,1,1,1)
            pos_hint: {'center_x': 0.5, 'center_y': 0.5}
            size_hint: '0.01dp', '0.02dp'
            canvas:
                Color:
                    rgba: self.col
                Ellipse:
                    pos: self.pos
                    size: self.size
                Line:
                    points: (OrbitMap.x,OrbitMap.y,OrbitMap.width,OrbitMap.height)
                    joint: "round"

Which produces the following image:

Can anyone help me understand why the starting x coordinate matches with the map but the y coordinate is below the image and the top right coordinates both fall short? Thanks for any assistance. I really thought I understood widget positioning but I guess not.

A: The OrbitMap is scaled and translated to meet your pos_hint and size specifications from your kv. Assuming that your orbit line coordinates are in pixels relative to the original map, then you will need to translate and scale those coordinates to match the scale and translation applied to the map image. I believe you can accomplish that using this in your kv for the Widget canvas:
Widget:
    id: TDRS10
    col: (1,1,1,1)
    pos_hint: {'center_x': 0.5, 'center_y': 0.5}
    size_hint: '0.01dp', '0.02dp'
    canvas:
        PushMatrix:
        Translate:
            xy: (OrbitMap.x + (OrbitMap.width - OrbitMap.norm_image_size[0])/2, OrbitMap.y + (OrbitMap.height - OrbitMap.norm_image_size[1])/2)
        Scale:
            origin: 0,0
            x: OrbitMap.norm_image_size[0] / OrbitMap.texture_size[0] if OrbitMap.texture_size[0] > 0 else 1
            y: OrbitMap.norm_image_size[1] / OrbitMap.texture_size[1] if OrbitMap.texture_size[1] > 0 else 1
        Color:
            rgba: self.col
        Ellipse:
            pos: self.pos
            size: self.size
        Line:    # test diagonal line 1
            points: (0, 0, OrbitMap.texture_size[0], OrbitMap.texture_size[1])
            joint: "round"
        Line:    # test diagonal line 2
            points: (0, OrbitMap.texture_size[1], OrbitMap.texture_size[0], 0)
            joint: "round"
        Line:    # test norizontal line
            points: (0, OrbitMap.texture_size[1]/2, OrbitMap.texture_size[0], OrbitMap.texture_size[1]/2)
            joint: "round"
        Line:    # test vertical line
            points: (OrbitMap.texture_size[0]/2, 0, OrbitMap.texture_size[0]/2, OrbitMap.texture_size[1])
            joint: "round"
        PopMatrix:

The above uses the canvas Scale and Translate matrices to convert the line coordinates. I have replaced your orbit line with some test lines to make sure that the scheme works.


text:
Q: Numpy installation AWS EC2 Error I tried easy install and pip to install numpy on an EC2 micro instance.   Didn't work.
I get:

RuntimeError: Broken toolchain: cannot link a simple C program

I tried virtualenv too, same story.
What am I doing wrong?

A: You probably don't have the development packages installed.
Amazon Linux run:
sudo yum groupinstall "Development Tools"

Ubuntu run:
sudo apt-get install packaging-dev

A: For simple testing, ssh into your instance
sudo yum install gcc
sudo pip install numpy

then go get yourself a coffee. Installed in about 3.5 mins.


text:
Q: Lambda capture reference variable by reference For a lambda, I'd like to capture something by reference which was held in the outer scope by reference already. Assume that the referenced value outlives the lambda, but not the scope in which the lamdba gets created.
I know that if a lambda captures a reference variable by value, the referenced object will be copied. I'd like to avoid this copy.
But what happens if I capture a reference variable by reference? What if the original reference variable will get out of scope before executing the lambda? Is this safe? In other words: is the object behind the reference referenced or is the reference variable referenced in the lambda?
auto f() {
    const auto & myRef = g();
    return [&]{ myRef.doSomething(); };
}

f()();  // Safe?

A: Yes, the key issue in capturing an object by reference is the lifetime of the referenced object, not the lifetime of any intervening references used to get it.  You can think of a reference as an alias rather than an actual variable.  (And in the type system, references are treated differently from regular variables.)  The reference aliases the original object, and is independent of other aliases used to alias the object (other than the fact that they alias the same object).
=====EDIT=====
According to the answer given to this SO question (pointed out by dyp), it appears that this may not be entirely clear.  Throughout the rest of the language, the concept of a "reference to a reference" doesn't make sense and a reference created from a reference becomes a peer of that reference, but apparently the standard is somewhat ambiguous about this case and lambda-captured references may in some sense be secondary, dependent on the stack frame from which they were captured.  (The explicit verbiage the SO answer quotes specifically calls out the referenced entity, which would on the face indicate that this usage is safe as long as the original object lives, but the binding mechanism may implicate the capture chain as being significant.)
I would hope that this is clarified in C++14/17, and I would prefer it to be clarified to guarantee legality for this usage.  In particular, I think the C++14/17 ability to capture a variable via an expression will make it more difficult to simply capture a scope via a stack-frame pointer and the most sensible capture mechanism would be to generally capture the specific entities individually.  (Perhaps a stack-frame-capture could be permitted if an actual local object is captured by reference, since this would result in UB if the lambda is called outside the scope in any event.)
Until we get some clarification, this may not be portable.


text:
Q: You have an error in your SQL syntax; and $db->query(ERROR: 1) I tried to so hard to find a solution for this but in vain.
I could insert into the db successfully all the data, but still I get the same problem.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1

I did escape my variables, added ticks ` to the table, but still the same problem.
$insert = $db->query("INSERT INTO `uploadusers` (uploadusers.uname, uploadusers.phone, uploadusers.mail, uploadusers.lng, uploadusers.path) VALUES ('" . mysqli_real_escape_string($db, $userName) . "', '" . mysqli_real_escape_string($db, $userPhone)."', '" . mysqli_real_escape_string($db, $userMail)."', '" . mysqli_real_escape_string($db, $userLng)."', '" . mysqli_real_escape_string($db, $path)."')");
                if ($db->query($insert)) {
                        echo "New record created successfully";
                    } else {
                        echo "Error: " . $insert . "<br>" . $db->error;
                    }

When I echo $insert gives me '1' and $db->error gives me that error.

A: The problem here is that you're calling query() twice.
So remove one of them and just do if ($insert)) {
$insert = $db->query("INSERT INTO... ");
    if ($insert) {


text:
Q: Memory issue in Java I've a multi-threaded program which deals with lots of String manipulations and after few hrs of executions the memory exceeds and cause the "java.lang.OutOfMemoryError: Java heap space" issue. And I've already utilized my whole memory to the java program i.e.  16 GB.
For the test I've created following sample program to understand the issue and its doing the same issue, after just re-initializing a string builder few thousand times it consumes more than 5-10MB of memory, can anyone pls help to overcome this issue.
StringBuilder strObj = new StringBuilder();
for(int i=0; i<50000; i++) {
    strObj = null;
    strObj = new StringBuilder();
}

A: In what sense does it consume 5-10MB of memory? you're allocating that much here. Java is not going to bother reclaiming it until it needs memory. This can't be causing OutOfMemoryError, not this type of code.
So, why not actually show the kind of code that is causing the OOME?

A: Thanks for the support guys, actually my problem was resolved after garbage collecting manually by calling System.gc() statement.


text:
Q: SmsReceiver works with API 21 and earlier versions, however doesn't work with API 26 So, i am trying to write an app which will send SMS messages, receive and see the messages that have been sent. So far i can send a message, but receiving messages is not working on API 26. My next emulator is API 21 and on that version Toast message appears when message is received.
I have successfully managed permissions required for sending and receiving a sms message.
I have read some documentation, but can't quite find what i need. If there is someone who knows what the problem is i would be thankful for help.
public class SmsReceiver extends BroadcastReceiver {
private static final String TAG = "SmsReceiver";

@Override
public void onReceive(Context context, Intent intent) {

    Bundle bundle = intent.getExtras();

    if(bundle != null) {
        Object[] pdus = (Object[]) bundle.get("pdus");
        SmsMessage[] messages = new SmsMessage[pdus.length];
        String message = "";

        for(int i = 0; i < pdus.length; i++) {
            messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
            if(i == 0) {
                message += messages[i].getOriginatingAddress() + ": ";
            }
            message += messages[i].getMessageBody();
            Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        }
    }
}

}
Manifest file

<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <receiver android:name="package.name"
        android:exported="true"
        android:permission="android.permission.BROADCAST_SMS">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

I hope this is enough, if needed i can provide other class or manifest file. Thanks in advance

A: you have to get the user's permission on runtime with below pseudo code :
public static void requestPermissionForReadSMS(Fragment fragment) {
        if (fragment.shouldShowRequestPermissionRationale(Manifest.permission.READ_SMS)) {
            Helpers.showRequestPermissionAlertDialog(fragment, fragment.getString(R.string.read_sms_permission), fragment.getString(R.string.permission_request));

        } else {
        fragment.requestPermissions(new String[]{Manifest.permission.RECEIVE_SMS},
                Constants.READ_SMS_PERMISSION);
        }

}

after that your BroadcastReceiver will work
also you can add BROADCAST_SMS to your receiver tag inside your manifest :
<receiver android:name="packagename.SmsReceiver"
    android:exported="true"
    android:permission="android.permission.BROADCAST_SMS">
    <intent-filter
        android:priority="4876123720">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

in addition you can read about "SMS Retriever" api witch is provided by official document for receiving sms in your application

A: I was completely missing the point on my question. The mistake that was producing wrong behavior was tied to intent for receiving messages. I thought that i could use same intent for printing sent messages and receiving messages. In the end when i created custom intent for receiving an sms and it worked.


text:
Q: uWSGI logging not working if log file is removed My goal is rotating the logs generated by uWSGI, but when the original log file is deleted (after compression) it is not re-created again.
So I thought that the app needs a graceful restart of the master process after the file is deleted. I use this RESTART script:
/home/tester/uwsgi-18
--reload /var/run/uwsgi/my_app_tester/my_app_tester.pid

The app restart, but the log does not.
To get the logging work again I need to kill -2 the process and run the START script again, so another process number is generated and the logging works again.
Obviously I do not want such hard STOP just for rotating logs...
My app is built with Catalyst, the server runs Nginx and here it is the uWSGI START script:
/home/tester/uwsgi-18
--master
--daemonize /var/log/uwsgi/my_app_tester/log
--socket /tmp/uwsgi/my_app_tester/my_app_tester.socket
--processes 1
--psgi /home/tester/my_app/my_app.psgi
--pidfile /var/run/uwsgi/my_app_tester/my_app_tester.pid
--procname-master TESTER
-L

Is there another way to restart the app without loosing connections and logging?
Thank you in advance:
Migue

A: You have various approaches:
1) copytruncate in the logrotate script, this will work reliably and without the help of uWSGI
2) uWSGI log rotation: --log-maxsize <bytes> will automatically rotate logs when a specific size is reached
3) classic logrotation + log reloading, just add --log-master and trigger log reloading with http://uwsgi-docs.readthedocs.org/en/latest/MasterFIFO.html
There are other approaches too (like triggering the log reopen when touching a files), but the previous one are the most common.


text:
Q: What's the point of dnsmasq in NetworkManager? I very recently came to realize that the caching is disabled by default on the dnsmasq that is integrated with NetworkManager. In my mind, that defeats the point and makes dnsmasq a redundant layer in name resolution.
Obviously, I must be missing something - what is the purpose of dnsmasq in NM?

A: The point is that switching nameservers is annoying. /etc/resolv.conf only gets read once when you start an application (technically when you do the first lookup), so if you change nameservers (because you moved from wireless to wired to 3g and back etc.), you will need to restart applications that need to look up names (such as browsers).
This is mitigated by using the local resolver, which does respond to these changes in a timely fashion, allowing applications to remain stupid and only query the nameserver on localhost.

A: From man NetworkManager.conf on 16.04, on the dns option:

dnsmasq: NetworkManager will run dnsmasq as a local caching
nameserver, using a "split DNS" configuration if you are connected
to a VPN, and then update resolv.conf to point to the local nameserver.

So basically if you connect to a VPN, NetworkManager can instruct dnsmasq to use any VPN-specific DNS servers for required domains. This is impossible to do with just resolv.conf.


text:
Q: Parsing error: Cannot read file '.../tsconfig.json'.eslint The error Parsing error: Cannot read file '.../tsconfig.json'.eslint shows in all .ts files in the src folder including index.ts.
I have no idea how to set up configs. The issue just shows a red line and makes the file red. However, everything compiles and run fine. The entire Node project was created using the firebase CLI.
tsconfig.json file:
{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "es2017"
  },
  "compileOnSave": true,
  "include": [
    "src"
  ]
}

.eslintrc.js file:
module.exports = {
  env: {
    browser: true,
    es6: true,
    node: true,
  },
  extends: [
    "plugin:import/errors",
    "plugin:import/warnings",
    "plugin:import/typescript",
  ],
  parser: "@typescript-eslint/parser",
  parserOptions: {
    project: "tsconfig.json",
    sourceType: "module",
  },
  plugins: [
    "@typescript-eslint",
    "import",
  ],
  rules: {
    "@typescript-eslint/adjacent-overload-signatures": "error",
    "@typescript-eslint/no-empty-function": "error",
    "@typescript-eslint/no-empty-interface": "warn",
    "@typescript-eslint/no-floating-promises": "error",
    "@typescript-eslint/no-namespace": "error",
    "@typescript-eslint/no-unnecessary-type-assertion": "error",
    "@typescript-eslint/prefer-for-of": "warn",
    "@typescript-eslint/triple-slash-reference": "error",
    "@typescript-eslint/unified-signatures": "warn",
    "comma-dangle": "warn",
    "constructor-super": "error",
    eqeqeq: ["warn", "always"],
    "import/no-deprecated": "warn",
    "import/no-extraneous-dependencies": "error",
    "import/no-unassigned-import": "warn",
    "no-cond-assign": "error",
    "no-duplicate-case": "error",
    "no-duplicate-imports": "error",
    "no-empty": [
      "error",
      {
        allowEmptyCatch: true,
      },
    ],
    "no-invalid-this": "error",
    "no-new-wrappers": "error",
    "no-param-reassign": "error",
    "no-redeclare": "error",
    "no-sequences": "error",
    "no-shadow": [
      "error",
      {
        hoist: "all",
      },
    ],
    "no-throw-literal": "error",
    "no-unsafe-finally": "error",
    "no-unused-labels": "error",
    "no-var": "warn",
    "no-void": "error",
    "prefer-const": "warn",
  },
  settings: {
    jsdoc: {
      tagNamePreference: {
        returns: "return",
      },
    },
  },
};

I had tried restarting VScode, clearing the cache, and all to no avail. I am guessing I need to change some of the paths but I am not very good at changing the config files so I don't want to accidentally break the entire project.

A: Another approach is if you happened to open the Workspace folder one level above the Project (as was in my case), just start a new Workspace with the ACTUAL project folder. That solved my Eslint error.

A: I suddenly started seeing this error using vscode. Restarting vscode has resolved my issue

A: I solved it by adding @typescript-eslint/parser to the extends:

A: Update your eslintrc.json file with the following line:
"project": "PROJECT_NAME/tsconfig.json"
with PROJECT_NAME being the name of your project (not a macro).

A: For those using Angular and eslintrc.json, add the 2 stars to the project node like this:
"overrides": [
    {
        "files": ["*.ts"],
        "parserOptions": {
            "project": ["**/tsconfig.json"],
        },

A: By default, the projects (in parserOptions) are resolved relative to the current working directory. If you run eslint in a different working directory to the folder containing tsconfig.json, @typescript-eslint/parser will not be able to locate the file.
To fix this, you can set tsconfigRootDir to __dirname, which would make the parser resolve the project configuration relative to .eslintrc.js:
module.exports = {
  // ...
  parserOptions: {
    project: "tsconfig.json",
    tsconfigRootDir: __dirname,
    sourceType: "module",
  },
  // ...
}

If you're having some trouble with
/path/to/.eslintrc.js
  0:0  error  Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser.
The file does not match your project config: .eslintrc.js.
The file must be included in at least one of the projects provided

see this question.

A: What fixed this for me is to simply navigate into the project directory containing my tsconfig.json, and that it was able to locate the file.
Otherwise, I liked @dheeraj9499's answer that you can modify your .eslintrc.json "project" array within "parserOptions" and locate where your tsconfig.json is located from within the current directory. So something like the following was able to find tsconfig.json in the correct directory:
"parserOptions": {
  "project": [
    "code/eMOS/Scripts/tsconfig.json",
    "code/eMOS/Scripts/tsconfig.spec.json"
  ],
 }

A: Parsing error: Cannot read file 'd:\test\testproject\tsconfig.app.eslint.json'.eslint
One of the major issues I faced here because of the way the project folder is opened in vs code.
assume the folder structure is
d:\test\testproject where 'testproject' is the angular project you are using.
if you are opening the test folder in vs code then navigating to testproject as below
D:\test>
D:\test>cd testproject
D:\test\testproject>

Doing this will create 2 settings.json files, one for the main opened folder and one for the child folder which in turn doesn't allow the settings to be applied properly.
So always opening the project folder directly in the vscode would help overcoming the issue, when all the dependencies are mentioned properly in eslintrc.json and tsconfig.json files would help in solving the issue.

A: A VSCode-specific approach, that worked for me was to create a .vscode folder in the root project directory and add the following property to the settings.json file inside it:
{
  "eslint.workingDirectories": [
    "src"
  ]
}

The "src" could be any directory, which should be in eslint's scope.

A: I got this error in Visual Studio Code when working on a typescript project via WSL 2 on Windows 10.
It was fixed by installing the Remote - WSL extension in VS Code.
The files were hosted in my \wsl$\Ubuntu\home<user>\ location. The error message specified the correct file location, and VS Code could open the file.
The above fixes using the root directory and parser options did not help.

A: It works for me
"parserOptions": {
  "project": ["<YourProjectName>/tsconfig.json"],
}

A: If you get the following error message in a multi-module project in IntelliJ (e.g. a folder containing several backend services as well as a frontend module), IntelliJ might not be able to tell what to do.
In my case I got the following error on top of a .ts-file:

To fix this, I have clicked on "ESLint settings..." and picked "Manual ESLint configuration"

Then I entered the path to the frontend module root folder in "Working directories:" and picked the correct path to eslint in "ESLint package" (which - in my case - was in <frontend-module-root>/node_modules/eslint).
This way I still get eslint to work and do not have to change any project-related configuration at all (it works from frontend module root folder in CLI already).


text:
Q: How to create a matrix for specific elements in R and keep on adding to it I am trying to create a matrix in R.
I have two files: one correspond to brain model and whole blood file.
They look like this:

I want to create one big matrix for individual genes like this:
gene1 rs1 rs2 rs3 ...
whole
brain
gene2 rs1 rs2 rs3
whole
brain
and so on ...
So first I find the union set of rsid between these two file and then find union number of genes.
sqlite <- dbDriver("SQLite")
dbname <- "en_Whole_Blood.db"
db = dbConnect(sqlite,dbname)
wholeblood_df <- dbGetQuery(db,"SELECT * FROM weights")
View(wholeblood_df)
dbname <- "en_Brain_Cortex.db"
db = dbConnect(sqlite,dbname)
braincortex_df <- dbGetQuery(db,"SELECT * FROM weights")
View(braincortex_df)
##union snp:
snp_between_whole_brain <- c(braincortex_df$rsid,wholeblood_df$rsid)
snp_union <- unique(snp_between_whole_brain)
cols_length <- length(snp_union)
x_rownames <- list.files("C:/Users/Downloads/data/models_file/test_Code")
models_df_between_whole_brain <- matrix(,nrow=length(x_rownames),ncol=cols_length)
colnames(models_df_between_whole_brain) <- snp_union
rownames(models_df_between_whole_brain) <- x_rownames
total_genes <- c(braincortex_df$gene,wholeblood_df$gene)
genes_union <- unique(total_genes)
models_df_between_whole_brain <- as.data.frame(models_df_between_whole_brain)

Once I have created a dataframe it look like this:

But I want to create a dataframe for each gene in one only:
like this

gene1 rs1 rs2 rs3
brain
blood
#gene2 rs1 rs2 rs3
brain
blood

#the number of rows will be same for all the gene.
#Then after creating the matrix i want to match the rsid. so if rsid1 is present in brain then its corresponding weight should be added instead of NA and if not then it gets 0 value. But I want to do this for all the genes.
I wrote this code:
for(i in 1:length(genes_union)){for(j in
    1:length(colnames(models_df_between_whole_brain))){x <-
    (braincortex_df %>% filter(braincortex_df$gene ==
    genes_union[i], braincortex_df$rsid
    %in% colnames(models_df_between_whole_brain)[j]) %>%
    select(weight)) if(is.na(x)=FALSE)
    {models_df_between_whole_brain[1, j]=weight} else
    {models_df_between_whole_brain[1,j]=0}}}

the above code is giving me error
Error: unexpected 'if' in "for(i in 1:length(genes_union)){for(j in 1:length(colnames(models_df_between_whole_brain))){x <- (braincortex_df %>% filter(braincortex_df$gene==genes_union[i],braincortex_df$rsid%in%colnames("

I am not able to understand how to create the entire matrix or dataframe for all the genes.
Can anyone give me some idea or advice on how to solve this.
I tried the above code that I mentioned. I am able to do it for 1st col 1st row but not able to fill it for all the rsid and for all the genes

I used the comment approach and got this:  enter image description
here

These are the inputs:
x <- str(wholeblood_df)
'data.frame':   206238 obs. of  7 variables:
 $ gene      : chr  "ENSG00000107937.18" "ENSG00000107937.18" "ENSG00000107937.18" "ENSG00000107937.18" ...
 $ rsid      : chr  "rs7475652" "rs7918643" "rs3125034" "rs3750730" ...
 $ varID     : chr  "chr10_295356_T_C_b38" "chr10_301812_C_T_b38" "chr10_302079_G_C_b38" "chr10_653149_A_G_b38" ...
 $ ref_allele: chr  "T" "C" "G" "A" ...
 $ eff_allele: chr  "C" "T" "C" "G" ...
 $ weight    : num  0.00454 -0.00735 0.00691 0.01152 0.01207 ...
 $ matrix    : chr  "wholeblood" "wholeblood" "wholeblood" "wholeblood" ...
> y <- str(braincortex_df)
'data.frame':   176364 obs. of  7 variables:
 $ gene      : chr  "ENSG00000185736.15" "ENSG00000185736.15" "ENSG00000185736.15" "ENSG00000185736.15" ...
 $ rsid      : chr  "rs2085346" "rs12765102" "rs11250286" "rs1876899" ...
 $ varID     : chr  "chr10_617697_G_A_b38" "chr10_1142141_G_T_b38" "chr10_1149946_C_T_b38" "chr10_1154505_A_C_b38" ...
 $ ref_allele: chr  "G" "G" "C" "A" ...
 $ eff_allele: chr  "A" "T" "T" "C" ...
 $ weight    : num  -0.05847 0.00128 0.00176 -0.00193 0.00182 ...
 $ matrix    : chr  "braincortex" "braincortex" "braincortex" "braincortex" ...

A: on approach:
create example data - you forgot to provide some other than a screenshot ;-)
wholeblood_df <- structure(list(gene = c("ENSG0000123456", "ENSG0000123987"),
    rsid = c("rs7470815", "rs3853288"), varID = c("foo", "baz"
    ), ref_allele = c("C", "T"), eff_allele = c("A", "G"), weight = c(0.001,
    0.001)), class = "data.frame", row.names = 1:2)
braincortex_df <- structure(list(gene = c("ENSG0000123456", "ENSG0000123987"),
    rsid = c("rs7470815", "rs3853288"), varID = c("ping", "pong"
    ), ref_allele = c("C", "T"), eff_allele = c("A", "G"), weight = c(NA,
    0.009)), class = "data.frame", row.names = 1:2)

merging and reshaping with {tidyr} and {dplyr}:
library(dplyr)
library(tidyr)

## add a column indicating the data provenance for later ...
wholeblood_df$matrix = 'wholeblood'
braincortex_df$matrix = 'braincortex'

bind_rows( ## rowbind the required portions (columns) of both datasets:
  braincortex_df |> select(matrix, gene, rsid, weight),
  wholeblood_df |> select(matrix, gene, rsid, weight)
) |>
pivot_wider( ## juxtapose 'weight' of blood and brain:
  names_from = matrix,
  values_from = weight
) |>
## coalesce weight values = keep first non-NA value in a row
## 'brain' comes first, so weight will be taken from this column unless NA
mutate(braincortex = coalesce(braincortex, wholeblood)) |>
## re-pivot to long format:
pivot_longer(cols = c(braincortex, wholeblood),
             names_to = 'matrix',
             values_to = 'weight'
) |>
select(matrix, gene, rsid, weight) |>
pivot_wider(names_from = rsid,
            values_from = weight
            ) |>
select(-matrix)

output:
# A tibble: 4 x 3
  gene           rs7470815 rs3853288
  <chr>              <dbl>     <dbl>
1 ENSG0000123456     0.001    NA
2 ENSG0000123456     0.001    NA
3 ENSG0000123987    NA         0.009
4 ENSG0000123987    NA         0.001


text:
Q: in Java how to get a server datetime from a client I want to get the server date time and set this to the client using Java Socket programing.example when I pass the Server IP address it will return the server's date and time and set this to the client.
thanks in advance for your help

A: *

*new ServerSocket / accept

*new Socket / connect / read

*Server get time / write

*client set local time

For each point you may find an answer in SO, and a tutorial at Oracle.


text:
Q: How to insert if not existing and update if existing (upsert)? I am currently having a confusion with:
var post = {ip: host, status: info};
var sql = con.query('INSERT OR IGNORE INTO ipaddress SET ?', post,
function(err, result){});

I have already set the IP address to primary key.

A: Sequelize
Since you're using node.js, how about using Sequelize?

Sequelize is a promise-based ORM for Node.js v4 and up. It supports the dialects PostgreSQL, MySQL, SQLite and MSSQL and features solid transaction support, relations, read replication and more.

It doesn't matter if you don't know SQL well because you can use its built-in functions. For example, if you want to perform an upsert:
ipaddress.upsert({
    ip: host,
    status: info,
});

Pure MySQL
If you still want to use MySQL, use ON DUPLICATE KEY UPDATE to perform an upsert.
var sql = `INSERT INTO post (ip, status) VALUES (${host}, ${info}) ON DUPLICATE KEY UPDATE ip=${host}, status=${info}`;

But you need to take care some potential issues like SQL injection.