text:
Q: Java Try-Catch Exception Calculator So I'm trying to make a user input calculator using try-catch and exception. The program keeps on repeating and couldn't get the actual input for the numbers and it also includes the statement Wrong input. Please try again.
Any idea on how to fix this?
import java.util.*;
public class Calculator
{
    public static void main(String[] args) {
        int x=1;
        do {
            try {
                System.out.println("Menu");
                System.out.println("1-Addition");
                System.out.println("2-Subtraction");
                System.out.println("3-Multiplication");
                System.out.println("4-Divison");
                System.out.println("5-Modulos");
                System.out.println("6-Exit");
                System.out.println("Choose option: ");
                Scanner scan = new Scanner(System.in);
                int choice = scan.nextInt();

                switch (choice) {
                    case 1:
                        System.out.print("Input two numbers:");
                        String dimension = scan.nextLine();
                                String[] parts = dimension.split(" ");
                                int a = Integer.parseInt(parts[0]);
                                int b = Integer.parseInt(parts[1]);
                                int c=a+b;
                                System.out.println("Sum = " +c);
                            break;
                    case 2:
                        System.out.print("Input two numbers:");
                        String dif = scan.nextLine();
                                String[] difference = dif.split(" ");
                                int num1 = Integer.parseInt(difference[0]);
                                int num2 = Integer.parseInt(difference[1]);
                                    int d=num1-num2;
                                    System.out.println("Difference = " +d);
                        break;
                    case 3:
                        System.out.print("Input two numbers:");
                        String multi = scan.nextLine();
                                String[] product = multi.split(" ");
                                int num3 = Integer.parseInt(product[0]);
                                int num4 = Integer.parseInt(product[1]);
                                int p=num3*num4;
                                System.out.println("Product = " +p);
                        break;
                    case 4:
                        System.out.print("Input two numbers:");
                        String div = scan.nextLine();
                                String[] quotient = div.split(" ");
                                int num5 = Integer.parseInt(quotient[0]);
                                int num6 = Integer.parseInt(quotient[1]);
                                int q=num5/num6;
                                System.out.println("Quotient = " +q);
                         break;
                    case 5:
                        System.out.print("Input two numbers:");
                        String mod = scan.nextLine();
                                String[] modulo = mod.split(" ");
                                int num7 = Integer.parseInt(modulo[0]);
                                int num8 = Integer.parseInt(modulo[1]);
                                int m=num7%num8;
                                System.out.println("Modulos = " +m);
                        break;
                    case 6:
                        System.out.println("Now exiting program...");
                        break;
                }
            } catch (Exception e) {
               System.out.println("Wrong input. Try again.");
            }
        } while (x==1);
    }
}

A: You need to do this
int choice = Integer.parseInt(scan.nextLine());

because you are reading next input with readline()
String dimension = scan.nextLine();

and \n is already present it the stream when you enter your option with nextInt() because nextint() never reads the \n which you leave behind by pressing Enter button.

A: You should add:
scan.skip("\n");

right after
int choice = scan.nextInt();

Why? Because nextInt() reads next integer from input. And it leaves new line character at the end on the input. It's like:
1<enter>

After that you invoke scan.nextLine() which reads everything up to next new line character. In fact there is 1 new line character in the buffer. And here your nextLine() reads an empty string.
To solve that issue you have to skip buffered new line characters with scan.skip("\n").
EDIT:
in addition, your code doesn't allow you to exit, because you're not changing your x variable. Try to change it after System.out.println("Now exiting program...");. It will work ;)

A: This will help you to identify root cause:
} catch (Exception e) {
    System.out.println("Wrong input. Try again.");
    e.printStackTrace();
}


text:
Q: Download file by passing URL using java code I am trying to write a code in java in which user provide a url link and the program take url link and download a web page as it is and save at particular location..same as save as... option available on webpage.
Please can anybody help me
Thanks in advance

A: // Sample URL :  http://www.novell.com/coolsolutions/tools/downloads/ntradping.zip
import java.io.*;
import java.net.*;

public class UrlDownload {
    final static int size = 1024;

    public static void fileUrl(String fAddress, String localFileName, String destinationDir) {
        OutputStream outStream = null;
        URLConnection uCon = null;

        InputStream is = null;
        try {
            URL url;
            byte[] buf;
            int byteRead, byteWritten = 0;
            url = new URL(fAddress);
            outStream = new BufferedOutputStream(new FileOutputStream(destinationDir + "\\" + localFileName));

            uCon = url.openConnection();
            is = uCon.getInputStream();
            buf = new byte[size];
            while ((byteRead = is.read(buf)) != -1) {
                outStream.write(buf, 0, byteRead);
                byteWritten += byteRead;
            }
            System.out.println("Downloaded Successfully.");
            System.out.println("File name:\"" + localFileName + "\"\nNo ofbytes :" + byteWritten);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void fileDownload(String fAddress, String destinationDir) {
        int slashIndex = fAddress.lastIndexOf('/');
        int periodIndex = fAddress.lastIndexOf('.');

        String fileName = fAddress.substring(slashIndex + 1);

        if (periodIndex >= 1 && slashIndex >= 0 && slashIndex < fAddress.length() - 1) {
            fileUrl(fAddress, fileName, destinationDir);
        } else {
            System.err.println("path or file name.");
        }
    }

    public static void main(String[] args) {
        if (args.length == 2) {
            for (int i = 1; i < args.length; i++) {
                fileDownload(args[i], args[0]);
            }
        } else {
        }
    }
}

It is working fully.

A: You can use Java URL API to get an input stream on the URL then read the from it and write through output stream on a file.
see read data from url, Write to file

A: Have a look at the HtmlParser. It has some features that will help you extract resources from a web page.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are the command(s) to script a daily time sync? I'm experiencing clock drift on my Mac Mini of 1-2 minutes every day.  Like questioner here, I get relief if I open Date & Time from preferences every day or two.  It doesn't stop the drift, just corrects the time back to normal.  This tells me that the time server configured (or at least the one that's consulted when I use the UI to update time) is an accurate time server and is still alive, but there's some other force at work to drag time away from that.  Unusual here is that while most systems lose time, I'm gaining time each day [and it's been a gain since I first observed this problem].
This problem persists since before I upgraded from Snow Leopard to Mavericks when Mavericks was released.
This problem persists since installing a fresh "coin battery" (yes the box is 4-5 years old, so a dying battery could've been part of the problem).  It's not unheard of for a new battery to not have charge, but that seems unlikely.
This problem persists even after resetting the NTP.conf settings per the article above.
Basically I'm mystified, and even though I'm inclined to fix the root problem, in the meantime I'm losing big chunks of climactic action in the broadcast TV my EyeTV app is recording for us, and I'd like to at least apply a band-aid to keep my recordings on schedule while I continue to pick away at the root problem.
So while the hardware [mobo, battery] might be the ultimate root cause, I'm not ready to toss the box quite yet - it's still otherwise a workhorse.
Can someone explain to me in simple terms what command(s) I should embed in a daily script (to be wired into my crontab or whatever is currently the best task scheduler in Mavericks)?  If this was a Windows box I'd run something approximately like "w32tm.exe /resync" or "w32tm.exe /config /update".  Can anyone help me come up with an equivalent or appropriate command I should have Mavericks run every day for me?  Thanks!


text:
Q: ubuntu 100% CPU Load from apache My Ubuntu server has a 100% CPU usage due to Apache. Actually there are only a few pages on the server that no one ever visits. What is the reason for this and how can I find out?
Thanks in Advance

vmstat 2

workers

A: Unless I'm missing something, your post does not show your Ubuntu has 100% CPU usage.
What it does show is a high load.  This means a lot of stuff waiting in the queue.  This could be caused by a lot of things, very often heavy disk IO, but there could be other things, like CPU bottlenecks and network IO. My guess is your web server is being heavily hit, and has not been tuned to handle the load.
I'd start with 2 things - running something like "sudo vmstat 2" to see how much CPU is in use, and also your memory, swap (which I doubt is a problem here) and bandwidth.
I'd also look at the Apache logs and see if something like a bot is hitting your site.
You can likely reduce the load by reducing the number of Apache workers (and doing other tuning things), but reducing the workers can cause outages for people trying to use Apache if it is under some kind of DoS or equivalent.


text:
Q: Skipped Jobs because of DST I have to schedule a few jobs using Java Timer using JDK1.4 without using any third-party API.
If the Daylight Saving Time (DST) change is from 2 am to 3 am , what should be the expected behavior for Jobs scheduled between the DST transition time i.e 2 am and 3 am?

*

*Should the jobs be simply ignored as the time between 2 am and 3 am never appears on the clock

*Should they be run immediately at 3 am.

*Any other expected behavior ?

I think that many Enterprise applications cannot afford to skip the jobs. How should one proceed ?

A: Don't store/run/etc. anything using DST.  It's... difficult to maintain.
UTC
Store all dates in the database in UTC.  Perform all time calculations in UTC.  Maintain a single standard non-changing time measurement for all business processes.  Only when displaying a result to a user (showing on a screen, printing on a report, etc.) do you then localize the time to whatever that user would expect.
Basically consider all back-end logic to be in UTC, and at the interface level there would be a kind of translation layer between localized time and "system" time.

A: The answer by David is correct.
ScheduledExecutorService
In addition, I suggest using the ScheduledExecutorService rather than Timer.
Be sure to read up on including all the JavaDoc. Search StackOverflow to find discussion and example code. Specifically you must trap for all Exceptions or else the service will halt.


text:
Q: Submit an input at each character entry I'm trying to create a form in which the submit button is disabled until the text matches my conditions. And I'd like to constantly (each time a character is typed) check the text, instead of having to create a button that will activate another one.
Thanks !

A: You can use jquery and keyup to detect every time that the user type something here is an example:
http://jsfiddle.net/82sTJ/253/
<input type="text" id="text">
<button type="submit" disabled id="submitButton">
Submit
</button>

var condition = "good";
$('#text').keyup(function(event) {
   if($('#text').val() == condition) {
     $("#submitButton").prop('disabled', false);
   }else{
     $("#submitButton").prop('disabled', true);
   }
});

Here is the alternative way using input suggested by Rob:
var condition = "good";
$('#text').on("input", function(event) {
   if($('#text').val() == condition) {
     $("#submitButton").prop('disabled', false);
   }else{
     $("#submitButton").prop('disabled', true);
   }
});

Also you can use something like vue.js or angular to check the value in real time.
*Edited


text:
Q: Github API v3 POST with PHP I'm attempting to use the Github v3 API and posting JSON to update a profile (or some other call) and get the following response from Github;
Array
(
    [message] => Body should be a JSON Hash
)

I have gone over the relevant page on the API Docs: http://developer.github.com/v3/users/
And this page: http://developer.github.com/v3/#http-verbs which covers POST/PATCH
Here is the code that I'm using
$data = array("bio" => "This is my bio" );
$data_string = json_encode($data);

function curl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,1);
    curl_setopt($ch, CURLOPT_USERPWD, "USERNAME:PASSWORD");
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

$result = json_decode(curl('https://api.github.com/user'),true);

I have also tried CURLOPT_CUSTOMREQUEST as 'POST' and 'PATCH' but got the same error response for both.
Can anyone point me in the right direction for posting data to the API?

A: You have to either global $data_string or pass the $data_string variable to curl() for reusability.
Example:
function curl($curl, $data)
{
    $data_string = json_encode($data);
    // your code here
}

A: You should specify the header like this:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));


text:
Q: Angular CLI 6: Where to put library dependencies I'm converting a library (ng-app-state) to use the angular cli, now that v6 supports libraries (yay!).
After scaffolding and copying in some code, here is my first question:
How/where do I add 3rd party dependencies?
To package.json, or to projects/ng-app-state/package.json?

A: Turns out the answer is kind of "both". Understanding the answer comes from this:

*

*package.json is what will be used during development. You actually install all your libraries here for your own use, including the ones that users will also need. You should only have a node_modules/ directory in the root of your project, not within the library's directory (so only run npm install and similar here).

*projects/ng-app-state/package.json is what will be deployed to npm (with some additional fields added by the build process). So copy in the dependencies and/or peerDependencies that users of your library will need. There is no point putting devDependencies here.

That is the full answer. Read on to see an example.
In my case package.json has a long list of many dependencies and devDependencies (you can see it here), but all of this only effects me (and anyone who wants to contribute to ng-app-state). projects/ng-app-state/package.json is much smaller, and this is what affects users of my library:
{
  "name": "ng-app-state",
  "version": "8.0.0",
  "author": "Simonton Software",
  "license": "MIT",
  "repository": "simontonsoftware/ng-app-state",
  "peerDependencies": {
    "@angular/common": ">=6.0.0 <7.0.0",
    "@angular/core": ">=6.0.0 <7.0.0",
    "@ngrx/store": ">=6.0.0 <7.0.0",
    "micro-dash": ">=3.5.0 <4.0.0"
  }
}

After running ng build np-app-state --prod to generate what will be released to npm, this is what ends up in dist/ng-app-state/ (which is what should be published):
{
  "name": "ng-app-state",
  "version": "8.0.0",
  "author": "Simonton Software",
  "license": "MIT",
  "repository": "simontonsoftware/ng-app-state",
  "peerDependencies": {
    "@angular/common": ">=6.0.0 <7.0.0",
    "@angular/core": ">=6.0.0 <7.0.0",
    "@ngrx/store": ">=6.0.0 <7.0.0",
    "micro-dash": ">=3.5.0 <4.0.0"
  },
  "main": "bundles/ng-app-state.umd.js",
  "module": "fesm5/ng-app-state.js",
  "es2015": "fesm2015/ng-app-state.js",
  "esm5": "esm5/ng-app-state.js",
  "esm2015": "esm2015/ng-app-state.js",
  "fesm5": "fesm5/ng-app-state.js",
  "fesm2015": "fesm2015/ng-app-state.js",
  "typings": "ng-app-state.d.ts",
  "metadata": "ng-app-state.metadata.json",
  "sideEffects": false,
  "dependencies": {
    "tslib": "^1.9.0"
  }
}

A: No One Knows, yet.
I'm not sure this information is out there anywhere. I've filed an issue on the bug tracker and it's passed triage. I believe they'll be documented in the future.

*

*https://github.com/angular/angular/issues/43058
Right now to the best of my understanding, it could be said that 100% of all Angular Dependencies that are not core related that are in a project in a workspace, must also be in the workspace. They must be in the project so the end-user knows they're required as that'll get bundled in the dist. They must be in the workspace's package.json so they're actually installed in development with ng build and ng test.

A: It should be added in package.json as peerDependencies

A: The 3rd party dependencies should be placed in dependencies of projects/ng-app-state/package.json
However if the 3rd party dependencies also support ng 6 then you have a different question and more complexity beyond the scope of this question. I will briefly say that you may have to call ng update on their libraries or develop schematics that call theirs which expect their ng 6 version of library being present.

A: The Dependencies are Added in package.json as peerDependencies under the package name


text:
Q: Compact Metric Spaces and Separability of $C(X,\mathbb{R})$ Let $(X,d)$ be a compact metric space. Show that $C(X,\mathbb{R})$ is a separable metric space (space of continuous functions from $X$ to $\mathbb{R}$).

I first showed that if $(X,d)$ is compact, then it must be separable, so we have a dense subset $\{x_{1},x_{2},...\}$ which is countable of $X$. Then, I'm not so sure on how to move forward. I was thinking of using the Stone Weierstrass Theorem for the set of functions:
$F=\{1,f_{1},f_{2},...\}$
Where $f_{n}(x)=d(x,x_{n})$ for $x \in X$. Then, this implies that the above set is dense in $C(X,\mathbb{R})$ and countable, so $C(X,\mathbb{R})$ is separable if $F$ is a unital separating subalgebra.
Clearly $F$ is unital, but I'm not sure on how to show it is separating and a subalgebra of $C(X,\mathbb{R})$ (it is a subset of the former set since the distance function is continuous). How would one proceed with this step?
Thank you for your help.

A: Let $F$ as you said.
Let $\mathbb R[F]$ the $\mathbb R$-subalgebra generated by $F$.
We want to use Stone-Weierstrass theorem on the latter (rather than $F$) and show that it is dense. This will suffice for a proof that $C(X,\mathbb R)$ is separable, since $\mathbb Q[F]$ is countable and dense in $\mathbb R[F]$.
$\mathbb R[F]$ contains $1$ and it is obviously an algebra. Let's show that it separates points.
Let $x\ne y\in X$. Since $\{x_n\}_{n\in\mathbb N}$ is dense, there must exist $x_m$ such that $d(x,x_m)\le \frac13 d(x,y)$. Forcibly, it cannot hold $d(y,x_m)=d(x,x_m)$. If it held, then $$d(x,y)\le d(x,x_m)+d(y,x_m)\le \frac23 d(x,y)$$ absurd.
So the function $f_m$ separates $x$ and $y$.
Stone-Weierstrass can therefore be used on $\mathbb R[F]$, completing the proof.
Precisations:

*

*How is $\mathbb R[F]$ defined? Either the intersection of all the $\mathbb R$-subalgebras of $C(X,\mathbb R)$ which contain $F$ or, equivalently, as the $\mathbb R$-vector subspace of $C(X,\mathbb R)$ generated by the products of finitley many elements of $F$.

*How is $\mathbb Q[F]$ defined? Either the intersection of all the $\mathbb Q$-subalgebras of $C(X,\mathbb R)$ that contain $F$ or, as above, the $\mathbb Q$-vector subspace of $C(X,\mathbb R)$ generated by the products of finitely many elements of $F$.

*Why is $\mathbb Q[F]$ dense in $\mathbb R[F]$? It is rather easy, actually, but the notation is a bit tedious.
If $g\in\mathbb R[F]$, then there exist $k\in\mathbb N,\ g_1, \cdots, g_k\in F$ and a finite set $S\subseteq \mathbb N^k$ such that $$g=\sum_{(n_1,\cdots,n_k)\in S} \lambda_{n_1,\cdots,n_k}g_1^{n_1}\cdots g_k^{n_k}$$ for some $\lambda_{n_1,\cdots,n_k}\in\mathbb R$.
Now, if you approximate each $\lambda_{n_1,\cdots,n_k}$ with rationals $$\alpha_{n_1,\cdots,n_k}^{(t)}\stackrel{t\to\infty}{\longrightarrow}\lambda_{n_1,\cdots,n_k}$$
and call $$g^{(t)}=\sum_{(n_1,\cdots,n_k)\in S} \alpha^{(t)}_{n_1,\cdots,n_k}g_1^{n_1}\cdots g_k^{n_k}\in\mathbb Q[F]$$
you get $$\Vert g-g^{(t)}\Vert_\infty=\left\Vert \sum_{(n_1,\cdots,n_k)\in S} (\lambda_{n_1,\cdots,n_k}-\alpha_{n_1,\cdots,n_k}^{(t)})g_1^{n_1}\cdots g_k^{n_k}\right\Vert_\infty\le\\\le \left(\sum_{(n_1,\cdots,n_k)\in S}\Vert g_1^{n_1}\cdots g_k^{n_k}\Vert_\infty\right)\cdot\max_{(n_1,\cdots,n_k)\in S}\left\vert\lambda_{n_1,\cdots,n_k}-\alpha^{(t)}_{n_1,\cdots,n_k}\right\vert\stackrel{t\to\infty}{\longrightarrow}0$$


text:
Q: SQLite and PostgreSql longtext Does anyone know how to change a column in SQLite and PostgreSQL to LONGTEXT?
I have done so in MySQL successfully with:
"ALTER TABLE projects MODIFY description LONGTEXT;"
But this clause doesn't seem to work on SQLite. I tried hard to find documentation on PostgreSQL, but that site's format really makes people puke. SQLite's website is better but the only command I find relevant, alter table, doesn't seem to support changing column data type at all. ( infact, it doesn't even allow changing column name!!!)
Thanks all!

A: AFAIK, PostgreSQL does not have a limit on blobs, so don't worry.
SQLite3, apparently, doesn't care about the column type in this case (i.e. TEXT is the same as LONGTEXT)

A: For PostgreSQL, see the doc here (e.g., ALTER TABLE my_table ALTER COLUMN my_col text).
The SQLite doc states

SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.

And I suppose changing the datatype of the column is out of scope. Probably to support this, you will need to do a SELECT * INTO ... followed by DROP TABLE ... and then create the table and run INSERT INTO ... SELECT * FROM ...

A: There's no point in declaring a LONGTEXT column in SQLite.  All type names with TEXT or CHAR or CLOB in them are equivalent.

A: I don't know what problem you have with Postresql documentation, it's  quite good IMO.
To change a column datatype, here is the syntax.
Postgres supports arbitrary long strings (well, up to 2 GB or so) with the TEXT datatype.


text:
Q: Data copied between rows on form's datagrid Within AX 2009, I have, through compare and compile, added two new controls within a datagrid on a form, a Real edit and a combobox. I have compiled with no issues. The Allow Edit property is set to Yes on both controls.
However, on the form, if I edit one row, whether typing a new number with Real edit or combobox, and don't hit Save but hit the Down Arrow key, the data I typed on the previous records is duplicate in the next record and so on until I release the Down Arrow key, rather than just setting the focus on a new record.
The table where these fields were created doesn't exhibit this behavior. The focus simply moves to the next record and what was typed will not carry over to the next record. Only the form does this...
Has anyone seen this behavior before with AX forms?

A: You may have omitted to specify the data source on the grid itself?
Or if the new controls are based on Edit methods on the data source, have you got the data source parameter in the method signature?
see http://msdn.microsoft.com/en-us/library/aa637541(AX.10).aspx


text:
Q: How to get list of all branches created off a GIT branch (get all sub branches of a branch) Is there a way to get the list of all branches created off a branch in GIT.
For e.g. If we have say Rel2 branch created off master, and then we have SP1, SP2 and SP3 created from Rel2 Branch.
Is there any command in GIT to get SP1, SP2 and SP3 as output if i give Rel2 as input ?

A: Just take a commit you want and do
git branch --contains commitid

in your case you can also do
git branch --contains Rel2

This will list all branches that have the given commit in their history.
To list remote branches do
git branch -r --contains commitid


text:
Q: Installation issue with a `FetchContent`ed library I am trying to install and export the target defined by the following CMakeLists.txt in a Windows environment. It uses FetchContent to download a library from github. I can build the library with no problem and generate nfd.lib. My goal is to use this library in my other projects.
cmake_minimum_required(VERSION 3.24)
project(mynfd VERSION 1.0.0)
include(FetchContent)

FetchContent_Declare(nfd
        GIT_REPOSITORY https://github.com/btzy/nativefiledialog-extended.git
        GIT_TAG c++-version)
FetchContent_MakeAvailable(nfd)

At this point, nfd.lib is successfully built in _deps/nfd-build/src/nfd.lib.
When I add the following install commands to the CMakeLists.txt above, I run into issues.
# Installation
include(GNUInstallDirs)
install(TARGETS nfd
        EXPORT ${PROJECT_NAME}Targets
        FILE_SET HEADERS
        PUBLIC_HEADER DESTINATION ${nfd_SOURCE_DIR}/src/include
        )

install(EXPORT ${PROJECT_NAME}Targets
        FILE ${PROJECT_NAME}Targets.cmake
        NAMESPACE ${PROJECT_NAME}::
        DESTINATION lib/cmake/${PROJECT_NAME})

I get the following error messages.
CMake Error in cmake-build-debug-visual-studio/_deps/nfd-src/src/CMakeLists.txt:
  Target "nfd" INTERFACE_INCLUDE_DIRECTORIES property contains path:

    "C:/Dev/myproject/src/test/cmake-build-debug-visual-studio/_deps/nfd-src/src/include/"

  which is prefixed in the build directory.

CMake Error in cmake-build-debug-visual-studio/_deps/nfd-src/src/CMakeLists.txt:
  Target "nfd" INTERFACE_INCLUDE_DIRECTORIES property contains path:

    "C:/Dev/myproject/src/test/cmake-build-debug-visual-studio/_deps/nfd-src/src/include/"

  which is prefixed in the build directory.Target "nfd"
  INTERFACE_INCLUDE_DIRECTORIES property contains path:

    "C:/Dev/myproject/src/test/cmake-build-debug-visual-studio/_deps/nfd-src/src/include/"

  which is prefixed in the source directory.

How can I resolve this problem?


text:
Q: How can i use handlebars data in front end js variable I'm passing an object array to handlebars.
i'm retrieving it on front end like this
{{this.coment}}
The object contains this:
`{
    _id: "5c527707e28b4fac758cc674",
    sectionId: "2",
    comments: [
      {
        replies: [],
        authorAvatarUrl:
          "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDW3D0Emu0_gpP-tAEGPjW88zSabvpdICv6BaoNLArqY3xB4NA",
        authorName: "Jesus Zuñiga Vega",
        authorId: "1",
        authorUrl: "",
        comment: "Test",
        id: "72845"
      }
    ]
  },
  {
    _id: "5c5279f2e28b4fac758cc761",
    sectionId: "3",
    comments: [
      {
        replies: [],
        authorAvatarUrl:
          "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDW3D0Emu0_gpP-tAEGPjW88zSabvpdICv6BaoNLArqY3xB4NA",
        authorName: "Jesus Zuñiga Vega",
        authorId: "1",
        authorUrl: "",
        comment: "Test2",
        id: "37940"
      }
    ]
  },
  {
    _id: "5c527ce2e28b4fac758cc887",
    sectionId: "1",
    comments: [
      {
        replies: [],
        authorAvatarUrl:
          "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDW3D0Emu0_gpP-tAEGPjW88zSabvpdICv6BaoNLArqY3xB4NA",
        authorName: "Jesus Zuñiga Vega",
        authorId: "1",
        authorUrl: "",
        comment: "Hello",
        id: "77251"
      }
    ]
  }`

Note that it is missing the "[ ]" of the array
i want to know if it is possible to put the data in a js variable to use it in front end like this:
var existingComments = [
  {
    _id: "5c527707e28b4fac758cc674",
    sectionId: "2",
    comments: [
      {
        replies: [],
        authorAvatarUrl:
          "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDW3D0Emu0_gpP-tAEGPjW88zSabvpdICv6BaoNLArqY3xB4NA",
        authorName: "Jesus Zuñiga Vega",
        authorId: "1",
        authorUrl: "",
        comment: "Test",
        id: "72845"
      }
    ]
  },
  {
    _id: "5c5279f2e28b4fac758cc761",
    sectionId: "3",
    comments: [
      {
        replies: [],
        authorAvatarUrl:
          "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDW3D0Emu0_gpP-tAEGPjW88zSabvpdICv6BaoNLArqY3xB4NA",
        authorName: "Jesus Zuñiga Vega",
        authorId: "1",
        authorUrl: "",
        comment: "Test2",
        id: "37940"
      }
    ]
  },
  {
    _id: "5c527ce2e28b4fac758cc887",
    sectionId: "1",
    comments: [
      {
        replies: [],
        authorAvatarUrl:
          "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDW3D0Emu0_gpP-tAEGPjW88zSabvpdICv6BaoNLArqY3xB4NA",
        authorName: "Jesus Zuñiga Vega",
        authorId: "1",
        authorUrl: "",
        comment: "Hello",
        id: "77251"
      }
    ]
  }
];

Any help will be much aprecciated thank you very much!!!

A: One way you could do this is by generating a script tag.
<script type="application/javascript">var comment = {{{this.coment}}};</script>

Now, the variable should be available to use in your Javascript.  However, I do not prefer this approach since it is using a global variable.

A: Yes you can achieve this by creating helpers in the route file like this
handlebars = handlebars.create({
 helpers: {
  assign:function (varName, varValue, options) {
        if (!options.data.root) {
            options.data.root = {};
        }
        options.data.root[varName] = varValue;
    }
 }
})

And then in front end you can initialize or assign value to a variable like this
{{assign 'existingComments' this.coment}}

And then in order to access can use
{{@root.existingComments }}


text:
Q: How to integrate Dashboard created using Pentaho user console with web application I have created dashboard using pentaho user console.
The same dashboard needs to be integrated & displayed in java web application.
Please help me on this.


text:
Q: ArrayList method for list with sub categories Here's the code I'm using right now:
    public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot moviecatlog: dataSnapshot.getChildren()) {
                Actors =  (String) moviecatlog.child("Actors").getValue();
                Description = (String) moviecatlog.child("Description").getValue();
                Director = (String) moviecatlog.child("Director").getValue();
                Genre = (String) moviecatlog.child("Genre").getValue();
                Published = (String) moviecatlog.child("Published").getValue();
                MovieUrl = (String) moviecatlog.child("MovieUrl").getValue();
                Status = (String) moviecatlog.child("Status").getValue();
                ThumbUrl = (String) moviecatlog.child("ThumbUrl").getValue();
                Title = (String) moviecatlog.child("Title").getValue();
                id = (String) moviecatlog.child("id").getValue();

//                    recyclerView.setAdapter(new RecyclerViewAdapter(moviecatlog));

                ar = new ArrayList<String>();

                ar.add(Actors);
                ar.add(Description);
                ar.add(Director);
                ar.add(Genre);
                ar.add(MovieUrl);
                ar.add(Published);
                ar.add(Status);
                ar.add(ThumbUrl);
                ar.add(Title);
                ar.add(id);

                recyclerView.setAdapter(new RecyclerViewAdapter(ar));

How to put that data in an ArrayList? Right now, I'm just able to put all the data at once, but at the end, it only shows the properties of last item in the ArrayList.

A:    Arraylist actor=new Arraylist ();
        notification = new ArrayList<HashMap<String, String>>();
        notification1 = new ArrayList<HashMap<String, String>>();

        HashMap<String, String> list = new HashMap<String, String>;
          actoredata[]={om puri ,raj,};
          directore[]={mahesh bhatt,payrelal};
          for(i=0;i<actoredatalenth(),i++){

            list.put("actor", actore[i])));
        notification.add(list);
            }
            actore.add(notification);
             for(i=0;i<directorelenth(),i++){

            list.put("actor", directore[i])));
        notification.add(list);
            }actore.add(notification);


text: Q: Acrobat XI doesn't save javascript events I am having a problem with adding custom keystroke and format scripts into a text field. As it is told in the documents, I right click the field and select properties, go to the format tab and select custom as the format catagory, click one of the edit buttons, write some javascript and click ok. But, nothing is saved. It turns back to the format tab with format category is none, just an empty window. Does anyone know what is causing this problem?


text:
Q: Check if sender is UIBarButtonItem Can anyone tell me the correct way to check if sender was a UIBarButtonItem or not.
NSLog gives me these depending on what sender is:
sender for segue = <UIBarButtonItem: 0x6845e70>
sender for segue = <NSIndexPath 0x687fd00> 2 indexes [0, 0]
What command is used in an if statement to check for UIBarButtonItem?
Thanks

A: if([sender isKindOfClass:[UIBarButtonItem class]])

should do it for ya

A: Check this awnser: How do I test which class an object is in Objective-C?.
You could log the sender's class.
NSLog(@"Sender is a %@",NSStringFromClass([sender class]));

A: Worked for me !
if([sender isKindOfClass:[UIBarButtonItem class]])
{
    //Do stuff here
}


text:
Q: 'Minimize' a ViewController that user can access at any time anywhere in the app I need some hints or suggestions on an issue.
What I want to do is to 'Minimize' a UIViewController like the 'message circles' in old facebook messages. So that the user can continue using the app and just move the circle to anywhere on the screen and then tap it to open it up and continue working from there.
The minimized UIViewController is suppose to be a UIWebView and I want the user to be able to continue working from whatever state the webpage was in.
I know one is suppose to add code here but I more want some pointers on where to start and how to think or possibly some suggested codesnippets or links.
Hope someone can help me out.
Thanks
edit: Thanks Moti. Ok so I will Not be using storyboard but do do everything programmatically.
I will have it not fully hidden but 'minimized' as an ontop circle to be accessed to just by tapping it anywhere from in the app.
Trick14, I will have a check. tnx

A: If its part of navigation controller you can keep strong reference to it somewhere, so when you pop it out it will stay alive. And when you need it you can push it again.
If you can describe some more details regarding how you show/hide and if its part of storyboard or built in runtime, the community will be able to be more specific regarding solutions.
If you look into UIViewController you will see
addChildViewController:
removeFromParentViewController
willMoveToParentViewController:
didMoveToParentViewController:
You can play around with those to achieve what you need, for example when you detect that the "overlay" controller removed from parent view controller you could push it back in the method didMoveToParentViewController: of the the other controller.
Yes, there is some management to be done, but it is possible.
I will try to make some working example with dummy views.

A: Make a Base View Controller which is inherited by every ViewController in your app. Declare the functions in it. And you can directly access these functions in any of your base class. Or simply hide or show your view anywhere in your app.


text:
Q: Site.createPortalUser(u, accountId, password); returning null sometimes I am trying to enable self-registration in communities through sites but it is returning null randomly even when all the 3 values are populated. On the searching web, I found that we need to add forceSSl="True" but even after that it is not working.

A: Apparently, if you do not have a password according to validations in your org it Site.createPortalUser returns null.


text:
Q: Get rid of letters that are in string 1 in string 2 and then combine the new string 2 with string 1 I thought I solved this problem but then my solution also removed letters in string 1.
Here are some inputs and outputs that I want to achieve:
a, bcdefg, into abcdefg.   ab, cdefgic, into abcdefgi.   abc, adefghiad, into abcdefghi.   hello,world, into hellowrd. troy, warrior, into troywai.   frizzy,wizzo, into frizzywo.   stops,potts, into stops. stops,potts111, into stops1. stops,potts222, into stops2. jokes,bedazzling into jokesbdazling
Also please explain your solution if you can.

A: str1 = "abc"
str2 = "arabdcd"

letters_list = list(str1+str2)
letters = []

for l in letters_list:
    if l not in letters:
        letters.append(l)
new_string = "".join(letters)


text:
Q: How to present a good look result? I would like to present a good look result for my own functions.
I create my own function to solve some chi-square test exercises, and the result looks like that:

Here is my own function:
chisq.poly = function(prob, freq, significance.level = 0.95) {

  #calculate chi-squared value
  expect_freq<-prob*sum(freq)
  dif_freq<-freq-expect_freq
  dif_freq_sq<-((freq-expect_freq)^2)/expect_freq
  chi_square<-sum(dif_freq_sq)
  chi_square_crit<-qchisq(significance.level, length(freq)-1, lower.tail=TRUE)

  #we put all necessary values into a dataframe (good for display) and then rename headers
  chi_table<-data.frame(prob,freq,expect_freq,dif_freq)
  colnames(chi_table)<-c("Probability","Frequency","Expected frequency","Difference")

  #Finally, we show the result of test
  hypothesis<-"H0: The experimental data is like the statemnent."
  result<-if (chi_square>chi_square_crit) {"Reject the null hypothesis. The experimental data is not like the statemnent."
  }
  else "cannot reject null hypothesis"

  warning_test<-if (abs(sum(expect_freq-freq))<sum(abs(expect_freq-freq))) {"The expected frequency value may be less than 5, the result cannot be properly."
  }
  else "Something good so far."

  O<-list(chi_table,chi_square,chi_square_crit,hypothesis,result,warning_test)

  names(O)<-c('Table','Chi_square','Critical Chi_square','Hypothesis','Result','Warning')

  return(O)
}

And I want to fix it like this or better:


text:
Q: Best way to add a formatted localized string to an ASP.NET page? I've been using <asp:Literal runat="server" meta:resourcekey="Blah" /> with resx files in the App_LocalResources directory for translatable strings, but if my key, Blah.Text is "Enter the {0} category", how would I pass the parameter to replace {0} in this context?
I know I could use <%=string.Format(... but that seems unclean and I can't access the Local Resources in that way. What should I do for this use case?

A: An example of markup:
<asp:Literal runat="server" ID="Blah" />

from the code behind:
Blah.Text = string.Format(
    "Enter the {0} category",
    GetLocalResourceObject("Blah").ToString()
);

by using GetLocalResourceObject method.


text:
Q: $stateChangeStart is not firing in logout I have defined Loginctrl in index page and called it in login.html. Once the user logged in ,he can view a menu where user can navigate to every module (based on the click, ctrler will be changed as mentioned in router). In each module I have called
$scope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams) to track whether user have made any changes.
This event is firing properly in module navigation, but if i click the logout icon (logout method is in loginctrl),logout method is fired first and then this event gets fired.
Why this event is not firing even the state gets changed?


text:
Q: typescript interface with function returning different types Learning typescript and currently developing the following structure
type AModel {
    propA: string
}

type BModel {
    propB: string
}

class AController {
    payload():<AModel> {}
}

class BController {
    payload():<BModel> {}
}

Each controller must implement a payload function which returns their specific payload type. So I want something like this:
interface Payload {
    payload():<T>
}

class AController implements Payload {
    payload():<AModel> {}
}

class BController() implements Payload {
    payload():<BModel> {}
}

I'm assuming that the only way to define T is via a union type of all the different models that could be returned - or is there a better way?

A: You were close to the right path. By using generics you can achieve what you want:
Check the code in playground
interface Payload<T> {
  payload(): T;
}

interface AModel {
  propA: string
}

class AController implements Payload<AModel> {
    payload() {
      return { propA: 'someValue' }
    }
}

A: It depends on how free you want implementations of Payload to be.
If Payload can't only hold very specific types, then you should declare a union of what those are.
But, if Payload doesn't care what it holds, then I think you want this:
interface Payload {
    payload(): unknown
}

class AController implements Payload {
    payload(): AModel {
        return { propA: 'a' }
    }
}

class BController implements Payload {
    payload(): BModel {
        return { propB: 'b' }
    }
}

new AController().payload().propA // works

Typescript is smart enough to know that your class returned a subtype of what's declared in the Payload interface, and will use that more specific type if it can.
Playground


text:
Q: How to store 2 digit integer value and float values in char array in C Following is my C code to print values of char but I am getting unexpected results. The code is
#include<stdio.h>

main()
{

  char sendBuffer[1000];
  float count;
  int i;
  for(count=1.5;count<=2.5;)
  {
   for(i=0;i<=15;)
   {
     sendBuffer[0]=count+48;
     sendBuffer[1]='a';
     sendBuffer[2]='b';
     sendBuffer[3]='c';
     sendBuffer[4]=i+48;
     sendBuffer[5]='\0';
     printf("%s\n",sendBuffer);
     i=i+5;
    }
   count=count+0.5;
  }
}

The results I am getting are:
1abc0
1abc5
1abc:
1abc?
2abc0
2abc5
2abc:
2abc?
2abc0
2abc5
2abc:
2abc?

whereas, I was expecting something like
1.5abc0
1.5abc5
1.5abc10
1.5abc15

and so on. Can anybody tell me how to store integer and float values in char array in C?

A: I see the answers you're getting answer the problem, but don't give an explanation, and from the looks of it, you could use a good explanation, so here's what's happening:
Types in C
You need to understand that different types (int, char, float, double) take up different sizes in memory.  In C, a char is always considered to take up a single byte, and is in the range of -127 to 128.  (unsigned char goes from 0 to 255.)  ints take up 4 bytes, and their range is from -2M to 2M - 1.  float and double take 4 and 8 bytes respectively, and have a huge range, but limited precision.  (For more information, just search for "c type ranges", and you'll find lots of information, including these links on Stack Overflow, which also give you good explanations: Definition of range of a data type, Guarantateed minimum size/range of C data types).
Also, you know enough ascii to know to add 48 to a digit to get the char version, but make sure you have an ascii table nearby.  Conveniently, you can find one at http://www.asciitable.com.
You also have to understand that the compiler will do its best to convert from one to another, though in some cases, such as casting a float to an int, if you don't do it explicitly, your compiler should at least issue a warning.
Strings don't exist as a type in C.  Instead, you print into an array.  Other answers tell you how to do that.  What their code is doing is printing the values you want into a character array, which is all you need.
What your code is doing
Now, let's see what your current code is doing:
First of all, a quick sidebar: when you're doing a for loop, it's best to put the increment in the loop itself, so:
for(count=1.5;count<=2.5;count=count+0.5)
{
  for(i=0;i<=15;i=i+5)

would be more standardized.
Now, your first line is sendBuffer[0]=count+48;.  Here's what happens:

*

*You're taking count, which starts at 1.5, and adding 48, so the first number is 49.5.

*The compiler will automatically change a float to an int, though it should give you a warning about it.  It does so by truncating the value, changing 49.5 to 45.

*It then changes (int)49 to (char)49 which is the same value, but takes up one byte instead of 4.  Ascii 49 is '1', so this happens to be the number you wanted.

*The compiler does not do anything with the rest of the float.  It never sets sendBuffer[1] or [2] for this value.

Your next 3 lines hard code the second, third and fourth characters of the string to abc.  Even if your first line had set the full float value into sendBuffer, this would overwrite it.
Your final line takes i, which will be 0, 5, 10 and 15, and adds it to 48.  This is just like the first step, without the truncation from float.  So first it looks up ascii 48, which is '0', then ascii 53, which is '5'.  When i is 10, it now takes the int 58 and converts it to a character (again, changing it from 4 bytes to 1 byte).  Printing ascii 58 results in ':', and printing ascii 63 results in '?'.  And that's how your output ended up the way it did.
Possible solutions
Finally, a few words on the solution you were given:
Since all you're doing is outputting the result, you don't need sendBuffer nor snprintf.  Simply using
printf("%.1fabc%d\n", count, i);

would have sufficed.
It's instructive to think about what the printf family of functions does, though.  Though it's less efficient, let's use a few snprintfs to see what it's doing:
int index = 0;
index = snprintf(&sendbuf[index], sizeof(sendbuf) - index, "%.1f", count);
index += snprintf(&sendbuf[index], sizeof(sendbuf) - index, "abc");
index += snprintf(&sendbuf[index], sizeof(sendbuf) - index, "%d", i);
sendbuf[index++] = '\n';
sendbuf[index] = '\0';

What this does is what *printf does when you pass it multiple arguments: keep track of how much you've written and use that to tell where you're writing the next parts.
If you don't know it, the a += b syntax is shorthand for a = a + b.  a++ means "give me the value of a, then increment it."
So the second line of my code will print out the float value into sendbuf, starting at the 0 position.  *printf always returns the number of characters printed, so in this example, it will always print 3 characters, and I set index to 3.
The next line writes the string abc into sendbuf, starting at position 3, and the line after that prints the value of i into position 6.  Finally, I add the \n for the new line, and the last line is the null terminator.  I don't put index++ because I don't care about index any more, so don't need to bother incrementing it.  I put \0 (as did you above) instead of 0, simply because \0 reminds the programmer that we're dealing with a char array, not an integer array.
Again, all these lines aren't necessary, but since some of the issue seemed to be understanding what printf does, I thought it would be helpful.

A: This can work:
snprintf(sendbuf, sizeof(sendbuf), "%.1fabc%d", count, i);

A: Add a byte to the output array.  The first element needs 3 characters (bytes) not one.
sprintf(sendBuffer,"%0.1f",count);
sendBuffer[3] = 'a';
....


text: Q: Can I export and share my Google Developer Screen Sizes? Under "Emulated Devices" I've added a specific set of screen sizes. I would like to share these with someone so they can simply load them into their Google Developer Tools screen sizes. Is there some way to do that?


text:
Q: Print chunk of lines between matching patterns I have a bunch of email archives which looks like the pattern below. I am trying to separate the emails which is separated by starting From: and ending with the pattern From: .
From: Bikram Suwal veekram@gmail.com
To: John Doe johndoe@gmail.com
Subject: Greetings
Date: 04/05/1990 10:30 PM

Hello.
World
This is a test email.

From: Bikram Suwal veekram@gmail.com
To: John Doe johndoe@gmail.com
Subject: New Greetings
Date: 04/05/1990 10:30 PM

Yet another test email

Using awk, awk '/From/{p=1} p; /Date/{exit}' text.txt. It gives:
From: Bikram Suwal veekram@gmail.com
To: John Doe johndoe@gmail.com
Subject: Greetings
Date: 04/05/1990 10:30 PM

How can I possibly modify the awk command to get:
From: Bikram Suwal veekram@gmail.com
To: John Doe johndoe@gmail.com
Subject: Greetings
Date: 04/05/1990 10:30 PM

Hello.
World
This is a test email.

Thanks in advance

A: For your current input it would be enough to apply the following GNU awk expression:
awk -v RS="\n\n\n+" 'NR==1{ print; exit }' file

The output:
From: Bikram Suwal veekram@gmail.com
To: John Doe johndoe@gmail.com
Subject: Greetings
Date: 04/05/1990 10:30 PM

Hello.
World
This is a test email.

A: If you are not bothered about newline char then
$ awk '/^From:/{count++} count==1' infile

$ awk -v mail_no=1 '/^From:/{count++}count==mail_no; count>mail_no{exit}' infile

Examples :
$ awk '/^From:/{count++} count==1' infile
From: Bikram Suwal veekram@gmail.com
To: John Doe johndoe@gmail.com
Subject: Greetings
Date: 04/05/1990 10:30 PM

Hello.
World
This is a test email.

$ awk '/^From:/{count++} count==2' infile
From: Bikram Suwal veekram@gmail.com
To: John Doe johndoe@gmail.com
Subject: New Greetings
Date: 04/05/1990 10:30 PM

Yet another test email

To remove trailing newline char, I prefer to use tac like below
$ awk -v mail_no=1 '/^From:/{count++}count==mail_no;count>mail_no{exit} ' infile | tac | awk 'NF{found=1}found' | tac
From: Bikram Suwal veekram@gmail.com
To: John Doe johndoe@gmail.com
Subject: Greetings
Date: 04/05/1990 10:30 PM

Hello.
World
This is a test email.

Input :
$ cat infile
From: Bikram Suwal veekram@gmail.com
To: John Doe johndoe@gmail.com
Subject: Greetings
Date: 04/05/1990 10:30 PM

Hello.
World
This is a test email.

From: Bikram Suwal veekram@gmail.com
To: John Doe johndoe@gmail.com
Subject: New Greetings
Date: 04/05/1990 10:30 PM

Yet another test email

From: Bikram Suwal veekram@gmail.com
To: John Doe johndoe@gmail.com
Subject: New Greetings
Date: 04/05/1990 10:30 PM

Yet another test email

A: Find the solution
This will extract all email from the data
String[] separated = data.split("From:");
separated[0];
separated[1]; ......

Pattern p = Pattern.compile("\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b",Pattern.CASE_INSENSITIVE);
ArrayList<String> emails = new ArrayList<String>();
ArrayList<ArrayList<String>> buchEmails = new ArrayList<ArrayList<String>>();
for(int i=0;i<seperated.length();i++){
  Matcher matcher = p.matcher(seperated[i]);
    while(matcher.find()) {
      emails.add(matcher.group());
    }
   buchEmails.add(i,emails);
}

A: If, like @veekram stated in one of the comments, the next "From:" is the separator, then something like:
awk '/From:/{p++} p>1{next}1' file

will do.

A: Why not use a program designed to parse emails like `formail? For example to extract the first message:
<in.mbox formail -1 -f -ds

Output:
From: Bikram Suwal veekram@gmail.com
To: John Doe johndoe@gmail.com
Subject: Greetings
Date: 04/05/1990 10:30 PM

Hello.
World
This is a test email.


text:
Q: Name for time period between boot and shutdown (login/logout is to "session" like boot/shutdown is to ???) The time between login and logout is called a "user session", "login session" or simply "session". Is there a similar specific name for an OS "session", i.e. the period of time between boot and shutdown? "One uptime" is the only thing that comes to my mind, but that seems weird. Can it be used that way? Is there a better term?
Examples:

*

*The NTP sync and the log entry ocurred during the same ?????.
(meaning "the system was not rebooted between the NTP sync and the log entry")

*During one ?????, the uptime value increases monotonically over time.

A: I think you were nearly there yourself - I'd call this an "uptime cycle" if I were so inclined to name it.

A: You could use "system uptime", "uptime period", "uptime cycle" so as not to repeat yourself, e.g.:

*

*The NTP sync and the log entry occurred during the same uptime period.

*The uptime value increases monotonically over time during an uptime cycle.

*Dynamic detection is performed during system uptime


text:
Q: Finding first image on google text search (on the upper block) using jsoup I've used this :
     Elements images = doc.select("img[id^=dimg]");
     Element image = images.first();
     String url = image.absUrl("src");

As div.img-brk is an element represent the images block and I want to fetch the first image there.
div.img-brk img refer to the img decendents of div.img-brk.
adding the url I'm trying to get the image from. Here


text:
Q: Flutter websocket I'm building a real time flutter chat application using websocket.
i'm having issues on where and how to implement websocket so as to make sure that the user is always connected throughout the app. and whenever the user disconnect(due to poor internet connection or such), he will be reconnected automatically to websocket when he comes back online.
Thank you.

A: You will need a websocket server firstly, and will also need to think about which protocol you wish to use for communication with those servers so that you can provide peer to peer communication across all clients. This topic is covered in depth in the post building realtime apps with Flutter and WebSockets.  That's probably a good place to start.


text:
Q: mount bind inside container is not reflecting outside container I am trying to bind host dir to some dir inside container and expecting changes done inside container should reflect on host.
Here is the steps I have followed
created /hostdir on host and run ubuntu container in privileged mode
[root@nhbdlin03 ~]# mkdir /hostdir
[root@nhbdlin03 ~]# docker run -itd --privileged --name ubuntu -v /hostdir:/hostdir:z ubuntu
76aebded33274e95a6f569d0831aee4df27e9f200a8fd0401448239bd6f5bf80
[root@nhbdlin03 ~]# docker exec -it ubuntu bash

creating a container_dir inside container
root@76aebded3327:/# mkdir /container_dir

binding the two directory (successfull)
root@76aebded3327:/# mount --bind /container_dir /hostdir

creating a file named hello.txt inside /container_dir
root@76aebded3327:/# cd container_dir/
root@76aebded3327:/container_dir# touch hello.txt

its get reflected inside /hostdir as it is bind mount to /container_dir
root@76aebded3327:/container_dir# ls /hostdir/
hello.txt

exit container and check on host , is the same reflected
root@76aebded3327:/container_dir# exit

[root@nhbdlin03 ~]# ls /hostdir/
[root@nhbdlin03 ~]# ls /hostdir/ | wc -l
0
[root@nhbdlin03 ~]#

the content are not getting reflected.
I am missing something or doing completely wrong, please help me in the right direction.

A: Your bind mount made with mount --bind /container_dir /hostdir will override volume mount inside the container. You simply bind-mount /container_dir over it (same as when you mount e.g. /boot partition over /boot directory on your root filesystem); so anything you write to /hostdir from that point will go only to /container_dir inside container.
What you probably want to do is to swap mount --bind arguments or just make /container_dir a symlink to /hostdir. Or make /container_dir a Docker volume directly and save the hassle.

A: I am able to achieve above using bind mount type and bind-propagation=shared
[root@nhbdlin03 ~]# docker run -itd --name ubuntu --privileged --mount type=bind,source=/hostdir,target=/hostdir,bind-propagation=shared ubuntu
2cb814f600ed261ae5e50fcdaec6b5a5a17f3d41d37be307765e20274d918a25
[root@nhbdlin03 ~]# docker exec -it ubuntu bash
root@2cb814f600ed:/# mkdir /container_dir

root@2cb814f600ed:/# touch /container_dir/hello
root@2cb814f600ed:/#  mount --bind --make-shared /container_dir /hostdir
root@2cb814f600ed:/# ls /hostdir/
hello
root@2cb814f600ed:/# exit
exit
[root@nhbdlin03 ~]# ls /hostdir/
hello


text:
Q: Force TypeScript to generate export/imports with the ".js" extension; running Node 16? Have a TS 4.7 library using ESM modules.
tsconfig.json:
    "target": "ES2020",
    "module": "ES2020",
    "lib": ["ES2020"],
    "moduleResolution": "node",

package.json
"type": "module",

I have a main file with only a one silly export:
index.ts
export { Spig } from './spig';

which is compiled to:
index.js
export { Spig } from './spig';
//# sourceMappingURL=index.js.map

Problem
When I use this library from a Node CLI program (with ESM modules enabled as well), I get the following error:
Cannot find module <path>/lib/spig imported from <path>/lib/index.js

When I manually add .js in the generated index.js, the issue is gone:
export { Spig } from './spig.js';

How can I force TypeScript compiler to generate the extension, too? What am I missing here?

A: You cannot omit the file extension anymore in ESM module imports. The extension should be always .js/.jsx, not .ts/.tsx for a typescript file. So, in the index.ts you should add the extension to spig export like the following and every other file imported/exported if using ESM modules.:
index.ts
export { Spig } from './spig.js';

Also, moduleResolution should be set to Node16 or NodeNext so ESM modules work as expected.
As stated in the docs (enphasis by me):
Relative import paths need full extensions (e.g we have to write import "./foo.js" instead of import "./foo").
When a .ts file is compiled as an ES module, ECMAScript import/export syntax is left alone in the .js output; when it's compiled as a CommonJS module, it will produce the same output you get today under module: commonjs.
This also means paths resolve differently between .ts files that are ES modules and ones that are CJS modules. For example, let's say you have the following code today:
// ./foo.ts
export function helper() {
    // ...
}

// ./bar.ts
import { helper } from "./foo"; // only works in CJS
helper();

This code works in CommonJS modules, but will fail in ES modules because relative import paths need to use extensions. As a result, it will have to be rewritten to use the extension of the output of foo.ts - so bar.ts will instead have to import from ./foo.js.
// ./bar.ts
import { helper } from "./foo.js"; // works in ESM & CJS
helper();

This might feel a bit cumbersome at first, but TypeScript tooling like auto-imports and path completion will typically just do this for you.


text:
Q: how can i loop Bold one using 'for' function in the matlab? function varargout = voltagealgorithm20150226gui3rd(varargin)
% VOLTAGEALGORITHM20150226GUI3RD MATLAB code for voltagealgorithm20150226gui3rd.fig
%      VOLTAGEALGORITHM20150226GUI3RD, by itself, creates a new VOLTAGEALGORITHM20150226GUI3RD or raises the existing
%      singleton*.
%
%      H = VOLTAGEALGORITHM20150226GUI3RD returns the handle to a new VOLTAGEALGORITHM20150226GUI3RD or the handle to
%      the existing singleton*.
%
%      VOLTAGEALGORITHM20150226GUI3RD('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in VOLTAGEALGORITHM20150226GUI3RD.M with the given input arguments.
%
%      VOLTAGEALGORITHM20150226GUI3RD('Property','Value',...) creates a new VOLTAGEALGORITHM20150226GUI3RD or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before voltagealgorithm20150226gui3rd_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to voltagealgorithm20150226gui3rd_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help voltagealgorithm20150226gui3rd

% Last Modified by GUIDE v2.5 26-Feb-2015 14:51:37

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @voltagealgorithm20150226gui3rd_OpeningFcn, ...
                   'gui_OutputFcn',  @voltagealgorithm20150226gui3rd_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before voltagealgorithm20150226gui3rd is made visible.
function voltagealgorithm20150226gui3rd_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to voltagealgorithm20150226gui3rd (see VARARGIN)

% Choose default command line output for voltagealgorithm20150226gui3rd
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes voltagealgorithm20150226gui3rd wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = voltagealgorithm20150226gui3rd_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu1

% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

axes(handles.axes1);
cla;

for i=1:3
switch popup_sel_index

        case i
            x = [1:1:2]
            **xlRange = ('A1:B1');**
            y = xlsread('naver.xlsx','data',xlRange);
            plot(x,y)

end

end

i wanna make A1:B2 to A2:B2 and A3:B3 .......
i tried ('A(i):B(i)')  but it failed and matlab says Data range is invalid
plz help me solve this problem
how can i make A1:B2 to A2:B2 and A3:B3 by using 'for function'?

A: To fix this, you would have to create a matching string:
['A' num2str(i) ':B' num2str(i)]

For performance reasons, I recommend to read all three lines outside the loop in one call of xlsread.

A: for k=1:1:4
[~,~,raw] = xlsread('data.xlsx','data1');
popup_sel_index = get(handles.popupmenu1, 'Value');
switch popup_sel_index
    case k
    xlRange = sprintf('E%d:CW%d',k,k);
    x1 = [0.25:0.25:24]
    xlRange
    y1 = xlsread('data.xlsx','data1',xlRange);
    plot(x1,y1)
    end

i found the answer


text:
Q: Queue order details in rabbitmq when order is placed in Magento2EE In Magento2 EE,I need to queue to order details instantly when the order is placed. Rabbitmq is our message broker. I have installed rabbitmq and configured to the Magento2EE by following this link https://inviqa.com/blog/magento-2-tutorial-message-queues. . Everything is working fine. I can push the order  array to the queue by giving static order ID.
 <?php

namespace Inviqa\MessageQueueExample\Console;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Framework\MessageQueue\PublisherInterface;
use Inviqa\MessageQueueExample\Api\MessageInterface;
use Magento\Sales\Model\Order;

class MessagePublishCommand extends Command
{
    const COMMAND_QUEUE_MESSAGE_PUBLISH = 'queue:message:publish';
    const MESSAGE_ARGUMENT = 'message';
    const TOPIC_ARGUMENT = 'topic';

    /**
     * @var PublisherInterface
     */
    protected $publisher;
    protected $order;

    /**
     * @var string
     */
    protected $message;

    /**
     * {@inheritdoc}
     */
    public function __construct(
        PublisherInterface $publisher,
        MessageInterface $message,
        Order $order,
        $name = null
    ) {
        $this->publisher = $publisher;
        $this->message = $message;
        $this->order = $order;
        parent::__construct($name);
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $message = $input->getArgument(self::MESSAGE_ARGUMENT);
        $topic = $input->getArgument(self::TOPIC_ARGUMENT);

        try {

            $_orderId = 000000004;
            $_order = $this->order->load($_orderId);
            $_items = $_order->getAllVisibleItems();
            foreach ($_items as $_item) {
                $_orderItems[] = [
                    'sku' => $_item->getSku(),
                    'item_id' => $_item->getId(),
                    'price' => $_item->getPrice(),
                ];

            }
            $message = $_orderItems;

            $this->message->setMessage($message);
            $this->publisher->publish($topic, $this->message);
            /*print_r($message);
            die;*/
           // $output->writeln(sprintf('Published message "%s" to topic "%s"', $message, $topic));
            $output->writeln(sprintf('Published order'));

        } catch (\Exception $e) {
            $output->writeln($e->getMessage());
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->setName(self::COMMAND_QUEUE_MESSAGE_PUBLISH);
        $this->setDescription('Publish a message to a topic');
        $this->setDefinition([
            new InputArgument(
                self::MESSAGE_ARGUMENT,
                InputArgument::REQUIRED,
                'Message'
            ),
            new InputArgument(
                self::TOPIC_ARGUMENT,
                InputArgument::REQUIRED,
                'Topic'
            ),
        ]);
        parent::configure();
    }
}

Once the order is placed, for pushing order object i have planned to use sales_order_place_after event. But i'm not sure how to pull the result from observer, to this execute action.


text:
Q: ASensorEventQueue_hasEvents returns -1 and ALooper_pollAll returns -4 on basic usage I am trying to write an android app which uses the Java SDK for the GUI, and the NDK to draw things and read the Linear Acceleration sensor (based of the accelerometer but does not include gravity).  Basically, I want to know when the device is being shaken and my app is active.
I am using ASensorEventQueue_hasEvents and ALooper_pollAll in a fairly basic manner, I think, but they return -1 and -4 respectively.  These are errors, but I have no clue what they mean or what I could be doing wrong.  Any help would be welcome, thanks!  Here are some code snips:
To start listening for data from the linear acceleration sensor, I did:
//sensorManager = ASensorManager_getInstance();
sensorManager = ASensorManager_getInstanceForPackage(mypackage);
sensor = ASensorManager_getDefaultSensor(sensorManager, ASENSOR_TYPE_LINEAR_ACCELERATION);
if (sensor == nullptr) {
    return env->NewStringUTF("Linear accelerometer is not present");
}

looper = ALooper_prepare(0);
if (looper == nullptr) {
    return env->NewStringUTF("Could not get looper.");
}

eventQueue = ASensorManager_createEventQueue(sensorManager, looper, EVENT_TYPE_LINEAR_ACCELEROMETER, nullptr, nullptr);
if (eventQueue == nullptr) {
    return env->NewStringUTF("Could not create event queue for sensor");
}

//ASensorEventQueue_disableSensor(eventQueue, sensor);
int minDelay = ASensor_getMinDelay(sensor);
minDelay = std::max(minDelay, MAX_EVENT_REPORT_TIME);

int rc = ASensorEventQueue_registerSensor(eventQueue, sensor, minDelay, minDelay);
rc = ASensorEventQueue_setEventRate(eventQueue, sensor, minDelay);
return env->NewStringUTF("");

And my drawing loop looks like:
    int rc = ASensorEventQueue_enableSensor(eventQueue, sensor);
    std::vector<std::string> results;
    while (!stopDrawing) {
        int event = 0;
        void *data = nullptr;
        int rc;
        rc = ASensorEventQueue_hasEvents(eventQueue); // testing
        rc = ALooper_pollAll(wait_timeout, nullptr, &event, &data);
        if (rc == ALOOPER_POLL_TIMEOUT) {
            waiting += wait_timeout;

            if (waiting > EVENT_LOOP_TIMEOUT) {
                // If no data has been received, we have been waiting for a while, so assume
                // the shaking has stopped
                ASensorEventQueue_disableSensor(eventQueue, sensor);
            }
        } else if (rc == ALOOPER_POLL_ERROR) {
             return env->NewStringUTF("A looper error occurred");
        } else if (rc >= 0 && event == EVENT_TYPE_LINEAR_ACCELEROMETER) {
            std::vector<ASensorEvent> events;
            events.resize(100);
            while (ASensorEventQueue_hasEvents(eventQueue) == 1) {
                ssize_t nbrEvents = ASensorEventQueue_getEvents(eventQueue, events.data(), events.size());
                if (nbrEvents < 0) {
                    // an error has occurred
                    return env->NewStringUTF("");
                }

                float x = 0;
                float y = 0;
                float z = 0;
                for (int i = 0; i < nbrEvents; i++) {
                    x += events[i].acceleration.x;
                    y += events[i].acceleration.y;
                    z += events[i].acceleration.z;
                }

                graphics.updateAcceleration(x, y, z);
            }
        }
        graphics.updateUniformBuffer();
        graphics.drawFrame();
    }

Note: the call to ASensorEventQueue_hasEvents right before ALooper_pollAll was just so that I could see what it was returning since the ALooper_pollAll call always returned an error.  When running it in the debugger, I see that hasEvents is returning -1 and pollAll is returning -4.  This is happening in SDK versions 24 and 26 (I haven't tried 27 and vulkan is not supported below 24).  Any ideas why?

A: I had the precise symptoms described here, and for me it turned out that I was preparing the looper on a different thread than I was polling on.


text:
Q: MATLAB GUI, how to extract words from Static Text in GUI? I'm using MATLAB GUI. In my project I've loaded a file and displayed the content in the Static Text but I want it to be a more readable version to display in the interface for users.
This is the content of the file:
!MLF!#

"*/test001.rec"

0 200000 sent-start -162.580292

200000 4500000 five -2768.522217

4500000 7900000 five -2114.920898

7900000 12300000 one -2661.298828

12300000 15800000 two -2209.799805

15800000 29800000 sent-end -6030.099609
.

Is there a way to extract words from the Static Text in the GUI, and then convert the "five five one two" to "5512"?
This is my current coding:
data1 = importdata('C:\Users\User\Desktop\bin.win32\recout.mlf','')
set(handles.txtMsg, 'Max', 2);
set(handles.txtMsg,'String',data1)

%capturedString = get(handles.txtMsg,'String');
%capturedString = strjoin(captureString')

capturedString = 'nine one';
%StaticTextInString = regexprep(captureString,'[^\w'']','')

WordsToDigit=find(not(cellfun('isempty',strfind({'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'},capturedString)))) - 1;

set(handles.txtMsg,'String',WordsToDigit);'

Let's assume capturedString = 'nine one' first,
If I let the capturedString = 'nine', then WordsToDigit = '9'. However, if there is more than one word such as the one above: "nine one", then the outcome would be "Empty matrix: 1-by-0".
Is that possible to detect multiple sub-string in a string?
For example, capturedString = "dasd 312 nine wqej seven 98w one", WordsToDigit = '971'.

A: First, get Static Text from the GUI in to the string. For example, if you have access to the handles structure:
StaticTextInString = get(handles.yourstatictext,'String');

Afterwards, if you have only digits in the form of words, you can get the digit number using the following function:
find(not(cellfun('isempty',strfind({'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'},StaticTextInString ))))-1

For example for StaticTextInString = 'five' the previous command return 5.
The extension for the multiple words:
capturedString = 'dasd 312 nine wqej seven 98w one'
words = strread(capturedString,'%s','delimiter',' ');
digits = {'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'};
WordsToDigit = 0;
j = 1;
for i = 1:size(words)
    if sum(ismember(digits, words(i)))==1
        newdigit = find(not(cellfun('isempty',strfind({'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'}, char(words(i)) ))))-1;
        WordsToDigit = WordsToDigit*10 + newdigit;
        j=j+1;
    end
end

Results with WordsToDigit  = 971


text:
Q: Double Click and Run a Perl Program on a Mac I can run a Perl program from the terminal but I would like to run a program by double clicking it on the desktop.
I've tried using Platypus to run the program but the program requires user input and Platypus can't run any program that requires user input. I have right clicked the file and went into Get Info to try to change the program the file opens with. I've also tried to run the command chmod a-x "filename" to get the program to run when I double click it but I've had no luck with that either.
Does anyone know how this can be done?

A: Your permissions are wrong; you need to set the file to have +x (execute permission), not -x. Try
chmod +x program

Once you give it an execute bit, MacOS should give it an icon like this

Then double-clicking it will open and run the script in your default Terminal app. (Usually Terminal.app, but you could also use something like iTerm.)


text:
Q: How to combine 2 bitmaps via color mask? I want to use 3 bitmaps to create 1 resulting bitmap. The first will be the background. The second shall be drawn on top of the first with the help of a mask.
The images are loaded into Bitmap/BitmapData objects.
Example:
(red-green image is the mask, red is the visible part)
  back      mask    source    result

So how can I do that? What drawing function do I use in ActionScript-3?
Thanks for any help!
Edit:
(my first working solution, works only with pure red, green or blue)
var back: BitmapData = // load the back image
var mask: BitmapData = // load the mask image
var source:BitmapData = // load the source image (32-bit)
var result:BitmapData = back.clone();

// clone source because it will be modified in next step
var source2: BitmapData = source.clone();

// red of the mask becomes the alpha channel of source2
source2.copyChannel(mask, new Rectangle(0, 0, mask.width, mask.height), new Point(0, 0), BitmapDataChannel.RED, BitmapDataChannel.ALPHA);

// draw source2 to result
result.draw(source2);

(Is there a more efficient way? In this solution I have to clone source in order to keep original source bitmap intact.)

A: I don't know if it's the best way (performance and logic), but you can try:
var background:BitmapData = new Background();
var bmd1:BitmapData = new Mask();
var bmd2:BitmapData = new SourceImage();

var bmDiff:Bitmap = new Bitmap(mergeMaskAndBackground(bmd2, background, bmd1));
addChild(bmDiff);

function mergeMaskAndBackground(src:BitmapData, background:BitmapData, msk:BitmapData):BitmapData
{
     var diffBmpData:BitmapData = BitmapData(src.compare(msk));
     diffBmpData.floodFill(0, 0, BitmapDataChannel.RED);

     diffBmpData.draw(background, new Matrix(), new ColorTransform(), BlendMode.OVERLAY, background.rect, true);

     return diffBmpData;
}


text:
Q: How to populate a local URL in razor syntax? I have a local URL I am passing to a view via the ViewBag that comes from the referrer URL property of the Request object:
var returnUrl = Request.UrlReferrer.PathAndQuery;
if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
{
    ViewBag.ReturnUrl = returnUrl;
}
else
{
    ViewBag.ReturnUrl = "/DefaultPath";
}

In the Javascript of a function called on the viewI want to reference this URL to call back to the referring page. How would I write the razor syntax to properly format the URL to use in a window.location redirect?

A: The following mixed razor/javascript function solved my issue:
function referral_url_redirect() {
    var url = "@Url.Content(Convert.ToString(ViewBag.ReturnUrl))";
    if (url !== "null") {
        window.location = url;
    }
}


text:
Q: "Choose a password [that is] at least 6 characters long" - should I include "that is"? I am not a native English speaker. But I would like to know if the following sentence is correct?
"Choose a password at least 6 characters long."
Or should it be something like "Choose a password that is at least 6 characters long."?

A: You second sentence is correct,  or
Choose a password of at least 6 characters.

A: If a sentence is repeated often enough, it can be understood if a few words are left out. For example, did you understand the sentence? I'm sure you did.
The sentence is abridged: shortened by condensing. This doesn't mean removing critical elements of a sentence; they are all there.
Abridging does not make the sentence wrong. If it is easily understood, which is the purpose of communication, then it is fine.


text:
Q: Compute the contour integral $∫_{|z|=1} \frac{e^{i(1+z)}}{z^{10}}dz$ Compute the contour integral $$∫_{|z|=1} \frac{e^{i(1+z)}}{z^{10}}dz$$
I am stuck at solving the integral.
I know there is a singularity at z=0 and therefore we cannot apply the Cauchy Theorem directly.
I used the parametrization $z=e^{it}$ and $dz=ie^{it}$ where $R=1$.
However my integration resulted into a mess and i cannot seem to reach the final answer.

A: By Cauchy integral formula, we have that if $f(z)$ is holomorphic inside $\gamma$ and $a$ is inside $\gamma$, then
$$f^{(n)}(a) = \dfrac{n!}{(2 \pi i)}\int_{\gamma} \dfrac{f(z)}{(z-a)^{n+1}} dz$$
In our case, $f(z) = \exp(i) \exp(iz)$, $n = 9$, $a = 0$ and $\gamma$ is the contour $\vert z \vert = 1$.
Also, recall that $$\dfrac{d^n (\exp(az))}{dz^n} = a^n \exp(az)$$
Now you should be able to get your answer.


text:
Q: No deselect event for tagfield? Can somebody explain why there's only beforedeselect event but not "deselect" or "afterdeselect"?
Is there a way to get around this limitation? I need to execute code everytime an item is deselected.
Thanks.

A: TagField extends from Combobox.
Inside the Ext.form.field.ComboBox listeners are added to the selectionModel.
These include only beforeselect and beforedeselect, but not select.
The beforedeselect is fired inside the onBeforeDeselect method.
If you want to add it you have to override onBindStore and createPicker.
The selectionModel is extended from Ext.selection.DataViewModel. You can find all events there.
Example (just wrote it down you have to complete it):
Ext.define('MyApp.overrides.form.field.ComboBox', {
    override: 'Ext.form.field.ComboBox',

    onBindStore: function() {
        this.callParent(arguments);
        const me = this,
              picker = me.picker;

        if (picker) {
            me.pickerSelectionModel.on({
                scope: me,
                deselect: me.onDeselect,
                afterdeselect: me.onAfterDeselect
            });
        }
    },

    onDeselect: Ext.emptyFn,
    onAfterDeselect: Ext.emptyFn
});


text:
Q: WPF Toolkit Pie Chart Fill Values I Fill my Pie Chart with Data (form observablehas -> dict) but everytime the chart gets new data, the pie fades out and fades in. I want the pie slices to change like here:
http://silverlight.net/content/samples/sl2/toolkitcontrolsamples/run/default.html
if you choose "Pie Series" and then look at "dynamic data items".

A: When you get new data, you should add them to the ObservableCollection without clearing the ObservableCollection first.
I assume you either overwrite your ObservableCollection or you clear it before adding the new data.


text:
Q: Matching aws ami and availability zone on terraform When I create the VPC, I create a subnet in every availability zone.
Then, when I create my application, I want to input the ami and the type of instance (e.g. t3a.nano).
I want to avoid getting this error:

Error: Error launching source instance: Unsupported: Your requested
  instance type (a1.medium) is not supported in your requested
  Availability Zone (us-west-2b). Please retry your request by not
  specifying an Availability Zone or choosing us-west-2a, us-west-2c.

I am looking for a terraform module that can tell me if I can create my instance on this subnet given my ami and instance type.
I didn't find the terraform module one so I created my own.
It is doing what I want but I wonder if there is a better way.
I put my code here.
https://gitlab.com/korrident/terraform_calculate_ami_by_availability_zone
Quickly, I just use a  data "external" to call a bash
data "external" "subnet_available_for_ami" {
  count = "${length(var.subnets_id)}"

  program = ["bash", "${path.module}/check_subnet_ami.bash"]

  query = {
    ami     = "${data.aws_ami.latest_ami.id}"
    type    = "${var.instance_type}"
    subnet  = "${var.subnets_id[count.index]}"
    region  = "${var.aws_region}"
    profile = "${var.aws_profile}"
  }
}

This script will call AWS CLI with a dry-run
aws --region=${REGION} ec2 run-instances \
--instance-type ${INSTANCE_TYPE} \
--image-id ${AMI} \
--subnet-id ${SUBNET_ID} \
--profile ${PROFILE} \
--dry-run

And in the end I filter the results to return a clean subnet list
locals {
  uniq_answers = "${distinct(data.external.subnet_available_for_ami.*.result)}"

  uniq_answers_filtered = [
    for a in local.uniq_answers :
    a if length(a) != 0
  ]

  uniq_subnet_filtered = [
    for a in local.uniq_answers_filtered :
    a.subnet
  ]
}

Note that in the same script I also use the component aws_ami.
data "aws_ami" "latest_ami" {

Ideally, I would like this component to return me an ami available on my subnets.
There is no error, it works fine but is minimal.
If nothing is found, the calling module will deal with it.
The most problematic case is when there is only one result (I want my instances to be on multiple availability zones, not just one).
Has anyone found a better design?


text:
Q: Ruby On Rails Pundit Gem Authorizing Dashboard How would I provide pundit authorization for a dashboard controller which provides data from various models?
My DashboardsController looks like this:
class DashboardsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_user
  before_action :set_business
  after_action :verify_authorized

  def index

  end

  private

  def set_user
    @user = current_user
  end
  def set_business
    @business = current_user.business
  end

end

How would I authorize for both @user and @business within my DashboardsPolicy?

A: Pundit expects a current user and a model object to be passed to it. In this case I think what you would want is a DashboardsPolicy class, and you would authorize it like:
  def index
    authorize(@business)
  end

From the README:

Pundit will call the current_user method to retrieve what to send into
  this argument
The authorize method automatically infers that Post will have a
  matching PostPolicy class, and instantiates this class, handing in the
  current user and the given record

There is also a specific section in the README regarding headless policies that uses the Dashboard as the example action: https://github.com/varvet/pundit#headless-policies
You can also create a plain ruby object that takes two entities and use that as your object to authorize:
class UserBusiness
  def initialize(user, business)
  end

  ...other methods here
end

@model = UserBusiness.new(user, business)
authorize(@model)

A: I would argue that trying to get access to a dashboard is not a policy based on a resource named dashboard, but simply a special method in the business policy.
Therefore, I would add this to the BusinessPolicy as a method dashboard.
# in your controller
authorize @business, :dashboard?

# and the business_policy
class BusinessPolicy < ApplicationPolicy
  def dashboard?
    # condition depending on a `user` (current_user) and a record (business)
    user.admin? || user.business == record
  end
end

Or it might be even simpler. If someone is allowed to see the dashboard when she is allowed to show the business, then just re-use BusinessPolicy#show? in your controller:
authorize @business, show?


text:
Q: Android Problems with Widget and Multiple Pending Intents I have a widget I am working on that controls a media player service.  I have 4 buttons on my widget:

*

*Previous

*Play/Pause

*Stop

*Forward

The four buttons are assigned a pending intent which sends a Broadcast to the player service with the required action contained in it as an extra.
The problem I am having is that when I assign the pending intents to the buttons as below, they all seem to have the same broadcast value.  For example, with the code below all 4 buttons seem to send Globals.PlaybackActions.SKIP_FORWARD.  However, if I comment out the code that assigns the pending intents except for the "Play" button then pressing "Play" broadcasts the correct value.
Is there something I'm not aware of with using multiple pending intents as broadcasts on a widget or have I made a silly mistake in my code that I cannot spot?  Or secret option C?
I'm hopelessly lost and confused and would be very grateful for any help.  Thanks.
    public class PlayerWidget extends AppWidgetProvider {

        private boolean serviceIsPlaying = false;

        private PendingIntent pendingIntentPrev = null;
        private PendingIntent pendingIntentNext = null;
        private PendingIntent pendingIntentStop = null;
        private PendingIntent pendingIntentPlay = null;

        public void onReceive(Context context, Intent intent) {
            if (!intent.getAction().equals(Globals.BROADCAST_WIDGET_UPDATE)) {
                return;
            }

            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            ComponentName thisAppWidget = new ComponentName(context.getPackageName(), PlayerWidget.class.getName());
            int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget);

            this.updateViews(context, appWidgetManager, appWidgetIds);
        }

        private void updateViews(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){
            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_player);

            this.setClickIntents(context);

            if (this.serviceIsPlaying) {
                remoteViews.setImageViewResource(R.id.btnPlay, R.drawable.ic_action_pause);
                }
            else {
                remoteViews.setImageViewResource(R.id.btnPlay, R.drawable.ic_action_play);
            }

            remoteViews.setTextViewText(R.id.txtArtistName, currentTrack.getArtistName());
            remoteViews.setTextViewText(R.id.txtSongName, currentTrack.getSongTitle());
            remoteViews.setTextViewText(R.id.txtAlbumName, currentTrack.getAlbumName());
            remoteViews.setImageViewBitmap(R.id.imgAlbumArt, BitmapFactory.decodeFile(currentTrack.getAlbumArtPath()));

            remoteViews.setOnClickPendingIntent(R.id.btnPrev, pendingIntentPrev);
            remoteViews.setOnClickPendingIntent(R.id.btnNext, pendingIntentNext);
            remoteViews.setOnClickPendingIntent(R.id.btnStop, pendingIntentStop);
            remoteViews.setOnClickPendingIntent(R.id.btnPlay, pendingIntentPlay);

            appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
        }

        private void setClickIntents(Context context) {
            Intent intentPrev = new Intent(Globals.BROADCAST_PLAYBACK_ACTION);
            Intent intentNext = new Intent(Globals.BROADCAST_PLAYBACK_ACTION);
            Intent intentStop = new Intent(Globals.BROADCAST_PLAYBACK_ACTION);
            Intent intentPlay = new Intent(Globals.BROADCAST_PLAYBACK_ACTION);

            intentPrev.putExtra(Globals.EXTRA_PLAYBACK_ACTION, Globals.PlaybackActions.SKIP_BACKWARD);
            intentNext.putExtra(Globals.EXTRA_PLAYBACK_ACTION, Globals.PlaybackActions.SKIP_FORWARD);
            intentStop.putExtra(Globals.EXTRA_PLAYBACK_ACTION, Globals.PlaybackActions.STOP);

            if (this.serviceIsPlaying) {
                intentPlay.putExtra(Globals.EXTRA_PLAYBACK_ACTION, Globals.PlaybackActions.PAUSE);
            }
            else {
                intentPlay.putExtra(Globals.EXTRA_PLAYBACK_ACTION, Globals.PlaybackActions.PLAY);
            }

            pendingIntentPrev = PendingIntent.getBroadcast(context, 0, intentPrev, 0);
            pendingIntentNext = PendingIntent.getBroadcast(context, 0, intentNext, 0);
            pendingIntentStop = PendingIntent.getBroadcast(context, 0, intentStop, 0);
            pendingIntentPlay = PendingIntent.getBroadcast(context, 0, intentPlay, 0);
        }
    }

A: I think the problem is a second parameter in PendingIntent.getBroadcast() method. The second parameter is requestCode and it should be different for all 4 PendingIntent-s you are using.For example:
pendingIntentPrev = PendingIntent.getBroadcast(context, 0, intentPrev, 0);
pendingIntentNext = PendingIntent.getBroadcast(context, 1, intentNext, 0);
pendingIntentStop = PendingIntent.getBroadcast(context, 2, intentStop, 0);
pendingIntentPlay = PendingIntent.getBroadcast(context, 3, intentPlay, 0);

I have the same problem few days ago and this helped me. Hope it will help you too.


text:
Q: How to make Postman show CSRF token from get request using postman interceptor I'm having specific problem that I would like to find solution to. I'm working with my spring security and I should use Postman Interceptor to retrieve X-CSRF-TOKEN in Cookies section. I installed postman interceptor, and this is my spring security code with enabled csrf
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/", "index", "/css/*", "/js/*").permitAll()
                .antMatchers("/api/**").hasRole(STUDENT.name())
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();
    }

Now I'm not getting any cookies beside some SESSIONID and I've not idea how I should set up interceptor on this postman that will retrieve me cookies after enabling postmang interceptor, so if you could be kind and lead me? I've been struggling with this for days, and I also tried few approaches from here and ask on different groups, but no luck. Thanks in advance. Also I have user with pw for basic auth if needed and this is what I only get from postman https://prnt.sc/74GGlfA4TYYN

A: In my case I usually configure Spring Security to use a CookieCsrfTokenRepository, like so:
http.csrf(csrf -> csrf
    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnly(false)
);

And in my Postman requests, I add this script in the Tests tab.
var xsrfCookie = postman.getResponseCookie("XSRF-TOKEN");
pm.environment.set("xsrf-token", decodeURIComponent(pm.cookies.get("XSRF-TOKEN")))

In the Headers section of your request in Postman, you should have a header like this:

Key
Value

X-XSRF-TOKEN
{{xsrf-token}}

With this setup, Postman will retrieve the Cookie with the CSRF token returned from your backend and add it as an environment variable so you can use it in the next requests.


text:
Q: How to create notifications that will notify person in the right time even if app is closed I am making an app where people will type their jobs and tasks for that day, and then throught the day app will notify them. What should I use. Should I use something like JobScheduler or something like Foreground service. Please help

A: You can approach to your issue at least on two ways.
First way is to implement AlarmManager which is going to start service which is going to check is new message arrived and if it is you can rise notification. But some limitations of this approach are that you have to setup AlaramManager to trigger services once a while for example each 15 min and if in meanwhile message arrives user will not be notified in realtime.
Second approach is to use some third part client like FCM which is free but with limitation to 4kb per message(notification message) which is actualy pretty enough for notification.
AlarmManager Doc : https://developer.android.com/reference/android/app/AlarmManager
FCM Doc : https://firebase.google.com/docs/cloud-messaging/android/client


text:
Q: How do we find the canonical ensemble density matrix for two spins? A compound system is constructed by two coupling spins, and the Hamiltonian is

$$
\hat H = -J\hat\sigma_1·\hat\sigma_2 - \mu_\mathbf{B}\big( \hat\sigma_{1z}+\hat\sigma_{2z} \big)B.
$$

So, how can we obtain the canonical ensemble density matrix, i.e. $\hat\rho = Z^{-1}\exp(-\beta\hat H)$? Can anyone give me some hints or references?
$$EDIT: Question two$$
Suppose that the first spin represents system while the other represents environment. Their Hamiltonian are $\hat H_1 =-\mu_\mathbf{B} \hat\sigma_{1z}B$ and $\hat H_2 =-\mu_\mathbf{B} \hat\sigma_{2z}B$. Then $\hat H_{12} = -J\hat\sigma_1·\hat\sigma_2$ represents the interaction between system and env. My question is that what's the reduced density matrix of the first spin?

A: There are four state kets $|\uparrow_1\uparrow_2\rangle,|\uparrow_1\downarrow_2\rangle,|\downarrow_1\uparrow_2\rangle,|\downarrow_1\downarrow_2\rangle$ representing four possible configuration of the two spins, the eigenvectors of the Hamiltonian is the linear combination of them. There will be four eigenvectors and four eigenenergy.
You can also obtain the eigen-energy in the matrix way. Just write out the matrix form of the Hamiltonian, note that $\sigma_1\cdot\sigma_2=\sigma_{1x}\sigma_{2x}+\sigma_{1y}\sigma_{2y}+\sigma_{1z}\sigma_{2z}$ should be understood as the direct product of matrix. Similarly, $\mu B \sigma_{1z}$ should be understand as $\sigma_{1z}\otimes I_2$.
Once you get the eigenvalue, your matrix form of $\hat \rho$ is a diagonal matrix $[e^{-\beta E_1}/Z,e^{-\beta E_2}/Z,e^{-\beta E_3}/Z,e^{-\beta E_4}/Z]$
Regarding your second question
Once you obtained the eigenvalue $E_1,E_2,\cdots$ and corresponding eigenvector $|1\rangle,|2\rangle\cdots$, your density matrix operator is written as $\hat\rho=e^{-\beta E_1}/Z |1\rangle\langle1|+e^{-\beta E_2}/Z |2\rangle\langle2|+\cdots$
Expand $|1\rangle,|2\rangle\cdots$ using the four vector $|\uparrow_1\uparrow_2\rangle,|\uparrow_1\downarrow_2\rangle,|\downarrow_1\uparrow_2\rangle,|\downarrow_1\downarrow_2\rangle$, you can rewrite your density matrix $\hat\rho$. The reduced density matrix $\hat\rho_r=\mathrm{Tr}_2(\hat\rho)=\langle\uparrow_2|\hat\rho|\uparrow_2\rangle+\langle\downarrow_2|\hat\rho|\downarrow_2\rangle$