text:
Q: Enlarge an image and increase its resolution An ongoing purely recreational project.  I got my introduction to image processing with this Rotating perspective... question and had a lot of fun with it.
Now I want to take it to the next step.
The great solutions to the earlier question led me to the following image as quite a small JPEG:

Now, I hope to create a poster of the image that I can have printed at say 4' horizontally.  To do this I need a JPEG which will have at least a 4' horizontal dimension with a resolution of at least 300 dpi.
The artist created the original collage from pieces of cut colored paper - each piece a completely saturated color. The entire collage only has 10 or 11 colors.  I can pretty easily identify RGB values for each.
Also, the shapes that look approximately rectangular should all show as actual rectangles.  The artist originally used full sheets of the colored paper.
If you copy the above image into Mathematica and zoom in on it even a little like this:

you'll see that it doesn't have crisp straight edges and many of the colors appear modulated rather than saturated.  This will only get worse the more one blows up the image.  To enlarge this up to 4' wide I need a way to address all of those issues.
Call the attached JPEG i = Import["http://i.stack.imgur.com/oPQMH.jpg"];
ImageResize[i, 5000]

gets me pretty close to the size I need.
ColorQuantize[i, 11]

begins to get me towards the saturation of color that I want.
But these approaches don't get me all the way.
Do I need to try point operations and/or transformations of some kind?
Do I need to breakout grey scales for each of the RGB values?
Would some kind of mask help?  Something so I break the problem down into smaller pieces.
Any guidance appreciated.

P.S., I have the original artist's full cooperation and permission in this little project.  If anyone wants to make a print of the final product and display it he'd love to see it out in the world and enjoyed.

A: The goal should not be getting a high-res JPEG! What you want is a vector graphic of your images which is arbitrarily scalable without losing quality. Converted to PDF, such a vector graphic can be printed by any printing service.
Let us try some basic image processing. We start with your original image from the post you referred to and apply the perspective transformation. Afterwards, crop the image a bit but leave enough white border around:
img = Import["http://i.stack.imgur.com/DOGOB.jpg"];
t = FindGeometricTransform[{{1924.19`, 880.846`}, {154.761`,
     1200.69`}, {190.872`, 189.582`}, {1893.24`,
     297.914`}}, {{1924.19`, 880.846`}, {175.395`,
     1283.22`}, {175.395`, 571.325`}, {1893.24`, 297.914`}},
   "Transformation" -> "Perspective"];
persp = ImageTake[
  ImagePerspectiveTransformation[img, t[[2]], 1000, DataRange -> Full,
    PlotRange -> All], {50, -250}, {100, -15}]

Fixing the lighting
The first thing I wondered while reading over the answers to your last question was why no one fixed the obvious thing in this image: the light. There is a global color gradient of lighting and a very bright spot in the upper left corner. Looking at a 3D plot of the brightness makes this more visible:
ListPlot3D[ImageData[
   GaussianFilter[Last[ColorSeparate@ColorConvert[persp, "HSB"]], 5],
   "Real", DataReversed -> False][[1 ;; -1 ;; 10, 1 ;; -1 ;; 10]]]

I don't want to take the bright spot into account which does not represent the global lighting very well, but with the other 3 corners, I have places in the image which should be of the same brightness.
What I do is, I take the upper right, lower left and lower right corner in the image and calculate the mean of the brightness in this area:
{ur, ll, lr} = Mean[Flatten@ImageData[ImageTake[Last[
 ColorSeparate[ColorConvert[persp, "HSB"]]], #1, #2], "Real"]] & @@@
 {{{1, 30}, {-1, -30}}, {{-1, -30}, {1, 30}}, {{-1, -30}, {-1, -30}}}
(* {0.647115, 0.442144, 0.415678} *)

With these 3 corners, we could calculate a plane in 3D space, representing the global behavior of the brightness:
{nx, ny} = ImageDimensions[persp];
sol = First@Block[{x0, x1, y0, y1},
   {x0, y0} = {1, 1};
   {x1, y1} = {nx, ny};
   Solve[Thread[{{x1, y0, 1}, {x0, y1, 1}, {x1, y1, 1}}.{a, b,
        c} == {ur, ll, lr}], {a, b, c}]
];
corrFunc = Compile[{{x, _Real, 0}, {y, _Real, 0}, {f, _Real, 0}}, f - #] &[
  (a x + b y) /. sol];

Note that corrFunc takes a pixel-value f and subtracts the plane height at this point. The plane itself pretty much models the behavior of the lighting:

Let's separate our persp image into the 3 channels (hue, saturation and brightness) of the HSB colorspace. We will apply the correction (of course) only on the brightness channel, since this is anyway the only thing that matters... if you don't believe me, take a look at the hChan. With the corrected brightness, we create a perspCorr image.
{hChan, sChan, bChan} = ColorSeparate[ColorConvert[persp, "HSB"]];
bChanCorr = Image[MapIndexed[corrFunc[#2[[2]], #2[[1]], #1] &,
  ImageData[bChan, "Real"], {2}]];
perspCorr =
 ColorConvert[ColorCombine[{hChan, sChan, bChanCorr}, "HSB"], "RGB"];

Extracting a mask
The next thing I thought of is whether is possible to kill the background completely. After various tests, it seems the blue channel of the corrected image works if you want to separate background from the colored parts. Finding a good threshold can be done in a Manipulate:
Manipulate[
 Binarize[GaussianFilter[Last[ColorSeparate[perspCorr]], 1], t], {t, 0, 1}]

where I found here that 0.534 is appropriate:
mask = ColorNegate[
 Binarize[GaussianFilter[Last[ColorSeparate[perspCorr]], 1], 0.534`]]

We will use this later.
Color smoothing
Color smoothing can be done in various ways. There are many non-linear filters which would do the job, and without giving reasons I (the post is long enough anyway) choose the MeanShiftFilter here:
mshift = MeanShiftFilter[perspCorr, 4, .03, MaxIterations -> 50];
ImageTake[mshift, {200, 300}, {300, 500}]

This does not help you with the pixelized edges, but it smooths the homogeneous surfaces.

Now, let's use the mask for removing the background completely:
preprocessed =
 ImageAdd[ImageMultiply[mask, mshift], ColorNegate[mask]]

Vectorization
With this image, I would leave Mathematica and take a good vectorizer. InkScape does a good job, and will convert this pixel graphic into a scalable vector graphic for you. Without manual adjustment, this will not solve your edge-problem completely.
But since we're already at Mathematica.SE we can surely try to use some functions from this thread as suggested by rm.
bdata = Flatten[
   MapIndexed[Flatten[{#2 + .9 RandomReal[{-1, 1}, 2], #1}] &,
    Transpose@ImageData[
      ImageAdd[ImageMultiply[mask, bChanCorr], ColorNegate[mask]],
      "Real", DataReversed -> True], {2}], 1];
ListDensityPlot[bdata[[1 ;; -1 ;; 10]], InterpolationOrder -> 0,
 ColorFunction -> "SouthwestColors", BoundaryStyle -> None,
 Frame -> False, PlotRangePadding -> 0, AspectRatio -> Automatic]

Note that although the image looks pixelated here, it's not! First, I took only every 10th pixel to speed things up. Second, when you export the graphics as a 5000 pixel image, you get an image which looks from very near like a nice mosaic:


text:
Q: Delete files on a Raspberry Pi with Python script - permission error I have a script on my RasPi that on startup is in charge of moving and erasing a bunch of old files.
The script, named "erasePi.py" is called from rc.local
I have had some issues in the past few days with this script, lacking required permissions to erase and copy files.
At the end, I've found I was calling erasePi.py from rc.local with the following line:
sudo python /home/.../erasePi.py
and I changed with:
python /home/.../erasePi.py
since all the scripts run from rc.local have root permissions.
Everything working now, but I would like to ask if this solution is a coincidence of various factors or simply, with that sudo I was triggering an abnormal behavior of Raspbian?

A: It seems to be that the sudo command was the issue.
As you mentioned in your comment, rc.local file has root permissions. So it is not necessary to include sudo command.
I hope this comment helps you
Kind regards

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fibonacci in Arithmetic Progression I was reading a book, where the author said, with no proof, that

No four distinct fibonacci numbers are in arithmetic progression.

I tried with no progress for about one hour.
Can anyone show me a proof, please?

A: Let's assume $F_h < F_i < F_j < F_k$ are in AP, so $F_i — F_h = F_k — F_j=d$, the common difference
Then $d = F_i-F_h < F_i$; on the other hand, $d = F_k-F_j \geq F_k-F_{k-1}=F_{k-2}\geq F_i$, which poses a contradiction.


text:
Q: Create a Cognito test user to simulate external auth providers We are running a lot of system tests that simulate user behavior on the backend.
Currently all tests are done by creating a temporary cognito user on our test environment.
Our userpool has been configured to use email as username UsernameAttributes: - email
Now we want to run our test suite with a temporary user that identifies using an external auth provider. So in this case we want the username to be of the format SignInWithApple_xxxxx.yyyyyyyyyyyyyyyyyyyyyyyyyyy.zzzz.
How can I create a user that has a "Sign in with Apple - id"?
I run into an InvalidParameterException:  "Username should be an email."
How can I work around this and create a test user that simulates users coming from an external auth provider?


text:
Q: How to use Vaadin SQLContainer when I already have a JDBC connection pool Vaadin 7 offers the SQLContainer implementation. The Book of Vaadin says to use either of its implementations of a JDBC connection pool. But I already am using the Tomcat JDBC Connection Pool implementation. Having one pool that draws from another pool seems like a bad thing.
To continue using the Tomcat pool, I implemented the com.vaadin.data.util.sqlcontainer.connection.JDBCConnectionPool interface. That interface requires three methods:

*

*reserveConnectionI return a connection drawn from the Tomcat pool.

*releaseConnectionI do nothing. I tried calling close on the connection, but that actually closed the connection rather than returning it to the Tomcat pool. Apparently the SQLContainer already called close once and my second call to close actually closes down the connection. I was getting runtime errors saying the connection was not open.

*destroyI do nothing. Supposedly this method is just some workaround for some issue with Postgres (which I'm using), but seems irrelevant given that I am actually using the Tomcat pool.

➜ Is implementing that interface the correct approach?
➜ If implementing that interface is the way to go, did I do so properly? Any other issues I should address?
My Tomcat pool is available via JNDI, so I'm not sure if I should be using the Vaadin class J2EEConnectionPool.

A: J2EEConnectionPool Is Not A Pool (a misnomer)
Having looked at the source code, it appears the J2EEConnectionPool class is misnamed. It is not an implementation of a pool. It merely draws on a javax.sql.DataSource object (obtained via JNDI if not provided to constructor) to get a java.sql.Connection object.
The "Pool" part of the name must come from an assumption that the DataSource is backed by a connection pool.
Yes, Use J2EEConnectionPool
So, if a real connection pool is in use such as the Tomcat JDBC Connection Pool available via DataSource or JNDI, pass that DataSource or JNDI info to an instance of J2EEConnectionPool for use with the Vaadin SQLContainer.
Forum Thread
See this discussion, "Any chance of bug fix for TableQuery+SQLContainer and Connection pools?", on the Vaadin Forums.
Bug Ticket
See Ticket # 12370, "SQLContainer does not work with tomcat/BoneCP connection pool", in the Vaadin issue tracker.

A: You should in fact be able to use J2EEConnectionPool, exactly as you described in your own answer above. I have used successfully used J2EEConnectionPool with FreeformQuery so I know this works. Unfortunately there is apparently a bug in Vaadin's TableQuery implementation which caused the "connection has been closed" error you saw. See: http://dev.vaadin.com/ticket/12370
The ticket proposes a code change, but in my case I simply replaced the offending TableQuery with a FreeformQuery.


text:
Q: Is webpack + typescript needed for a node.js server in order to implement Angular SSR I have an existing project, a Node API + Angular project :
https://framagit.org/mael-jarnole/talebear/tree/master
And I am trying to implement SSR, using the official guide:
https://angular.io/guide/universal
Here is my WiP:
https://framagit.org/mael-jarnole/talebear/tree/ssr-wip
The SSR bundle and regular Angular app seem to build fine, my problem is the express server implementation :
So far Webpack outputs tons of warning and errors that I do not understand (probably coming from my lack of knowledge of webpack), that seem to be coming from third party js imports (mongoose, helmet etc.)
My questions are:

*

*Is it necessary to use Webpack and typescript for the Node server ? Porting the code can be quite long, I did it in a very quick way, and it is not very Typescript-like so far. I'd love to stick to my Javascript implementation that works.

*Why are there errors when running npm run webpack:server on my SSR branch ?

*If the answer is yes to the first question, what should I modify in order to have a working server Webpack configuration ? Where should I look at ? The configuration from the official guide outputs a huge server.js file
Sorry if my question is too broad ! Thank you for your help.

A: I started over from another angular + node boilerplate: https://github.com/angular/universal-starter, and merged my project step by step, re installing every dependencies. and my server now works...
So problem solved but no clue why it did not work on my ssr-wip branch.


text:
Q: Revert to an older version of Ionic 2 CLI So I updated my ionic 2 cli and I hate it... There's soo many bugs. How do I revert back to an older version of Ionic 2? The one I want would be the one that includes Angular Rc 4.
The one I would like to revert back to is 2.0.0-beta.36

A: So, altough this could be a duplicate and I marked it as one, still want to help you out a bit.
npm install -g ionic@2.0.0-beta.36
or (not sure about the .)
npm install -g ionic@2.0.0-beta36


text:
Q: How to write a T-SQL Script for different Source DB/Table versions My main question:
How do I write an insert-SQL query that can handle if the source table doesn't include all the Fields it might have. (see the "a little background" section for reasons)
so my destination Table has a known set of fields, but my source table(s) might lack some of those. Like this:
Destination.TableA
----------
ID
Field 1
Field 2
Field 3

source1.TableA
-----
ID
Field 2

source2.TableA
-------------
ID
Field 1
Field 2

so what I basically need is an equivalent to "if field ... exists, then insert into...." (primary keys should not be affected)
I know how to test for the existence of a table or other SQL object, but I don't know how to do that in an insert-statement concerning the tables' fields. - Can you give me a hint?
A little background:
We have a lot of customers running different Versions of our Product. Over time, our database has been expanded, field by field. Some Customer DBs have been customized to the personal needs of those customers.
Right now, I'm in the concept stage on developing a tool/script to Upgrade all those old Versions into our current Database Version. As, due to refactoring of our latest version, there is a lot of patching/moving of data due for this upgrade, I'd like to build a script that is able to upgrade all the versions of source databases. - This is mostly to avoid redundant adjustments while developing the script.
As I already have tools in place to generate SQL-queries, the amount of generated query code for me is secondary to its functionality.
p.s. After this upgrade, we have already built-in upgrade mechanics in place to ease upgrading in the future. This script is meant to get all our pre2018 up to date to get them into our new product/upgrade cycle.
p.p.s. all Databases run on Microsoft SQL Servers

A: Okay, this is going to be quite a messy answer, as there's a lot of things going on here to get this to work in a reasonably sensible way.  I'm using MERGE with dynamic SQL to generate scripts then run them for each table.
First I need some test data, so I created a Temp database to play with:
USE Temp;
GO
CREATE SCHEMA destination;
GO
CREATE SCHEMA source1;
GO
CREATE SCHEMA source2
GO
CREATE TABLE destination.tableA (
    ID INT,
    Field1 VARCHAR(50),
    Field2 VARCHAR(50),
    Field3 VARCHAR(50));
GO
CREATE TABLE source1.tableA (
    ID INT,
    Field2 VARCHAR(50));
GO
CREATE TABLE source2.tableA (
    ID INT,
    Field1 VARCHAR(50),
    Field2 VARCHAR(50));
GO

Then I added some test data, making this repeatable:
DELETE FROM destination.tableA;
DELETE FROM source1.tableA;
DELETE FROM source2.tableA;
INSERT INTO source1.tableA SELECT 1, 'dog';
INSERT INTO source1.tableA SELECT 2, 'cat';
INSERT INTO source2.tableA SELECT 1, 'dog', 'harold';
INSERT INTO source2.tableA SELECT 3, 'mouse', 'midge';
GO

The plan is to start with a totally empty destination table, and to have some cases where all the data comes from one table, and other cases where there's a mixture, e.g. one table provides one piece of data, put there's another column for the same primary key in another table.  This makes things much more complex, as now we need to INSERT or UPDATE depending on the data.  This is where MERGE comes in.
I also use FOR XML PATH to get comma-separated lists.  Here's the "nasty" dynamic SQL:
IF OBJECT_ID('tempdb..#schemas') IS NOT NULL
    DROP TABLE #schemas;
GO
SELECT SCHEMA_NAME INTO #schemas FROM INFORMATION_SCHEMA.SCHEMATA WHERE CATALOG_NAME = 'Temp' AND SCHEMA_NAME LIKE 'source%';
WHILE EXISTS (SELECT * FROM #schemas)
BEGIN
    DECLARE @schema VARCHAR(50);
    SELECT TOP 1 @schema = SCHEMA_NAME FROM #schemas;
    SELECT @schema;
    DECLARE @sql NVARCHAR(4000);
    SELECT @sql = N'MERGE destination.tableA AS [target] USING (SELECT * FROM ' + QUOTENAME(@schema) + '.tableA)
        AS [source] ('
        + STUFF((SELECT ',' + COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_CATALOG = 'Temp' AND TABLE_SCHEMA = @schema AND TABLE_NAME = 'TableA' ORDER BY ORDINAL_POSITION FOR XML PATH('')), 1, 1, '')
        + N') ON [target].ID = [source].ID
        WHEN MATCHED THEN UPDATE SET '
        + STUFF((SELECT ',' + COLUMN_NAME + ' = [source].' + COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_CATALOG = 'Temp' AND TABLE_SCHEMA = @schema AND TABLE_NAME = 'TableA' AND COLUMN_NAME != 'ID' ORDER BY ORDINAL_POSITION FOR XML PATH('')), 1, 1, '')
        + N' WHEN NOT MATCHED THEN INSERT ('
        + STUFF((SELECT ',' + COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_CATALOG = 'Temp' AND TABLE_SCHEMA = @schema AND TABLE_NAME = 'TableA' ORDER BY ORDINAL_POSITION FOR XML PATH('')), 1, 1, '')
        + N')
        VALUES ('
        + STUFF((SELECT ', [source].' + COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_CATALOG = 'Temp' AND TABLE_SCHEMA = @schema AND TABLE_NAME = 'TableA' ORDER BY ORDINAL_POSITION FOR XML PATH('')), 1, 1, '')
        + ');';
        EXEC sp_executesql @sql;
        SELECT @sql;
        DELETE FROM #schemas WHERE SCHEMA_NAME = @schema;
END;
GO
SELECT * FROM [destination].tableA;

Here's an example of one of the dynamic SQL scripts that gets run:
MERGE destination.tableA AS [target] USING (SELECT * FROM [source1].tableA)
AS [source] (ID,Field2) ON [target].ID = [source].ID
WHEN MATCHED THEN UPDATE SET Field2 = [source].Field2 WHEN NOT MATCHED
THEN INSERT (ID,Field2)
VALUES ( [source].ID, [source].Field2);

The end result of this is:
ID  Field1  Field2  Field3
1   dog     harold  NULL
2   NULL    cat     NULL
3   mouse   midge   NULL

Which looks good to me?
However, I imagine you would need to make quite a few changes to get this to work with your environment.  I'm hoping this gives you a few ideas on how this could be done?


text:
Q: Android remove navigation bar Im facing a seriour problem.
Im developing an app for Android API 14 (>= Android 4.0). I test the app in some devices and work well but the devices that have a navigation bar inside the screen not work.
I saw some answers here and here but nothing work.
Here is an image of the navigation bar: Image Navigation Bar
I have two questions:
1) Is there a way to hide the navigation bar for ever? im developing a game, so i dont want to this bar appear. Which is the best solution? maybe not to hide and calc the size of the screen with navigation bar?
2) When im developing in the graphical layout i try to hide the navigation bar adding the Theme: Theme.Holo.NoActionBar.Fullscreen but the navigation stills there, so when i position some views, when i run the app in a device, the views are not in the correct position
Thanks

A: try this, call in in your activity's onCreate
public void makeFullScreen() {
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    if(Build.VERSION.SDK_INT < 19) { //View.SYSTEM_UI_FLAG_IMMERSIVE is only on API 19+
        this.getWindow().getDecorView()
                .setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
    } else {
        this.getWindow().getDecorView()
                .setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE);
    }
}


text:
Q: Parsley.js: Error Message Hierarchy I am new to Parsley, and want to provide a good UX for my end users. The example on the Parsley site is admittedly "not a perfect example of UX-awareness."  Which leaves me wishing that there was a good example of error message display hierarchy.
The user should never see multiple error messages for the same field; it should only ever be one at a time. So, how do I make that happen?
I would suggest structuring the hierarchy according to the order in which the constraints are applied to the field.
Any suggestions or solutions?

A: I had the same problem.

*

*Check out: parsleyjs.org/documentation.html#parsleyclasses
and use code from "Change error container" section.

*Add this to your CSS: .parsley-container{display:none} input:focus+.parsley-container{display:block}
I made something more for myself:
.parsley-container {
  display: none;
  position: absolute;
  margin: 10px 0 0 0;
  padding: 2px 5px;
  z-index: 2;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  -ms-border-radius: 3px;
  -o-border-radius: 3px;
  border-radius: 3px;
  background: #ffffff;
  border: 1px solid #888888;
}
.parsley-container:after, .parsley-container:before {
  bottom: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}
.parsley-container:after {
  border-color: rgba(255, 255, 255, 0);
  border-bottom-color: #ffffff;
  border-width: 10px;
  left: 50%;
  margin-left: -10px;
}
.parsley-container:before {
  border-color: rgba(136, 136, 136, 0);
  border-bottom-color: #888888;
  border-width: 11px;
  left: 50%;
  margin-left: -11px;
}
input:focus + .parsley-container,
input:active + .parsley-container {
  display: block;
}

Pretty much like Chrome HTML5 validation.

A: The addValidator() function accepts a priority value as the third parameter.  The default for built-in validators is 30 for most of them, except "notblank" is 2, "regexp" is 64, "type-xxx" is 256 and "required" is 512. Parsley stops validating on the highest priority failing test(s).  This is configurable with the priorityEnabled setting.  In order to get just one at a time you can create custom validators each with a different priority:
window.Parsley.addValidator('check3', function(val, req) {
    return (val == whatever3(val, req));
// +--- Higher than check2
// v
}, 103).addMessage('en', 'check3', 'Failed check 3');

window.Parsley.addValidator('check2', function(val, req) {
    return (val == whatever2(val, req));
// +--- Higher than check1
// v
}, 102).addMessage('en', 'check2', 'Failed check 2');

window.Parsley.addValidator('check1', function(val, req) {
    return (val == whatever1(val, req));
// +--- Higher than many, lower than "required (512)" and "type-xxx (256)"
// v
}, 101).addMessage('en', 'check1', 'Failed check 1');


text:
Q: Gitlab Shell Script Permission Denied I am running a simple shell script with Gitlab CICD and I am getting Permission denied. Kindly suggest
When I do chmod +x test.sh it says operation not permitted.
stages:
  - build

build:
  stage: build
  script:
    - ls
    - ./test.sh

Shell test.sh
echo Hi

Error:

A: Instead of simply running chmod on your local system, it's better to run git update-index --chmod=+x path/to/file. This adds an executable flag to a file in Git and should ensure that a script can be executed inside a GitLab pipeline.
See also this question.

A: bash /the-script.sh is the best solution afaik
https://gitlab.com/gitlab-org/gitlab-runner/-/issues/2672

A: You have to either:
1- Run bash ./test.sh
OR
2- Add the line #!/bin/bash to the top of test.sh so that it knows to run it within bash

A: The line 23 tells that it is trying to execute the script with /bin/bash, but it doesn't have the permissions.
Try to give execution permision to the file by running this command:
sudo chmod 755 test.sh


text:
Q: How to specialize a class-member for multiple template values (constants)? I'd like to specialize a member-method of a template-class. This template-class has a constant template-parameter of type int and depending on the value different global variables have to be selected:
template <int INSTANCE>
class mailbox
{
public:
    void write(uint32_t v);
}

// global accessors of different instances
extern mailbox<0> mailbox0;
extern mailbox<1> mailbox1;

and later in a .cpp-file
template<>
void mailbox<0>::write(uint32_t v)
{
    access(reg_0, v);
}

template<>
void mailbox<1>::write(uint32_t v)
{
    access(reg_1, v);
}

mailbox<0> mailbox0;
mailbox<1> mailbox1;

This allows me to use the mailbox as follows:
mailbox0.write(0xdeadcafe);

This compiles and links. I'd like to simplify the method by using the constant INSTANCE:
template<int INSTANCE>
void mailbox<INSTANCE>::write(uint32_t v)
{
    if (INSTANCE == 0)
        access(reg_0, v);
    else
        access(reg_1, v);
}

But I'm unable to figure the right syntax to make it work. Is this at all possible while keeping my user-code as is? What are the right words and terms for what I want to do in C++-slang?

A: Isn't the problem just that you are trying to separate a template into .h and .cpp (which, in reality, is rarely feasible in the current standard)?
template <int INSTANCE>
class mailbox
{
public:
    void write(uint32_t v){
        if (INSTANCE == 0)
            access(reg_0, v);
        else
            access(reg_1, v);
    }
}

should work

A: Maybe you could go other way around - let global variable be a static member of a class parametrized by the same int mailbox is parametrized by. e.g.:
template <int INSTANCE>
struct reg {
    static RegType value;
};

template <int INSTANCE>
RegType reg<INSTANCE>::value;

then access to the reg value would be transparent without any specialization:
template<int INSTANCE>
void mailbox<INSTANCE>::write(uint32_t v) {
    access(reg<INSTANCE>::value, v);
}

If c++17 is in a game you can make a reg template global variable and let the code be even simpler:
template <int INSTANCE>
RegType reg;

template<int INSTANCE>
void mailbox<INSTANCE>::write(uint32_t v) {
    access(reg<INSTANCE>, v);
}

Edit:
If you can't modify the access pattern you could create array of reference wrappers (c++11):
#include <functional>

std::reference_wrapper<RegType> regs[2] {reg_0, reg_1};

template<int INSTANCE>
void mailbox<INSTANCE>::write(uint32_t v) {
    access(regs[INSTANCE].get(), v);
}


text:
Q: How is an element with xmlns different from one created with createElementNS with the same namespaceURI? Assume we have the following XML:
<ns:xml xmlns:ns="AAA">
  <predefined xmlns="AAA"/>
</ns:xml>

When running the following code in the browser:
const doc = new DOMParser().parseFromString(XML, 'text/xml');

const added = doc.createElementNS('AAA', 'added');
doc.documentElement.appendChild(added);

just serializing added returns <added xmlns="AAA"/>
but when serializing doc the result is
<ns:xml xmlns:ns="AAA">
  <predefined xmlns="AAA"/>
  <a:added />
</ns:xml>

Why are predefined and added behaving differently?
or asked the other way around:
How would I be able to create an element like predefined using createElementNS (and other DOM APIs)?

A: To make added behave like predefined  you need to explicitly set the xmlns attribute to the same namespace as the namespaceURI argument:
const added = doc.createElementNS('AAA', 'added');
added.setAttribute('xmlns', 'AAA');
doc.documentElement.appendChild(added);

Also be aware that parsing it with the mime type text/html changes the behavior of (parsing and) serialization to result in the following:
<ns:xml xmlns:ns="AAA">
  <predefined xmlns="AAA"></predefined>
  <added xmlns="AAA"></added>
</ns:xml>


text:
Q: Writing json rdd into AWS S3 without creating _temporary folder I am trying to write large json rdd files into AWS S3 with scala and spark on Zeppelin. When I try to write it with saveAsTextFile() method it creates _temporary/0/.. folders and writes each rdd parts into this folders. This process is quite fast but after this, I think it copies each parts into the target folder and this copying process is very slow;
rdd.saveAsTextFile(outputPath + filename)

I've tried to convert rdd to spark dataframe and write it with the following code and it was still the same;
sc.hadoopConfiguration.set("spark.hadoop.mapred.output.committer.class", "com.appsflyer.spark.DirectOutputCommitter")
val DF = rdd.toDF()
DF.repartition(50).write.json(outputPath + filename)

I found a way to write it as parquet file;
sc.hadoopConfiguration.set("spark.sql.parquet.output.committer.class", "org.apache.spark.sql.parquet.DirectParquetOutputCommitter")
val dataDF = rdd.toDF()
dataDF.repartition(10).write.parquet(outputPath+filename)

It works. It is fast because it doesn't create temporary folder. It writes it directly to the target. But I need to write this rdd as json txt file.
Is there any way to write json files without creating temporary folder on AWS S3? Or any committer for json files like "org.apache.spark.sql.parquet.DirectParquetOutputCommitter"?


text:
Q: Gate types of the WirelessHost As we know, AdhocHost is extended from WirelessHost, WirelessHost has three gate types:
Name            | Direction     | Size
--------------------------------------------------------
radioIn [ ]     | input         | numWlanInterfaces
pppg [ ]        | inout         | numPppInterfaces
ethg [ ]        | inout         | numEthInterfaces

What seems strange is that the direction of the RadioIn gate is the type of input, not inout, or the Inet developers should have a RadioOut gate for sending radio signal.
When a node wants to send data, then how does that node send through a radio interface?
What is the process of passing data packets through the WirelessHost components when sending data?
Also, what is the process of passing data packets through the WirelessHost components when receiving data?
Thanks in advance

A: *

*Radio communication in OMNeT++ is usually modeling using sendDirect(). That method does not require neither an output gate nor channel between sender and receiver. Receiver must have an input gate only.

Reference:
OMNeT++ Simulation Manual - Direct Message Sending

*In short: when an application in WirelessHost wants to send some data to other host it creates a packet, sends it to transport layer (TCP or UDP), thet the packet is sent to network layer (where a route may be chosen), then packet is send to radio interface. Radio interface calculates propagation conditions and sends the packet to all or selected receivers (depending of assumed model of propagation).


text:
Q: How do I remove auto-resizing in the select element I want to do the opposite the what OP wants in this post
My selects are auto resizing for some reason (probably by using bootstrap, which I have to use). I just want to have a default resizing.
I have two inline select elements and they keep resizing according to the length of the selected option. I want to change their behavior to the default like in this fiddle. It takes the longest string "United States of America" and sets the elements width according to it.
HTML

  Doc Type
  <v-select v-model="docTypeSelect.value"
    class="dropdown-default"
    :options="docTypeSelect.options"
    options-value="val"
    placeholder="Please Select"
    search justified required
    close-on-select
  ></v-select>

  Major/Minor
  <v-select v-model="majorMinorSelect.value"
    class="dropdown-default"
    :options="majorMinorSelect.options"
    options-value="val"
    placeholder="Please Select"
    search justified required
    close-on-select
  ></v-select>

I am using VueStrap here to use bootstrap with vue.js
CSS:
 .flex-top-down {
    display: flex;
    flex-direction: column;
  }

  .input-header {
    font-weight: bold;
    margin-left: 10px;
  }

  .dropdown-default {
    margin-top: 6px;
  }

A: if you would like to use bootstrap selectpicker then it can be really easy.
here is example.
https://silviomoreto.github.io/bootstrap-select/examples/#width


text:
Q: Access and change characteristics of a single line within pandas plot Using the built-in functionality of pandas dataframes to plot, e.g. an unstacked area graph as follows:
df = pd.DataFrame(np.random.randn(11, 3)+3, columns=['r', 'g', 'b'])
df.plot(kind='area', stacked=False, alpha=0.75)

Yielding something like this:

How does one ex-post change the style of only one individual line, changing e.g. its color, linewidth and opacity level etc.?

A: As noted by @StefanJansen, you can edit a lines' color by accessing the lines from the given Axes.
You can also modify other attributes like so:
ax.lines[0].set_linewidth(2)         # set linewidth to 2
ax.lines[0].set_linestyle('dashed')  # other options: 'solid', 'dashdot` or `dotted`
ax.lines[0].set_alpha(0.5)           # Change the transparency
ax.lines[0].set_marker('o')          # Add a circle marker at each data point
ax.lines[0].set_markersize(2)        # change the marker size. an alias is set_ms()
ax.lines[0].set_markerfacecolor      # or set_mfc()
ax.lines[0].set_markeredgecolor      # or set_mec()

To change the area under the curve, you want to access the collections stored in the Axes. Useful attributes here are color and alpha:
ax.collections[0].set_color('yellow')
ax.collections[0].set_alpha(0.3)

Obviously, you can change the index 0 in these examples to modify the other lines/collections.

A: If you capture the axes returned by pandas.plot() like so:
ax = df.plot(kind='area', stacked=False, alpha=0.75)

Then you can access attributes like lines and set parameters like colors (matplotlib docs on axis API for detail on available parameters):
ax.lines[0].set_color('red')

For your expanded question, the area can be modified through the collections API like so:
ax.collections[0].set_color('color_name')

Changing the index for lines and collections allows for updating specific items. As these are iterables, you can also iterate over lines or collections and do several things:
for line in ax.lines:
    line.set_kwarg(foo)


text:
Q: Keytool Private Key Missing Password An Android app I am managing was published on Android in 2012 signed with a private key that has no password. Now I am trying to publish an updated version, but I am not able to use the same release keystore to sign via Eclipse, which insists a password is required.
I've tried exporting and reimporting into a new keystore, but the process failed halfway as it insists on entering an existing password for the key, which is non-existent.
I've also tried exporting the certificates out and reimporting into a new keystore, which works, but the private key cannot be successfully transferred.
I am stuck now on how to sign the updated app with the existing key which has no password. I've tried all sorts of keytool commands to change passwords but it did not work.


text:
Q: converge absolutely of $\sum _{n=1}^{\infty }\:\frac{(-1)^n}{x^2+n}$
I need to find  $x$ so that $\sum _{n=1}^{\infty }\frac{(-1)^n}{x^2+n}$ is absolute convergence

$\sum _{n=1}^{\infty }\frac{(-1)^n}{x^2+n}$ is converge absolutely if :
$$\sum _{n=1}^{\infty }|\frac{(-1)^n}{x^2+n}|$$ is convergence
so  $$\sum _{n=1}^{\infty }|\frac{(-1)^n}{x^2+n}|=\sum _{n=1}^{\infty }\frac{1}{x^2+n}$$
I can see that if $x>|n|$,  $\sum _{n=1}^{\infty }|\frac{(-1)^n}{x^2+n}|$ is convergence
but how can I prove that ?
thanks

A: No it is wrong, your number $x$ is fixed when you study its dependence on $n$.
If $x>n$ ? What is the value of $n$ ? It will takes all values of $n \in \mathbb{N}^{*}$ !
In fact your series have positives terms and
$$
\frac{1}{x^2+n}\underset{(+\infty)}{\sim}\frac{1}{n}
$$
Hence your series never converges absolutely as $\displaystyle \sum_{ n \geq 1}^{ }\frac{1}{n}$ diverges.

A: To solve your question formally (without hand-waving), we might approach it this way:
We look at the behaviour of the sequence of terms like $a_n$ and note than in the limit of $n \rightarrow \infty$, it approaches a sequence which we know to diverge $(1/n)$. We then try to reexpress the sequence $a_n$:
$$a_n = A_n + \frac 1 n$$
because if we have a series of two terms
$$\sum_n a_n + b_n.$$
and we show that $\sum_n b_n$ converges, then the full series converges if and only if $\sum_n a_n$ converges.

It turns out that your sequence can be reexpressed as follows (I obtained this from taylor expansion about $x=0$ and summing all but the first term as a geometric series):
$$\frac 1 {x^2 + n} = \frac 1 n - \frac {x^2}{n(n+x^2)}$$
We know that $\left| \frac {x^2}{n(n+x^2)}\right| \leq x^2 \left| \frac {1}{n^2}\right|$ and so this portion of the sequence converges. It follows that your series converges iff $\sum_n 1/n$ converges. Which, of course, it does not.


text:
Q: Change the Tint Color of UITableView Multiple Selection Check Circles When you enable allowsMultipleSelectionDuringEditing on a UITableView and then enter edit mode on it, each row will display a light grey circle on the left hand side. Upon tapping a row, the circle will be replaced with a tick icon, of the tint colour currently set to the table view.

I'm wondering, is there any way to override the tint colours of both of these icons and control them manually? I've discovered if you set cell.tintColor, you can override the tint colour of the icon when it's checked (But not the hollow circle graphic), but I'd rather be able to change the tint colour of just this icon.
I'm getting the sinking feeling the only way to do this is to manually hack the internal subviews, but I'm hoping someone may have found a way I've missed.

A: Setting the tintColor property of the cell should be enough.
e.g.
cell.tintColor = .green


text:
Q: Why do I need an InheritedWidget in Flutter I've started to learning about Flutter's inherited widgets and i have a question.
Why do we need an InheritedWidget if we can get data from context.findAncestorOfExactType?
And that updateShouldNotify... Like, it notifies child widgets when some condition is true, and they are anyway running their build methods after InheritedWidget changed, because it's immutable and we can only chage it in some rebuild...

A: InheritedWidget is more useful for build method cases. When you want to get data from an ancestor inside your build method.
From the Flutter API: https://api.flutter.dev/flutter/widgets/BuildContext/findAncestorStateOfType.html

This should not be used from build methods, because the build context
will not be rebuilt if the value that would be returned by this method
changes. In general, dependOnInheritedWidgetOfExactType is more
appropriate for such cases. This method is useful for changing the
state of an ancestor widget in a one-off manner, for example, to cause
an ancestor scrolling list to scroll this build context's widget into
view, or to move the focus in response to user interaction.

Also by doing what you mention, you are coupling Widgets together which is not a good practice at all. Widgets are known to be able to moved from place to place without much modification.
There are many useful things that come from the Inherited Widget. Some of these things are very useful packages, I recommend that you take a look at them.

*

*Provider package

*InheritedWidget & InheritedModel

*Redux

*BLoC / Rx

*GetIt
You can also take a look at the InheritedWidget documentation


text:
Q: ASP MVC4 how to send header in action method of controller to force pdf file download? I have a controller on server side, and the method
        public ActionResult GetBulletin()
    {

       return File(@"E:\Fileserver\022015.pdf", "application/pdf");
    }

this is triggered when a user clicks on a link on the webpage, the document then is opened in a browser window.
the link is
Download

What i want to do is force the download, I read that we shall use the content disposition header, my question is how to have the server send this header?
        Response.AppendHeader("Content-Disposition", @"attachment; filename=E:\Fileserver\022015.pdf");
        return View() ;

doesn't work of course.thanks.

A: You should set only file name in your Response.AppendHeader("Content-Disposition", @"attachment; filename=E:\Fileserver\022015.pdf"); statement so it becomes:
Response.AppendHeader("Content-Disposition", @"attachment; filename=022015.pdf");.
Then you can use the File(<file-bytes>, <content-type>) to send the file to the client. In your case this could be done like this:
return File(System.IO.File.ReadAllBytes(@"E:\Fileserver\022015.pdf"), "application/pdf")


text:
Q: How can I easily detect the trigger depth in sqlite3? I have two SQLite3 tables, A and B. When column A.X is updated, I want to modify B.Y, and when B.Y is updated, I want to modify A.X.
I can use two triggers:
CREATE TRIGGER AtoB AFTER UPDATE OF X ON A BEGIN UPDATE B SET Y = ...

and
CREATE TRIGGER BtoA AFTER UPDATE OF Y ON B BEGIN UPDATE A SET X = ...

but it seems that both triggers are called once, no matter which table I modify, i.e. one always invokes the other.
I only want one of them to execute, since the updates are lossy in the direction of A to B. I don't want the loss in the reverse direction B to A, but if both triggers fire, then it makes it lossy in both directions.
A simple solution would be to implement three UDFs "increment_trigger_depth", "decrement_trigger_depth", and "get_trigger_depth", and then use "WHEN trigger_depth == 1" in the update statements. But, is there an easier way to determine trigger depth in SQLite3?

A: Use a new table to hold the trigger depth.
CREATE TABLE trigger_depth (depth);
INSERT INTO trigger_depth VALUES (0);

Then for increment_trigger_depth use
UPDATE trigger_depth SET depth = depth + 1;

etc.
Use
... WHEN (SELECT depth FROM trigger_depth) <= 0 BEGIN ...

to guard your trigger actions


text:
Q: Why inputStr === "" is always false? I have this JavaScript code in my application:
var boo = function(inputStr) {
    if (!inputStr || inputStr === "") {
        throw new Error("Input is null or empty.");
    }
    return new Aftamat(inputStr);
};

And Resharper says that inputStr === "" is always false. Why? Is this the Resharper bug?

A: if string is empty, it's kind of a false... so !inputStr will return true and actually your inputStr === "" will be never checked if your string is empty

A: Probably because if inputStr === "" was true, then !inputStr would also be true, but if !inputStr was true, then inputStr === "" would never have been checked.
Ie, that code will only be reached in a situation where the test must be true.


text:
Q: Deriving an array of indexes This is a continuation of exploration traversing data structures in JavaScript.
See here and here.
Given this Javascript object:
var parsed =       {
  "terms": [
    {
      "span": [
        12,
        13
      ],
      "value": "2",
      "label": "number"
    },
    {
      "span": [
        13,
        14
      ],
      "value": "x",
      "label": "multiply"
    },
    {
      "span": [
        14,
        16
      ],
      "value": "14",
      "label": "number"
    },
  ],
  "span": [
    12,
    21
  ],
  "weight": 0.85,
  "value": "2x14 test"
};

How would I derive an array of the indexes of the terms where the label: number?
In a previous question, noted above, I was able to solve the notion of deriving the index for a certain label, when it was known that there was only one instance of such.
parsed.terms.map(function(d){ return d['label']; }).indexOf('number');

Now I am faced with the notion of multiple instances, as in the object above. The above code snip will only derive the index of the first.
I could build an array by looping through the terms and see if each has a number label, however the ideal solution would perhaps expand or modify the code snip above and perhaps not use a loop.

A: When you need to map and filter simultaneously use reduce:
var indexes = parsed.terms.reduce(function(indexCollection, item, index) {
    if(item.label === 'number') {
        indexCollection.push(index);
    }

    return indexCollection;
}, []);


text:
Q: undefined method `/' for nil:NilClass I have a pretty common helper method in my application helper:
module ApplicationHelper
    def quid(num)
        number_to_currency (num / 100.0), unit: "£"
    end
end

But my applications keeps throwing an 'undefined method `/' for nil:NilClass' error.
If I print number_to_currency (num) it doesn't have an issue, it's only when I try to put an operator like / * - + that it gives this error.
This was working fine until today, and it's only in the product index view that I get the error.
I'm not sure what's wrong, can anyone help explain?  I'm stumped!
UPDATE:
Here's the product index view code:
    <% @products.each do |product| %>

<%= product.title %>

<%= link_to "See more", product %>

        <%= image_tag(product.avatar.url(:medium)) %>

        <%= product.description %>

        <%= quid product.price_in_pence %>

    <% end %>

price_in_pence is an integer, but turning 100.00 into 100 doesn't help, so I don't think that's the issue, I think it is because num is returning nil for some reason.

A: The error comes, because the num variable is nil in some cases. number_to_currency(nil) works, because the helper is implemented like this:
def number_to_currency(number, options = {})
  return unless number
  ...
end

source: http://apidock.com/rails/ActionView/Helpers/NumberHelper/number_to_currency
You see, a nil doesn't hurt here, because it will instantly return.
Your function, however, tries to execute nil / 100.0 first. As the error states, the / method is not defined on nil.
You probably need some special nil treatment, or hunt the cases when nil is given to your helper.


text:
Q: Add i++ for each new row that will created by the button I try to make some repeatable fields with PHP and Javascript. This works fine, but after saving the post (creating an plugin for WordPress) the cloned row will override the latest one. This is because I don't use unique id's for each row.
I want to add an 'id' attribute with javascript and I want for each row that is created with the id 1 increase. I had already done something similar with PHP, but found out that this is not what I wanted and I am better out with javascript, I think, because when I clone the field with the "add new" button the amount doesn't increase with +1;
Here is the php code that I had used:
$count = 2;
for ($i = 0; $i < $count; $i++) {

    // Begin a table row
    echo '
';
    echo '' . '['.$i.']' . '	';

            // Do cool stuff inside the row

    echo '-	';
    echo '
'; // End .row

} // End for loop

Add new row

JS code for the repeatable fields:
// Add repeatable row
jQuery('.repeatable-add').click(function() {
    // Clone row
    var row = jQuery(this).closest('.ui-sortable').find('tbody tr.row:last-child');
    var clone = row.clone();

    clone.find('input[type=text], text, textarea, select, input.upload_image').val(''); // Reset the values
    clone.find('.preview_image').attr('src', ''); // Reset the values

    row.after(clone);

    //
    return false;
});

I think I have to do something like this snippet of line:
clone.find('tr.row').attr('id', 'repeatable-' + addInteger);

But how do I increase with +1 inside Jquery/Javascript, like my example in PHP?

A: What you want to do is look at the ID of the row you're cloning and use that ID to give the new row its proper index value.  I added two lines of code to your example, one defining a new variable called clonedIdIndex and one using the value in that variable to define a new ID for the cloned row.
jQuery('.repeatable-add').click(function() {
    // Clone row
    var row = jQuery(this).closest('.ui-sortable').find('tbody tr.row:last-child'),
        clone = row.clone(),
        clonedIdIndex = parseInt( clone.find('tr.row').attr('id').split('-')[1], 10 );

    clone.find('input[type=text], text, textarea, select, input.upload_image').val('');
    clone.find('.preview_image').attr('src', ''); // Reset the values

    // Assign new ID
    clone.find('tr.row').attr('id', 'repeatable-' + (++clonedIdIndex));

    row.after(clone);

    //
    return false;
});


text:
Q: Login into Asp.net Web application with Finerprint using asp.net C# Javascript I want to login to my asp.net web application using fingerprint. That means I don't want to use any login id and password. I just want to login with my fingerprint. I have got a 3m cogent device and the device works fine but I don't know how to integrate the device with my software. I am using ActiveX.
My Javascript code is:
 <script type="text/javascript">

    $(document).ready(function () {
        $('#scan').click(function () {
            $('#dicscan').addClass('scanning');
            setTimeout(function () {
                $('#dicscan').removeClass('scanning');
            }, 20 * 1000);
        });
    });
</script>
<script type="text/javascript">
    function OpenActiveX() {
        var port = document.getElementById("Comport");
        port.Conopen = 1;
        if (port.error > 0) //Display errors if found
            alert(port.ErrorDescription);
    }

    function Matching() {
        var retval = 0;
        var port = document.getElementById("Comport");
        port.Ksserialnumber = 1;
        port.KsCapture = 1;
        port.KsAuthenticationMatch = 1;
        retval = port.KsMatchretvalue;
        if (retval > 0) {
            alert("Two fingers are Matched...");
            window.open('ResultPage.html', '_self');
        }
        else {
            alert("Finger Not Matched...");
        }
        if (port.error > 0) //Display errors if found
            alert(port.ErrorDescription);
     }
</script>

I am getting undefined in port.KsMatchretvalue.

A: I am using 3M Cogent CSD 200 model Finger Print reader device
Hope you have SDK already
Below is a little code for this device to capture and match details to allow log in .
Two function here
1.] Capture - to save fingerprint
2.] Match - to match fingetprint at the time of log in
Note : its a code block from my application , you have to made adjustment according to your application
byte[] bTemplateDataOne;
        byte[] bTemplateDataTwo;
        byte[] isoTemplateBytes;
        bool ErroFlag = false;
        int nTempltSizeOne;
        int nTempltSizeTwo;
        MMMCogentCSD200APIs csd200Obj = null;
        CSD200Wrapper wr = null;
private void btnCapture_Click(object sender, EventArgs e)
    {
        try
        {
            int nRc = -1;
            byte[] fpRawBytes = null;
            int m_Width = 0, m_Height = 0;
            isoTemplateBytes = null;
            int nfiq = 0;

            pictCaptureImg.Image = null;
            pictCaptureImg.Refresh();
            if (true == chkbCaptureOnly.Checked)
            {
                pbClaimed.Image = null;

                pbClaimed.Refresh();

                bTemplateDataOne = null;
                nTempltSizeOne = -1;
                bTemplateDataTwo = null;
                nTempltSizeTwo = -1;
                rbClaimed.Checked = true;

                nRc = csd200Obj.captureFP(30000, ref fpRawBytes, ref m_Width, ref m_Height);
                if (nRc == CSD200APICodes.SUCCESS && fpRawBytes != null)
                {
                    bmp = CreateGreyscaleBitmap(fpRawBytes, m_Width, m_Height);
                    pictCaptureImg.Image = bmp;
                    MessageBox.Show("Fingerprint Capture Successful.");
                }
                else if (nRc == CSD200APICodes.ERROR_TIMEOUT)
                {
                    MessageBox.Show("Fingerprint Capture Timeout");
                }
                else
                {
                    MessageBox.Show("Fingerprint Capture Failed. ErrorCode: " + nRc);
                }
            }
            else
            {
                nRc = csd200Obj.captureFP(30000, ref fpRawBytes, ref m_Width, ref m_Height, ref nfiq, ref isoTemplateBytes);

                if (nRc == CSD200APICodes.SUCCESS && fpRawBytes != null)
                {
                    bmp = CreateGreyscaleBitmap(fpRawBytes, m_Width, m_Height);

                    pictCaptureImg.Image = bmp;

                    if (rbClaimed.Checked == true)
                    {
                        pbClaimed.Image = bmp;
                        if (isoTemplateBytes != null)
                        {
                            bTemplateDataOne = isoTemplateBytes;
                            nTempltSizeOne = isoTemplateBytes.Length;
                        }
                    }
                    else
                    {
                        MessageBox.Show("Try Again , Some error occured");
                    }
                    MessageBox.Show("Fingerprint Capture Successful.\n NFIQ: " + nfiq);
                }
                else if (nRc == CSD200APICodes.ERROR_TIMEOUT)
                {
                    MessageBox.Show("Fingerprint Capture Timeout");
                }
                else
                {
                    MessageBox.Show("Fingerprint Capture Failed. ErrorCode: " + nRc);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
private void btnMatch_Click(object sender, EventArgs e)
    {

        if (bTemplateDataOne != null )
        {
            //DataTable dt = new DataTable();
            //dt.Columns.Add("value");
            //for (int i = 0; i < bTemplateDataOne.Length; i++)
            //{
            //    DataRow dr = dt.NewRow();
            //    dr["value"] = bTemplateDataOne[i];
            //    dt.Rows.Add(dr);
            //}
            bool isMatch = false;
            int matched = 0;
            int index = 0; ;
            string strAppPath = Path.GetDirectoryName(Application.ExecutablePath);
            try
            {
                string result1 = Convert.ToBase64String(bTemplateDataOne, 0, bTemplateDataOne.Length);

                string connectionstring = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString.ToString();
                SqlConnection con = new SqlConnection(connectionstring);
                con.Open();
                SqlCommand cmd = new SqlCommand("select Biometric,Name,id from Details ", con);
                DataSet ds = new DataSet();
                SqlDataAdapter ad = new SqlDataAdapter(cmd);
                ad.Fill(ds);
                con.Close();

                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        bTemplateDataTwo = null;
                        bTemplateDataTwo = Convert.FromBase64String(ds.Tables[0].Rows[i][0].ToString());
                        nTempltSizeTwo = bTemplateDataTwo.Length;

                        //DataTable dt1 = new DataTable();
                        //dt1.Columns.Add("value");
                        //for (int ii = 0; ii < bTemplateDataTwo.Length; ii++)
                        //{
                        //    DataRow dr = dt1.NewRow();
                        //    dr["value"] = bTemplateDataTwo[ii];
                        //    dt1.Rows.Add(dr);
                        //}

                        isMatch = csd200Obj.matchTemplates(bTemplateDataOne, bTemplateDataTwo);
                        if (isMatch == true)
                        {
                            index = i;
                            matched++;
                        }

                    }

                    if (matched > 0)
                    {
                        string msg = "Fingers are Matched." + Environment.NewLine;
                        msg += "Welcome: " + ds.Tables[0].Rows[index]["Name"];
                        msg +="( id : " + ds.Tables[0].Rows[index]["id"] + ")" + Environment.NewLine + "matched value : " + matched;
                        MessageBox.Show(msg);
                        WriteFMRFile(nTempltSizeOne, bTemplateDataOne, strAppPath + "\\One.fmr");
                        WriteFMRFile(nTempltSizeTwo, bTemplateDataTwo, strAppPath + "\\Two.fmr");
                    }
                    else
                    {
                        MessageBox.Show("Not Matched." + Environment.NewLine + "matched value : " + matched);
                    }
                }
                else
                {
                    MessageBox.Show("There is no fingerprint saved in the system"+Environment.NewLine+"Register someone first .");
                }
            }
            catch (BioSDK710Exception cgtEx)
            {
                MessageBox.Show(cgtEx.ShowError(), "CogentBioSDK710 Error");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //else if(chkbCaptureOnly.Checked == true && (bTemplateDataOne == null || bTemplateDataTwo == null))
        else if (chkbCaptureOnly.Checked == true && (bTemplateDataOne == null))
        {
            MessageBox.Show("Please uncheck 'Capture Only' and recapture.", "Warning");
        }
        //else if (chkbCaptureOnly.Checked == false && (bTemplateDataOne == null || bTemplateDataTwo == null))
        else if (chkbCaptureOnly.Checked == false && (bTemplateDataOne == null))
        {
            MessageBox.Show("Please capture fingerprints.", "Warning");
        }

    }


text:
Q: How to convert total value to percentage % in vue js / javascript? I am trying to create a progressbar i want to convert total value to percentage % and want to show it as a style width value, for example
40% out of 100% here 40% will 400USD and 100% will be 1000USD how can we do it is it possible to create some function in array object?
I am using VueJS 3 with Nuxt Js
Below is my VueJs code in < Progressbar /> component
<template>

</template>

Style
.progress-bar{
    background-image: linear-gradient(45deg, rgba(255,255,255,0.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,0.15) 50%, rgba(255,255,255,0.15) 75%, transparent 75%, transparent);
    background-size: 6px 6px;
}
.progress-bar-animated{
    animation: 1s linear infinite progress-bar-stripes;
}
@keyframes progress-bar-stripes {
    0% {
        background-position-x: 0.5rem;
    }
}

export default {
    data(){
        return{
            deals:[
                // deals
                {
                    icon: require("../../assets/img/ico/ico-1.jpeg"),
                    name: "Agoric",
                    type: "Blockchain Service",
                    collected: 883673,
                    goal: 1000000,
                    status: "11h 3m" + " left",
                    link: "/"
                }
            ]
        }
    },
}

A: Just use the formular deal.collected * 100 / deal.goal

new Vue({
    el: '#app',
    computed: {
      percentage() {
        return (deal) => deal.collected * 100 / deal.goal
      }
    },
    data(){
        return{
            deals:[
                // deals
                {
                    icon: ''/*require("../../assets/img/ico/ico-1.jpeg")*/,
                    name: "Agoric",
                    type: "Blockchain Service",
                    collected: 883673,
                    goal: 1000000,
                    status: "11h 3m" + " left",
                    link: "/"
                }
            ]
        }
    },
})
.progress-bar{
    background-image: linear-gradient(45deg, rgba(255,255,255,0.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,0.15) 50%, rgba(255,255,255,0.15) 75%, transparent 75%, transparent);
    background-size: 6px 6px;
}
.progress-bar-animated{
    animation: 1s linear infinite progress-bar-stripes;
}
@keyframes progress-bar-stripes {
    0% {
        background-position-x: 0.5rem;
    }
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.6.1/css/bootstrap.min.css" rel="stylesheet"/>


text:
Q: PMT Javascript function not returning expected results I am trying to calculate loan repayments using the PMT function. I have attempted to recreate this in Javascript using the following formula, but the results are not what I am expecting. All of the variables are returning the expected values:
var pv = loan amount
var fv = future value
var i = interestrate
var n = numberofpayments

var repayment = (pv - (fv / (Math.pow(1 + i), n))) / (1 - (1 / Math.pow(1 + i), n) / i);

I am most likely using the incorrect Javascript syntax somewhere (I am fairly new to Javascript), or it could be an error with my formula, so any help would be much appreciated.
Using the following example:
pv = 10000
fv = 5000
i = 0.25
n = 36

I am getting the following output from the above formula: -68.96
This is incorrect, the correct result should be around: 158
Formula based on: http://www.tvmcalcs.com/index.php/calculators/apps/lease_payments

A: your problem is that you have Math.pow(1 + i), n. Should be Math.pow(1+i,n)
var repayment = (pv - (fv / (Math.pow(1 + i, n)))) / (1 - (1 / Math.pow(1 + i, n)) / i);

--- update
Here is the correct formula:
var pv = 10000;
var fv = 5000;
var i = 0.25 / 12;
var n = 36;

function payment() {
  return (pv - fv) * (i) / (1 - (Math.pow(1 + i, -n)));
}

A: Finally got it to work:
   var pv = parseFloat(document.repaymentcalc.loanamount.value, 10);
   var i = parseFloat(document.repaymentcalc.interestrate.value, 10) / 1200;
   var n = parseFloat(document.repaymentcalc.numberpayments.value, 10) * 12;
   var fv = parseFloat(document.repaymentcalc.finalpayment.value, 10);

   var repayment = ( pv - (fv / Math.pow((1 + i), n))) / ((1 - (1 / Math.pow((1 + i), n))) / i);


text:
Q: Input default pdf in case the src attribute is not found I'm embedding PDF files to a very simple HTML page and everything works fine, but I need a fallback in case the source file does not exist. If the src file is not found an alternative file should be displayed (not-found.pdf for instance).
The problem is very similar as the one on the topic below but with PDF files.
Inputting a default image in case the src attribute of an html <img> is not valid?
I've tried the solutions provided on that topic but none of them worked.
I'm using a simple embed tag:
<embed src="../files/ID 41279.pdf" width="1026px" height="1780" onerror="if (this.src != '../files/not-found.pdf') this.src = '../files/not-found.pdf';">

As you can see I tried to use javascript (as suggested on the topic above) but nothing happens. On the console the error 404  (for the original file) show as usual but the document is blank.
Is it possible to do that with PDF files?
It only need to work on Chrome, so compatibility with other browsers is not necessary.
A pure HTML solution would be better but using javascript or jquery is ok too.
Also, the fallback doesn't need to be a PDF file, I can make do with an image or event text (as long as I can format it).
Thanks!

A: Although this is not an orthodox answer to your question, you can handle the error with apache configuration (if you are using apache server) redirecting on missing file error as mentioned here Redirect requests only if the file is not found?
but maybe you can achieve similar results with other servers.


text:
Q: Why is InternalViewResolver unable to find jsp file? This is my App Controller
@Controller
public class AppController {

    @Autowired
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public UserService getUserService() {
        return userService;
    }

    @GetMapping(value = "/")
    public String getHomePage() {
        return "home";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String getLoginPage(Model model) {
        model.addAttribute("userCredentials", new UserCredentials());
        return "login";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String getRegisterPage(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @RequestMapping(value = "/registered", method = RequestMethod.POST)
    public ModelAndView successfullyRegistered(User user) {
        getUserService().registerUser(user);
        ModelAndView modelAndView = new ModelAndView("welcome");
        modelAndView.addObject("user", user);
        return modelAndView;
    }

    @RequestMapping(value = "/loggedIn", method = RequestMethod.POST)
    public ModelAndView successfullyLoggedIn(UserCredentials userCredential) {
        ModelAndView modelAndView = new ModelAndView("welcome");
        User user = getUserService().validateUserCredential(userCredential.getUserName(), userCredential.getPassword());
        if (user != null) {
            modelAndView.addObject("user", user);
            return modelAndView;
        } else {
            modelAndView = new ModelAndView("notFound");
        }
        return modelAndView;
    }
}

This is my InternalViewResolver
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {
    "com.xyz.login"
})
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public InternalResourceViewResolver resolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        //  resolver.setViewClass(JstlView.class);
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}

Everytime I run the code, I get HTTP 404 Not Found error. It says:

Type Status Report
Message JSP file [/LoginSpringMvcHib/WEB-INF/views/home.jsp] not found

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
I want to return the home page when the app runs.


text:
Q: Can a Java source file also be a valid AsciiDoc document with a table of contents? I have done some experiments with writing programs that are also at the same time valid documentation that can be rendered as README's by e.g. Github - this ensures that code snippets are up to date and valid - and had some very interesting findings with Markdown.  Unfortunately that format does not support having an automatically generated table of contents, so we looked into AsciiDoc which does.
I managed to copy an example using :toc: macro (to be able to place it after the opening summary), and then went on to make it valid Java, which essentially mean that you have to start the file with the /* characters but then I cannot make the table of contents appear any more.
The snippet starts with:
= Asciidoctor PDF Theming Guide
Dan Allen <https://github.com/mojavelinux[@mojavelinux]>
// Settings:
:idprefix:
:idseparator: -
:toc: macro
:experimental:
ifndef::env-github[:icons: font]
ifdef::env-github[]
:outfilesuffix: .adoc
:!toc-title:
:caution-caption: :fire:
:important-caption: :exclamation:
:note-caption: :paperclip:
:tip-caption: :bulb:
:warning-caption: :warning:
endif::[]
:window: _blank
// Aliases:
:conum-guard-yaml: #
ifndef::icons[:conum-guard-yaml: # #]
ifdef::backend-pdf[:conum-guard-yaml: # #]
:url-fontforge: https://fontforge.github.io/en-US/
:url-fontforge-scripting: https://fontforge.github.io/en-US/documentation/scripting/
:url-prawn: http://prawnpdf.org

////
Topics remaining to document:
* line height and line height length (and what that all means)
* title page layout / title page images (logo & background)
////

[.lead]
The theming system in Asciidoctor PDF is used to control the layout and styling of the PDF file
... blurb removed ...
/* (Experiment with asciidoc)

= Dagger 2 Hello World

// (Important:  As an experiment Main.java is also a valid markdown file copied unmodified to README.md, so only edit Main.java)

This project is a single file Hello World Dagger-2 Maven project for
Java 8 and later, while also being its own documentation written in AsciiDoc.

toc::[]

My gut feeling is that the TOC does only work as expected if the file starts with lines parsed by AsciiDoc where this is set up and configured.  If any output is generated before the configuration bits (like the Java comment) then the TOC is silently empty.
Hence I would like to know how I should do this correctly.  All I want is a functional toc::[] macro in a file starting with /*

A: Asciidoc markup files are not Java source files. While I understand that this would be a compelling combination of the formats, that capability does not exist.
To keep source files up-to-date, your Asciidoc source files can use the include directive to include a source file. See: https://asciidoctor.org/docs/user-manual/#include-directive
To include, say, a single method, you can use tags to mark the start and end of the method's implementation, and then you can include that tag-delimited code section like this:
[source,java]
----
include::path/to/source.java[tag="method-x"]
----

Note that if the path to the Java source that you want to include is outside of the current directory, you may have to change the safe mode accordingly: https://asciidoctor.org/docs/user-manual/#running-asciidoctor-securely


text:
Q: iOS accessibility labels not shown in Instruments on device build I have been putting accessibility labels into our source code so that we can automate using apples automation framework.  When we first started this project, we were building using sdk 4.3 and I had troubles getting the simulator to show the labels in the application.  Through advice on stack overflow I was able to fix it by altering the accessibility.plist in the simulator files.
Now that we have switched over to iOS sdk 5.0.  I am having the opposite problem.  I can no longer get the labels to show up on the device when I run our automation tests.  They show up fine in the simulator.  And I'm also able to confirm that they were properly compiled into the application by turning on VoiceOver on the device and doing a triple-double tab of and application window to show the elements.
I've looked over all the build settings and made sure everything was set to a debug build, and have tried going back to a build that I know worked when building for a 4.3 device and having the same exact settings(except for the sdk version of course) but the labels are still not being picked up.
So where do I go from here?  Is there a library file that needs to be included into the application when building for iOS 5?

A: On the device, in "Settings > Accessibility > Triple-click Home", choose "Ask".  This seems to turn on "enough" of the accessibility machinery to make things work, but not so much of it that it'll interfere with the normal functions of the device (ex. turning on VoiceOver works too, but changes the flow of the app in ways that break tests.)


text:
Q: Rearrange HTML table I have a JSON data like this:
var data = [
    {"city":"seattle", "state":"WA", "population":652405, "land_area":83.9},
    {"city":"new york", "state":"NY", "population":8405837, "land_area":302.6},
    {"city":"boston", "state":"MA", "population":645966, "land_area":48.3},
    {"city":"kansas city", "state":"MO", "population":467007, "land_area":315}
  ]

I have added this JSON data into my HTML table. Now how can I randomly arrange this data every 5 seconds when button is clicked?
alter.addEventListener('click', function() {
    //code goes here
})

A: Here is a way how to shuffle you array every 5 seconds after you click your button if you click it multiple times it will always cancel the previous timeout instance

var data = [{
    "city": "seattle",
    "state": "WA",
    "population": 652405,
    "land_area": 83.9
  },
  {
    "city": "new york",
    "state": "NY",
    "population": 8405837,
    "land_area": 302.6
  },
  {
    "city": "boston",
    "state": "MA",
    "population": 645966,
    "land_area": 48.3
  },
  {
    "city": "kansas city",
    "state": "MO",
    "population": 467007,
    "land_area": 315
  }
]

const arrRandomIndex = []
const newArr = [];

while (arrRandomIndex.length !== data.length) {
  const randomNum = Math.floor(Math.random() * data.length);
  if (!arrRandomIndex.includes(randomNum)) {
    arrRandomIndex.push(randomNum);
  }
}

for (let i = 0; i < data.length; i++) {
  newArr[i] = data[arrRandomIndex[i]];
}

let timeId;

document.getElementById('alter').addEventListener('click', function() {
  clearTimeout(timeId);
  timeId = setTimeout(_ => console.log('Random array', newArr), 5000)
})
<button id="alter">
AlTER
</button>

A: Given rows is a nodeList of tr
function randomise() {
    for (const row of rows) {
        const table = row.parentElement;
        table.insertBefore(
            row,
            table.children[Math.floor(Math.random() * table.children.length)]
        );
    }
}

alter.addEventListener("click", () => {
    randomise();
    setInterval(function () {
        randomise();
    }, 5000);
});


text:
Q: How do I fix: InvalidOperationException upon Session timeout in Ajax WebService call We are invoking Asp.Net ajax web service from the client side. So the JavaScript functions have calls like:
// The function to alter the server side state object and set the selected node for the case tree.
function JSMethod(caseId, url)
{
    Sample.XYZ.Method(param1, param2, OnMethodReturn);
}

function OnMethodReturn(result)
{
   var sessionExpiry = CheckForSessionExpiry(result);
   var error = CheckForErrors(result);

   ... process result
}

And on the server side in the ".asmx.cs" file:
namespace Sample
[ScriptService]
class XYZ : WebService
{
       [WebMethod(EnableSession = true)]
        public string Method(string param1, string param2)
        {
            if (SessionExpired())
            {
                return sessionExpiredMessage;
            }
            .
            .
            .
        }
}

The website is setup to use form based authentication. Now if the session has expired and then the JavaScript function "JSMethod" is invoked,
then the following error is obtained:
Microsoft JScript runtime error: Sys.Net.WebServiceFailedException: The server method 'Method' failed with the following error: System.InvalidOperationException-- Authentication failed.
This exception is raised by method "function Sys$Net$WebServiceProxy$invoke" in file "ScriptResource.axd":
function Sys$Net$WebServiceProxy$invoke
{

             .
             .
             .
               {
                    // In debug mode, if no error was registered, display some trace information
                    var error;
                    if (result && errorObj) {
                        // If we got a result, we're likely dealing with an error in the method itself
                        error = result.get_exceptionType() + "-- " + result.get_message();
                    }
                    else {
                        // Otherwise, it's probably a 'top-level' error, in which case we dump the
                        // whole response in the trace
                        error = response.get_responseData();
                    }
                    // DevDiv 89485: throw, not alert()
                    throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceFailed, methodName, error));
}

So the problem is that the exception is raised even before "Method" is invoked, the exception occurs during the creation of the Web Proxy. Any ideas on how to resolve this problem

A: You have a callback method (OnMethodReturn) specified in the WebMethod call, but not an error handler method.  You need to create one and pass it into as you do the callback method.  Then you can handle your failed WebMethod calls in there.

A: This problem occurs even before the Ajax framework can invoke the target method, it fails while creating the web proxy. Anyway I solved the problem by enabling Anonymous access to the Web Service folder and checking for Session explicitly in the Web Service methods

A: Why not use, try { } catch { } around your JS method call?

A: try this one...use "static"
[WebMethod(EnableSession = true)]
public static string Method(string param1, string param2)


text:
Q: R: How to use rlangs .data feature in conjunction with magrittrs pipeline dot? I am making an R-Package and I'm struggling with the imports in a way that pleases R CMD check. It gives me the no visible binding for global variable '.' Note.
I went searching and found this answer, which seems like the best way to deal with the issue.
But it raises a new problem since I can't seem to figure out how to use the rlang .data feature in conjunction with the . from magrittr.
Here is some nice and working code: tibble(A=0:10,B=10:20) %>% .$A
Now I'd like to change it to use the rlang .data feature. Something like this tibble(A=0:10,B=10:20) %>% .data$A exept that it's not working : Error in .$.data : 3 arguments passed to '$' which requires 2
How can I use the .data feature in  conjunction with the . from magrittr? Or to put it more abstract: What is the best way to get rid of R CMD check no visible binding for global variable '.' Note?

A: .data won't help here: it solves the problem for data masking, which is not what's happening with . (see also dplyr . and _no visible binding for global variable '.'_ Note in package check).
I believe you have two choices: either don't use . inside the package, or follow this answer and add
if (getRversion() >= "2.15.1") utils::globalVariables(c("."))

as a top-level call somewhere in your package source.


text:
Q: How to copy only files(not directories) using batch file? The directory structure is:
  Images
    -Folder1
      -image1.jpg
      -image2.jpg
    -Folder2
      -image3.jpg
      -image4.png
    -Folder3
      -image6.png
      -image7.jpg
    -Folder4

I want to copy all images(i.e *.jpg, *.png) files only (not the folders) into the parent directory("Images").
I have tried using "robocopy" as follows:
robocopy /np ..\..\Exam\Images ..\..\Exam\Images *.jpg *.png /S

Here all files as well as folders are copied :(. But I need only files to be copied. How to do this?
Many many thanks in advance!

A: Try this on the command line:
for /r "Images" %i in (*.jpg *.png) do copy "%~fi" "my\target folder"

For a bach script the %  must be doubled %%.

A: I think COPY or XCOPY is best used for files while I prefer Robocopy when dealing with folders.
Using the posted example try: (adjust paths to suit your needs.
    @Echo off
    For /f %%b In ('Dir C:\Exam\Images /b /s /a:d') Do (
       Robocopy %%b C:\Exam\Images *.jpg *.png /xx /np
    )

A: Robocopy only has the /XD switch to exclude directories but it excludes the whole directory. I'd use a batch file to do it instead.
Try this:
@echo off
setlocal

for /f %%a in ('dir *.jpg *.png /b /s /a-d') do (
   copy %%a PathToImagesFolder
)

A: an easier way of doing this might be
for /r %%p in (*.png, *.jpg) do copy %%p destinationFolder.

A: there is an easy to use program called Drop-It if this is a repetitive task then you can use this to sort|move|copy the files to a single directory. hope this helps


text:
Q: nodejs docker localhost website is not working I want to run my nodejs app with docker but it seems not to be working
I have created my dockerfile
built and image
and created a container from the image
I tried accessing it through web browser but it is not working
Nodejs Code
const express = require("express");
const app = express();
const port = 3000;

app.get("/", (req, res) => {
  res.json({ name: "John Stone", email: "stone@gmail.com" });
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

Dockerfile
FROM node:latest
WORKDIR /app
ADD . .
RUN npm install
CMD node index.js

Building image
docker build --no-cache -t user-api:lastest .
creating a container
docker run --name userapi -d -p 80:3000 2d97204ae010
Output
When I go to the web broswer and type localhost:3000 I get "This page isn't working" response

A: -p 3000:80 should be -p 80:3000. The host port number comes first, and the container port number second. See this section of the docker run docs for more details.


text:
Q: Get context of newly started activity via startActivityForResult I am starting an activity via startActivityForResult. Is there any way to get the instance or context of the newly started activity? Thanks.

A: Not that I'm aware of.
When an activity starts another activity, it can pass data to it (call this upstream). When the activity is done, it can return data to the caller (call this downstream). The upstream and downstream communication only happens at the point of invocation and termination respectively.
You seem to need the context of the called activity in the caller. Most likely the calling activity will be put in the "Paused" state when the called activity starts. Even if you were to manage to make the called activity to set the context object to some variable they both can share (e.g. via the global application object), there is no guarantee that the calling activity will be around to make use of the context.


text:
Q: Sum values of each columns with some condition in dataframe to create another dataframe I have one dataframe with
data = {'Clothes':['Shirt-cotton', 'Shirt-silk', 'Trouser', 'Trouser', 'skirt-short', 'skirt-long'],
        'Color':['Black', 'White', 'Blue', 'Grey', 'White', 'Black'],
        'January':[68768,7898,97987,98799, 878, 536],
        'February':[7099,7970,78680,9697, 567,234],
        'March':[9080,8979,8689,9890, 980,765]}

df = pd.DataFrame(data)

df = Clothes      Color   January  February  March
    Shirt-cotton  Black    68768    7099      9080
    Shirt-silk    White    7898     7970      8979
     Trouser      Blue     97987    78680     8689
     Trouser      Grey     98799    9697      9890
    skirt-short   White    878      567       980
    skirt-long    Black    536      234       765

I need output as mentioned below
df1 = Clothes  January  February  March
       Shirt    76666    15069    18059
      Trouser   196786   88377    18579
       skirt    1414      801      1745

df2 = Color  January  February   March
      Black   69304    7333       9845
      White   8776     8204       9959

I am new to pandas, kindly help me to get this output

A: df1 aggregates the monthly values by Clothes types. So you can use groupby + sum:
df1 = df.groupby(df['Clothes'].str.split('-').str[0].str.capitalize()).sum().reset_index()

Output:
   Clothes  January  February  March
0    Shirt    76666     15069  18059
1    Skirt     1414       801   1745
2  Trouser   196786     88377  18579

df2 is filtering df for Shirt entries. One way is to use boolean indexing:
df2 = df[df['Clothes'].str.contains('shir', case=False)]

Output:
  Clothes  Color  January  February  March
0   Shirt  Black    68768      7099   9080
1   Shirt  White     7898      7970   8979


text:
Q: Find Two Largest Numbers, C++ I'm using this approach: First find the largest among 5 numbers then save the subscript of array of the largest number in an "ivariable" after displaying the largest number, do like this
array[ivariable] = 0 ;
so that first largest set to zero and its no longer here in the array.
And do the same again, find the largest, but I'm not getting what I'm trying to.
Its a logical error.
Thanks
#include <iostream>
using namespace std;
int main(void)
{
    int counter, large,number,det_2, i , large3, det_3= 0;
    int det[5] = {0,0,0,0,0};

    for(int k(0); k < 5 ; k++)
    {
        cout << "Enter the number  " << endl ;
        cin >> det[k] ;
    }

    for( i; i<5; i++)
    {
        large = det[i] ;
        if (large > det_2)
        {
            det_2= large ;
            counter = i ;
        }
        else
        {

        }
    }
    cout << "Largest among all is  " << det_2 << endl;
    det[i] = 0 ;

    for( int j(0); j<5; j++)
    {
        large3 = det[j] ;
        if(large3 > det_3)
        {
            det_3= large3 ;
        }
        else
        {

        }
    }
    cout << "Second largest  " << large3 << endl ;

    system("PAUSE");
}

A: You've got possible syntax and initialization errors.  Fix those first:
for(int k(0); k < 5 ; k++):  I've never seen an integer initialized this way.  Shouldn't it be:
for (int k = 0; k < 5; k++) ?  (Same with the last loop.)
Also,
for( i; i<5; i++)
The variable i is uninitialized.  Variables are not initialized to any default value in C++.  Because you've left it uninitialized, it might execute 5 times, no times, or 25,899 times.  You don't know.
This should be:
for (i = 0; i < 5; i++)
But the whole thing could probably be a bit clearer anyway:
#include <iostream>
using namespace std;
int main(void)
{
    int largest = -1;
    int second_largest = -1;

    int index_of_largest = -1;
    int index_of_second_largest = -1;

    int det[5] = {0, 0, 0, 0, 0};

    for (int i = 0; i < 5; i++)
    {
        cout << "Enter the number  " << endl;
        cin >> det[i];  // assuming non-negative integers!
    }

    for (int j = 0; j < 5; j++)  // find the largest
    {
        if (det[j] >= largest)
        {
            largest = det[j];
            index_of_largest = j;
        }
    }

    for (int k = 0; k < 5; k++)  // find the second largest
    {
        if (k != index_of_largest) // skip over the largest one
        {
            if (det[k] >= second_largest)
            {
                second_largest = det[k];
                index_of_second_largest = k;
            }
        }
    }

    cout << "Largest is " << largest << " at index " << index_of_largest << endl;
    cout << "Second largest is " << second_largest <<
            " at index " << index_of_second_largest << endl;

return 0;
}

A: Always give your variables values before you use them
det_2 = det[0];
counter = 0;
for (i = 1; i < 5; i++)

A: *

*first problem I saw was that you are iterating using i as an index, but you don't initialize i.

code should be:
    for(i = 0; i<5; i++)
         ^^^^

*

*same goes for det_2. You compare elements against it, but do not initialize it. You should set it to det[0] before the loop where you use it.

*third problem: Your "set largest value to zero after printing" sounds like it is there so that you can apply the same algorithm the second time.
You should create an additional function that gives you the index of the largest element, and call it like this:
int index = find_largest_index(a);
cout << "largest element: " << a[index] << endl;
a[index] = 0;
cout << "second largest element: " << a[ find_largest_index(a) ] << endl;

A: GCC 4.7.3: g++ -Wall -Wextra -std=c++0x largest.cpp
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

int main() {
  std::cout << "Enter 5 numbers: ";

  // Read 5 numbers.
  std::vector<int> v;
  for (auto i = 0; i < 5; ++i) {
    int x = 0;
    while (!(std::cin >> x)) {
      // Error. Reset and try again.
      std::cin.clear();
      std::cin.ignore();
    }
    v.push_back(x);
  }

  // partition on element 3 (4th number)
  std::nth_element(std::begin(v), std::next(std::begin(v), 3), std::end(v));

  std::cout << "Two largest are: ";
  std::copy(std::next(std::begin(v), 3), std::end(v), std::ostream_iterator<int>(std::cout, " "));
}

A: In the specific case of 5 elements, the algorithm you use is unlikely to make any real difference.
That said, the standard algorithm specifically designed for this kind of job is std::nth_element.
It allows you to find the (or "an", if there are duplicates) element that would end up on position N if you were to sort the entire collection.
That much is pretty obvious from the name. What's not so obvious (but is still required) is that nth_element also arranges the elements into two (or three, depending on how you look at it) groups: the elements that would short before that element, the element itself, and the elements that would sort after that element. Although the elements are not sorted inside of each of those groups, they are arranged into those groups -- i.e., all the elements that would sort before it are placed before it, then the element itself, then the elements that would sort after it.
That gives you exactly what you want -- the 4th and 5th elements of the 5 you supply.
As I said originally, in the case of just 5 elements, it won't matter much -- but if you wanted (say) the top 50000 out of ten million, choosing the right algorithm would make a much bigger difference.

A: nth_element isn't always suitable (or as efficient as it could be) as it needs to rearrange the input elements.
It's very common to want just the top two elements, and can be done efficiently in one pass by keeping the best and second-best values seen so far, and whenever a value you iterate over is better than the second-best, you'll either replace the second-best with it or the best, and in the latter case you also overwrite the best with the new value.  That can look like this:
#include <utility>

template <typename It, typename EndIt, typename Less = std::less<>>
auto top_two(It it, EndIt end, Less less = Less{}) -> std::pair<It, It>
{
    It first = it;
    if (it == end || ++it == end)
        return {first, end};
    std::pair<It, It> results = less(*it, *first) ? std::pair{first, it} : std::pair{it, first};
    while (++it != end)
        if (less(*results.second, *it))
            results.second = less(*results.first, *it)
                             ? std::exchange(results.first, it) : it;
    return results;
}

(See it running at http://coliru.stacked-crooked.com/a/a7fa0c9f1945b3fe)
I return iterators so the caller can know where in the input the top two elements are, should they care (e.g. to erase them from a container, or calculate their distance from begin(), or modify their values).
It you want the two lowest values, just pass std::greater<>{} as your "less" argument.
Some convenience functions to make it easier to call with containers or initializer_lists:
template <typename Container, typename Less = std::less<>>
auto top_two(const Container& c, Less less = Less{})
{
    return top_two(begin(c), end(c), less);
}

template <typename T, typename Less = std::less<>>
auto top_two(const std::initializer_list<T>& il, Less less = Less{})
{
    return top_two(begin(il), end(il), less);
}

If you want a general solution for the top-N elements, it's better to make N an argument and create a multiset of N top values (using a dereferencing comparison type), putting the initial N elements in, then whenever a new element is more than the **top_n.begin() value, do a top_n.insert(it); followed by top_n.erase(top_n.rbegin()); to drop the worst element: these operations are O(log N) so remain reasonably efficient even in pathological cases, such as input that is incrementing numbers.


text:
Q: Calling all synonymists! We need your help! And now plural(s) too? There is a straightforward query provided by Michael Mrozek with SEDE
Alarming Results
There are 607 tag pairs on Stack Overflow which differ by only a hyphen!!
SELECT a.TagName AS First, b.TagName AS Second
FROM Tags AS a, Tags AS b
WHERE a.Id < b.Id
AND REPLACE(a.TagName, '-', '') = REPLACE(b.TagName, '-', '');

Call to Arms
After upvoting his awesomeness, please make synonym suggestions.  Note that this data is a month old, so -- for example -- stackoverflow and stack-overflow were already proposed, but still need votes!!
And, lest you think this is on a problem on Stack Overflow, Programmers has six tag pairs and I'm sure there are plenty others out there -- Super User has 29.  Server Fault has 55.  Let's get those badges!
And also Plurals
After learning a bit more SQL, I've also constructed a query for tags which differ by only ending in 's' or 'es'.  There are currently 614 tag pairs on Stack Overflow which fit this criterion.  Now it does incorrectly catch (css, c) as well as  (aes, a), but it certainly has plenty of synonyms to suggest!!

*

*112 on Server Fault

*37 on Super User

*28 on Programmers

A: Among the many proposals generated by these queries, here's a three -> one:

*

*performance-counter (6 questions) -> performance-counters

*performancecounters (3 questions)  -> performance-counters

*performancecounter (191 questions)  -> performance-counters
though performance-counters only has 33 questions, the:

*

*phrase is two words, meriting the hyphen

*plurals tend to be preferred as 'all-encompassing'

And the same goes for:

*

*control-templates (2 questions) -> control-templates

*controltemplates (19 questions)  -> control-templates

*controltemplate (302 questions) -> control-templates
though control-templates only has 2 questions.  So perhaps controltemplate instead?
Update: And for...

*

*web-controls (31 questions) -> web-controls

*webcontrols (189 questions)  -> web-controls

*webcontrol (58 questions) -> web-controls
though control-templates only has 31 questions?

A: See also these queries:

*

*https://data.stackexchange.com/stackoverflow/s/433/tags-spelling-variants-dashes

*https://data.stackexchange.com/stackoverflow/s/432/tags-spelling-variants-singular-plural

*https://data.stackexchange.com/stackoverflow/s/431/tags-spelling-variants-ae-be-z-s


text:
Q: adding user in java CRUD web app This is my first CRUD Web application based on Java. I am using Eclipse, Tomcat EE server, and MySQL database. The application contains basically a list of users with first name, last name, date of birth, phone number, email, address.
At this point I want to make possible adding a new user to the list of users, still cannot figure out where the problem is, and why I cannot make it work.
Here is part of the code referring to the problem.
This is the servlet:
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String page = "";
        String action = request.getParameter("action");
        if (action.equals("addUser")) {
            User user = new User();
            user.setFirstName(request.getParameter("firstName"));
            user.setLastName(request.getParameter("lastName"));
            user.setPhoneNumber(request.getParameter("phoneNumber"));
            user.setEmail(request.getParameter("email"));
            String month = request.getParameter("month");
            String day = request.getParameter("day");
            String year = request.getParameter("year");
            user.setDob(UserController.parseDate(month, day, year));
            boolean addUs = dbUtil.addUser(user);
            if (addUs) {
                page = "/UsersList.jsp";
            } else {
                page = "/AddUser.jsp";
            }
            RequestDispatcher dispatcher = request.getRequestDispatcher(page);
            dispatcher.forward(request, response);
        }
        doGet(request, response);
    }
And here is the DAO Implementation:
@Override
public boolean addUser(User user) {
    try (Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);) {
        String query = "INSERT INTO users (firstName, lastName, dateOfBirth, phoneNumber, email)"
                + " VALUES (?, ?, ?, ?, ?);";
        PreparedStatement stmt = conn.prepareStatement(query);
        stmt.setString(1, user.getFirstName());
        stmt.setString(2, user.getLastName());
        stmt.setDate(3, (Date) user.getDob());
        stmt.setString(4, user.getPhoneNumber());
        stmt.setString(5, user.getEmail());
        stmt.executeQuery();
        return true;
    } catch (SQLException sqle) {
        System.err.println("Error with connection.");
        sqle.printStackTrace();
        return false;
    }

}

I am ready to share any additional information if necessary.