text:
Q: Test Driven Development is the way to go. But how should it be done? A number of developers are designing their applications using Test Driven Development (TDD) but I would like to know at which stage should I incorporate TDD into my projects? Should I first design my classes, do some unit tests and determine what methods are needed or design methods first and then do some unit tests after?
What is the best way to go about this?

A: The mantra for test driven design:

*

*create the test.

*compile test (and verify that it fails)

*write the interface

*compile test (it should compile now)

*run test (it should fail now)

*write the code

*compile/run test (it should do both now)

Repeat for each item.

A: I'm very skeptical about writing unit tests before implementation. Maybe it would be efficient if you had a good idea about the exact design about the classes and methods required but generally at the start of a new project you don't.
My preferred approach is to acknowledge that the start of a new project can be a bit of organised chaos. One part of the design process is writing code to validate certain ideas or to find the best way. A lot of time the code hits a dead end and gets thrown away and any unit tests written for it would have been a waste of time.
Don't get me wrong I'm all for well designed software and at a certain point it's essential that the organised chaos morphes into a well understood design. At that point the class structure and UML diagrams start to solidify. This is the point TDD becomes important to me. Every class should be able to be tested in isolation. If the design is good with the right degree of decoupling that is easy to achieve usually with a sprinkling of mock objects around the place. If the design is bad testing becomes a real nightmare and consequently gets ignored.
At the end of the day it's high quality productive code that you're after. Unit tests are one of the best tools to help achieve that but they shouldn't take on a life of their own and become more important than the code they are testing which you sometimes get the feeling of from the TDD mantra.

A: Start small
a) The next time you add a method to a Utility class, write the tests first for the method.  Methods that do string handerling are a good place to start, as they tend to have lot of bugs, but are don't need complex dataset to test them.
b) Then once you get confidant with writing unit tests, move on the classes that don't touch UI and don't talk directly or indirectly to the database.
c) You have then got to decide if you will design your application to make unit testing easier.  E.g

*

*it is hard to test UI code so look at
MVP etc,

*it is head to test code
that access the database, so separate
your logic into method that don't need
to access the database to run.

a) and b) has a big payback without having to change how you design the overall system.  You have to consider if c) is worth the cost....  (I think it is, but a lot of people don't and often you can't control the overall system design.)

A: TDD is a coding and design-in-the-small technique.  It is not a big-picture envisioning technique.  If you starting to write an application, you want to do some storyboards, or wireframes, or even some simple sketches.  You should have an idea about the larger-scale design i.e. the classes and relationships in your system.  Before you get to the point where you'd start to do interaction design (e.g. methods and arguments) you start doing TDD.
The wireframes you have done will give you an idea of how the system should appear.  The large scale design will give you an idea of what classes to create.  However, none of these models should be considered correct or permanent.  As you write tests, you'll find better design ideas that will change your high-level design, and even your wireframe design.

A: The point of it being test driven is that the tests drive the design as well as the implementation.
In some cases that's not appropriate - it may be blatantly obvious what the design should look like, especially if it's implementing an existing interface (or some similarly restricted choice) but when you've got a large "design space" TDD encourages you to writes tests demonstrating how you want to be able to use the class, rather than starting off with you how you think you want to implement it.
Generally if something is easy to test, it will be easy to use.

A: Ideally you will start to apply TDD when you begin coding. Think about your design first, you can draw diagrams on paper ; no need to use CASE tool, just envision the main classes and their interactions, pick one, write a first simple test, write the code to make it pass, write another test, make it pass, refactor ...
If your process mandates documenting and reviewing the design before the coding stage, then you cannot follow TDD and let your design emerge. You can however make your design first, and then do the implementation test-first. You'll get unit-tests as if you applied TDD, but still applying your process.
Keep your design as hi-level as possible, so that you can let the low-level details of the design emerge.

A: Please look at
http://en.wikipedia.org/wiki/Test-driven_development
They have stated a high level tasks

A: TDD ensures that developers give equal importance to test cases as compared to their business logic. I followed it in my project and i could see the advantages: Since i started with writing my test cases first, i ensured that my test cases handle all the possible coverages of a business logic, thereby catching/reducing the number of bugs. Some times its not practical since it requires enough time to write these test cases.
The bottom line is you need to unit test your code really well.So either you start with implementation and then ensure that there are enough test cases for all the scenarios (Most people dont hence this practice has emerged.) or write the test methods do a dry run and then write your implementation. Your implementation is said to be complete only when all your testcases pass successfully.

A: You should listen to stack overflow podcast 41 where they talk about TTD. It's hard to say everybody is using TDD and it would be take a lot of time and resources to have a high code coverage percentage. Unit testing could effectively double the development time if you write tests for all of your code.
One of the points from the podcast is that your time and resources could be better used doing other tasks such as usability and new features.


text:
Q: little information needed in PHP i am working on a project which is airways ticketing.
i am able to display the final ticket to the user but how can i give user the ability to print  it when he/she clicks on print button.
please help..
    <title>Untitled Document</title>

<?PHP
mysql_connect("127.0.0.1","root","");
mysql_select_db("cmc");
$id=$_REQUEST['id'];
$r=mysql_query("select * from manifest where transid=".$id);
$d=mysql_fetch_assoc($r);
?>

HORIZON AIRWAYS PASSENGER TICKET

PNR NUMBER:
<?php echo $d["pnrno."]; ?>

 PASSENGER'S NAME:
<?php echo $d["name"]; ?>

DATE OF ISSUE:
<?PHP
ini_set('date.timezone','asia/calcutta');
echo date("d/m/y"); ?>

TIME OF ISSUE:
<?PHP
echo date("h/i/s"); ?>

DATE OF JOURNEY:
<?php echo $d["day"]."-".$d["month"]."-".$d["year"]; ?>

NOT TRANSFERRABLE

PASSENGER NAME:
<?php echo $d["name"]; ?>

SECTOR:
<?php echo $d["sector"]; ?>

FLIGHT #
CLASS
DATE
DEP. TIME
ARR. TIME
STATUS

<?php echo $d["flight_no."]; ?>
<?php echo $d["class"]; ?>
<?php echo $d["name"]; ?>
<?php echo $d["departure"]; ?>
<?php echo $d["arrival"]; ?>
<?php echo "confirm"; ?>

<form name="form1" method="POST">
<input type="submit" value="Print" name="submit"/>
</form>

A: Printing has to be done on the client side, not the server side.  This shouldn't be a form (I would actually make it a link).  The simplest method:
<input type="submit" value="Print" onclick="print(); return false;"/>

A: You can trigger the print event bij using the javascript function: window.print().
Example:
print page

TIP!
Use a print CSS to tell the browser what to print! That way the user doesn't waste paper ;)
Example including a print CSS stylesheet:

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to describe the common boundaries between regions in a infinite Sudoku? This relates to the answer to a question "Who wins two player sudoku?" and this awesome blog.
A Sudoku can be $N \times N$ where $\sqrt{N}$ is a natural number because $N \times N / \sqrt{N} \times \sqrt{N} = N$, the number of regions in the Sudoku.
It seems more computationally efficient to describe it as $(m^2)^2 = m^2\;(m^2) = m \times m\: (m \times m)$ because the square root does not have to be derived, and more notationally efficient because the regions are described.
$m \times m\; (m \times m)$ means "an $m$ by $m$ matrix of $m$ by $m$ matrices".
$m^2\;(m^2)$ means "$m$ squared $m$ squared", a colloquial description of the geometry.
Coordinates (cells) are $\left[-\frac{m}{2},\ldots, \frac{m}{2}\right]$ for even $m$ and $\left[-\frac{m-1}{2},\ldots, \frac{m-1}{2}\right]$ for odd $m$.
Using these methods, I understand the boundaries between regions in any finite Sudoku.

*

*What I don't understand is the common boundaries between regions in an infinite Sudoku.

I find it helpful to think of the surface of the Sudoku as a torus, so the left side connects to the right side, and the top to the bottom, which does not violate the constraints but makes every regional boundary common.
-----------
I'm also interested in how to describe an infinite Sudoku using cardinal numbers.
Using the above notation, $\infty = \aleph_0$ is the set of all natural numbers, I'd do it:
$$
(\infty^2)^2 = \infty\times\infty\;(\infty\times\infty)
$$
I feel like $\sqrt{\infty}$ is problematic because it seems like $\sqrt{\aleph_0} = \aleph_0$
It also strikes me while the regions in infinite Sudoku can be $\aleph_0$, a Sudoku comprised of an such infinite regions is probably uncountable.
Since I am only confident in my understanding of $\aleph_0$, spending most of my time on finite sets, is the Sudoku comprised of an infinite set of regions with an infinite number of cells an $\Omega$?
There's also the question of $(\infty^n)^n$ where $n = \aleph_0$

A: Thanks for your kind words about my blog.
In the general-size square Sudoku board, you have an $\kappa\times\kappa$ array of $\kappa\times\kappa$ local blocks for some (possibly infinite) cardinal $\kappa$. Every location on the Sudokou board has an address $(\alpha,\beta)$ in its local block, and the local block itself has coordinates $(\gamma,\delta)$.  Thus, every location on the Sudoku board is specified by four coordinates:
 $$(\alpha,\beta,\gamma,\delta).$$
This is (local address, global block coordinates). The boundaries between the local boards play no meaningful role. Every row, column and local block has size $\kappa^2$.
On the $\mathbb{Z}$-Sudoku board, for example, which I considered on my blog, we have a $\mathbb{Z}\times\mathbb{Z}$ array of $\mathbb{Z}\times\mathbb{Z}$ local boards. For example, each local $\mathbb{Z}\times\mathbb{Z}$ block has its own origin and its own address $(2,17)$ and so on. One needn't imagine any "boundaries" between the sub-boards.

Asymmetric Sudoku is somewhat more general, since it works with rectangular sub-boards, which may not be square. Indeed, for any two cardinals $\kappa$ and $\lambda$, one may consider a $\lambda\times\kappa$ array of local boards with shape $\kappa\times\lambda$. It is interesting to consider even the extreme case of a $1\times\kappa$ array of $\kappa\times 1$ blocks. Note that the order of the coordinates must swap, in order that the size of the rows and columns is the same, and the same as the size of the local blocks, since the Sudoku conditions require these to form bijections with the set of labels. Think of a $6\times 6$ board as a $2\times 3$ array of $3\times 2$ matrices. In the general case, every location is specified by the coordinates $(\gamma,\delta)$ of the board, and the address  $(\alpha,\beta)$ within that local block, where now $\gamma,\beta<\lambda$ and $\delta,\alpha<\kappa$.
A Sudoku solution is a function $f:(\kappa\times\lambda)\times(\lambda\times\kappa)\to L$, where $L$ is the set of labels (of size $\lambda\times\kappa$) that obeys the three requirements:

*

*Every row is a bijection with $L$. So $f(\alpha,\beta,\gamma,\delta)$ is a bijection, if you fix $\delta<\kappa$ and $\beta<\lambda$.

*Every column is a bijection with $L$. So $f(\alpha,\beta,\gamma,\delta)$ is a bijection, if you fix $\gamma<\lambda$ and $\alpha<\kappa$.

*Every local board is a bijection with $L$. So $f(\alpha,\beta,\gamma,\delta)$ is a bijection, if you fix $\gamma<\lambda$ and $\delta<\kappa$.

Note that if $G$ is a group of size $\lambda$ and $H$ is a group of size $\kappa$, then we can use these groups as location coordinates, and define $f(h,g,g',h')=(gg',hh')$, taking $L=G\oplus H$ as the set of labels. This is a solution, because if you fix $g$ and $h'$, it is a bijection; and similarly if you fix $h$ and $g'$, or if you fix $g'$ and $h'$. So every assymmetric Sudoku board has a solution arising in this way. This answers a question asked by Gerhard in a comment on an earlier post.
Actually, this way of thinking leads one to a fourth Sudoku-like condition, namely, requiring that $f(\gamma,\delta,\alpha,\beta)$ is a bijection when you fix $\alpha$ and $\beta$, which is the collection of locations, one per local block, each with the same local coordinates in those blocks. For example, the labels appearing in all the locations with local address $(2,17)$, over all the local blocks, would have to be a bijection with $L$.
In the group example, this extra condition corresponds to fixing $g$ and $h$, and this shows that any Sudoku solution arising from groups will indeed obey the extra requirement. However, one can easily find Sudoku solutions not fulfilling the extra requirement, and so these solutions cannot arise from groups in the way I described (e.g. perhaps the operation that they define is not associative). One can also find infinite solutions without the extra requirement, since the argument on my blog shows that any finite position not yet violating the Sudoku rules extends to a full solution on a countably infinite board. So one could start with two labels violating the extra requirement and extend it.

A: In M-games, the elements of Sudoku carry weight $v$, and elements sharing a common boundary or vertex with exterior regions "influence" these regions $v/2$.
Infinite spaces $ℤ$ may be "split"  by arbitrarily assigning any cell coordinate 0; the $(c < 0 , 0 < c)$  disjoints will have the same cardinality:
$c < 0 > c$
In order to maintain the common boundaries, make the common boundaries 0.
$> 0$ is $[1,2,…]$ and $[…, -2, -1]$ is $< 0$
$c > 0 < c$  is the boundary
$[c > 0, .., c < 0]$
$[c_{-i} > 0, .., c_{-i} < 0] ,  [c_{i} > 0, .., c_{i} < 0]$
Now the sets expand infinitely inward—the center of regions can never be reached but connections are maintained.
-----------------
(i don't know if this breaks anything. naively, i feel like this is "twisting" the paradox and stowing it in the center to solve the problem of the common boundaries. i'm more of an engineer so I can't help thinking of infinity procedurally—how high i can count in how much time i have. i see coordinates as scalars because the elements have weight, and here there are 2n vectors for any n dimensions.  Each pair of opposite vectors points towards the other but can never intersect. My thought is they probably spiral toward infinity so I'm calling this spiral sudoku: "At the still point of the turning world, neither flesh nor fleshless; neither from nor towards; at the still point, there the dance is.";)
Spiral Sudoku can be expressed procedurally with an additional constraint that element expression $p_x$ must start in the greatest $c < 0$ or least $c > 0$, with the least unexpressed element $p > 0$ for any region, and all subsequent $p_x$ must share a cell boundary with a previous $p_x$
The toroidal surface is attractive because it reinforces the idea of "no center"—every region and vertex is the same until the initial $p_x$, and the regions themselves have to expressible center.
Where n is number of dimensions: $p_x \cap n$
Wherever that first $p_x$ is expressed becomes the center vertex of the sudoku.
This becomes a stacking game around a single vertex, or, because spaces can be virtual, players may "jump" across "hyperspace" to the closest uncolonized vertices to express new $p_x$
If new p must only share a vertex with $p_x$ sparser aggregations may be formed with empty spaces between $p_x$. Element weights $v$ may be balanced where $p_x$ can also be the greatest unexpressed $p < 0$.


text:
Q: Backup files in pre-folders of a certain size I want to backup my NAS on multiple DVD's. What i had in mind was a script what does the following:
-Create a folder for each DVD
-Copy the files and filestructure into the DVD folders
-Stop / goto next DVD folder when the first DVD folder is full
i.e. the trigger is 4 GByte (which calculates easy for the example)
I have a datasrouce with 10 gb of data., so this will be 3 DVD's. So the script first create three folders: DVD-1, DVD-2 and DVD-3. Next the copy will start to copy 4 GB to the DVD-1 folder. After that, the remaining files must come in DVD-2 and DVD-3.
As far as i know, rsync and cp doesn't bother about calculating this. I know it is an option to do this by using archives like zip, tar or gz but at first i want to try it with unpacked files.
Is all above an option with standard Linux bash commands or is it insane?

A: No, there isn't any standard tool that does this out of the box. But it's pretty simple to code up, and there are a few projects to do it:
https://unix.stackexchange.com/questions/18628/generating-sets-of-files-that-fit-on-a-given-media-size-for-tar-t


text:
Q: What's the difference between "what it's like to do sth" and "what is sth"? Today I was surfing in Reddit, and found a quote:

The saddest people always try their hardest to make people happy because they know what it's like to feel absolutely worthless and they don't want anyone else to feel like that. - Robin Williams

What I wondered was the clause in the sentence: "what it's like to feel worthless".  In English, we usually see a clause like what is a dog, in which the word what is the subjective pronoun of the sentence sth is a dog, but the clause mentioned above doesn't seem to be following this rule because it has a subject "it" in it.
I thought that what is probably a determiner for "it" — say, for example "what kind of dog is the biggest breed."— but I found there's a interrogative sentence like "What is it like to be a nurse", so my assumption of what as a determiner seems to be false.

A: Your confusion may stem from focusing on the wrong word in the sentence.  In both examples, "what" has essentially the same meaning or function.  It refers to "the identity, nature, or value of an object or matter" (see Webster).
In What is a dog, you are inquiring about the nature of a dog.  In ...know what it's like to... you are referring to the nature of whatever the subject is.
The real difference is inclusion of "like".  The meaning of like here is "similar to", although that meaning has to be taken loosely in this usage.
"What is it like to be an astronaut?" means "What is the experience of being an astronaut similar to?"  In other words, describe the experience of being an astronaut in terms of something similar that I might be familiar with and can relate to.
This comes into play when you want to talk about an experience, emotion, or something else that is intangible.  You can't define or describe it by pointing to it and saying, "It is that."  You can only describe it as being similar to something else.  It is the difference between, "What is sadness?" (i.e., dictionary definition of the word "sadness"), and "What is it like to feel sad?" (i.e., description of the sensation of experiencing sadness; what is experiencing sadness similar to?).
In your quote:

...they know what it's like to feel absolutely worthless...

"knowing what it's like" means they have had a similar experience and know how it feels (as opposed to simply having heard or read about it but not experienced it).

A: I interpret "what is it like" as being short for "what does it feel like".  The phrase is about a feeling, or the emotional experience of doing something.  (For example, the emotions experienced by a nurse doing her job.)
Kenny Chesney's song, "How Forever Feels" has examples of "what does something feel like".  (Unfortunately for an English Language Learner, Chesney takes poetic license with the grammar of the song, and the song is written in the Southern dialect of American English.)


text:
Q: How can I create a stream for DockerDotNet BuildImageFromDockerfile method? I am trying to build a Docker image using the DockerDotNet library:
  public Task<Stream> BuildImageFromDockerfileAsync(Stream contents, BuildImageFromDockerfileParameters parameters, CancellationToken cancellationToken)
  {
        if (contents == null)
        {
            throw new ArgumentNullException("contents");
        }

        if (parameters == null)
        {
            throw new ArgumentNullException("parameters");
        }

        BinaryRequestContent data = new BinaryRequestContent(contents, "application/tar");
        const string path = "build";
        IQueryString queryParameters = new QueryString<BuildImageFromDockerfileParameters>(parameters);
        return this.Client.MakeRequestForStreamAsync(this.Client.NoErrorHandlers, HttpMethod.Post, path, queryParameters, data, cancellationToken);
    }

However, I am getting a 500 return from the server, with no error message. The Docker api docs state that:
The input stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz.
I have copied my code below, I would be really grateful if anyone could point out any obvious mistakes. The tar archive is a single folder containing a Dockerfile, created with 7zip.
       var parameters = new BuildImageFromDockerfileParameters
        {
            RepositoryTagName = "test-image",
            RemoveIntermediateContainers = true
        };

        using (var fileStream = new FileStream(@"C:\temp\Dockerfile.tar.gz",FileMode.Open))
        {
            await client.Miscellaneous.BuildImageFromDockerfileAsync(fileStream, parameters, new CancellationToken());
        }

Dockerfile:
#using ubuntu as having trouble with ssl on debian
FROM ubuntu:14.04

#install php
RUN apt-get update && apt-get install -y php5-cli

#copy crontab, php script and data files container
COPY my-crontab /
COPY getData.php /
COPY saveddata.xml /

#run crontab
RUN crontab /my-crontab
ENTRYPOINT cron -f


text:
Q: How to read hex values into integer with fstream (C++) I am trying to read a little-endian hex string from a binary file, and put that value into an integer to work with it. When I try to read, instead of getting a number I get ascii symbols. I've tried casts and atoi and nothing seems to work. What is the best way to use fstream to read a hex string into an integer from a file?
This is essentially my program:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(int argc, char* argv[]) {
    fstream input;
    fstream output;
    char cbuffer[4];
    char revbuffer[8];

    input.open(argv[1], fstream::binary | fstream::in);
    output.open("output.txt", ios::out | ios::app);
    input.seekg(16, input.beg);
    input.read(cbuffer, 4);

    cout << sizeof(revbuffer) << endl;
    cout << cbuffer[0] << cbuffer[1] << cbuffer[2] << cbuffer[3] << endl;
}

A: If it's an integer value stored in binary format, I guess it's either a int32_t or a uint32_t. Since you mention that the value is stored in little-endian byte order, I guess you want to make sure that the host running your program converts it (if it needs to). C++20 has std::endian. If that's not available to you, there are usually macros for detecting endianness at compiletime that you can use instead of the std::endian tests I've used. I've assumed that the value is a uint32_t below.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <type_traits> // std::endian

// little endian unsigned 32 bit integer to host byte order
inline uint32_t Le32toh(uint32_t le) {
    #if __cplusplus <= 201703L
    // run-time check
    static constexpr uint16_t endian = 1;
    if(*reinterpret_cast<const uint8_t*>(&endian)==1) return le;
    #else
    // compile-time check
    static_assert(std::endian::native == std::endian::little || std::endian::native == std::endian::big);
    if constexpr (std::endian::native == std::endian::little) return le;
    #endif

    const uint8_t* c=reinterpret_cast<const uint8_t*>(&le);
    return // little-to-big endian conversion
        (static_cast<uint32_t>(c[0])<<24) |
        (static_cast<uint32_t>(c[1])<<16) |
        (static_cast<uint32_t>(c[2])<<8) |
        (static_cast<uint32_t>(c[3]));

    return le;
}

int main(int argc, char* argv[]) {
    std::vector<std::string> args(argv+1, argv+argc);

    std::fstream output("output.txt", std::ios::out | std::ios::app);

    uint32_t cbuffer;

    for(const auto& file : args) {
        std::fstream input(file, std::fstream::binary | std::fstream::in);
        input.seekg(16, input.beg);
        // read directly into the varibles memory
        input.read(reinterpret_cast<char*>(&cbuffer), 4);
        // output the value unconverted
        std::cout << std::hex << cbuffer << "\n";
        // convert if needed
        cbuffer = Le32toh(cbuffer);
        // output the value converted
        std::cout << std::hex << cbuffer << "\n";
    }
}


text:
Q: How do I parameterize format strings used by StringContext? Let's say I have a line of code like this:
log.info(f"$name%-20s $amt%7.2f")

What I want is to make the 20 (the width of the name) something that itself can be parameterized.  How can I do that?
What if I also wanted to make the 7.2 width for amt also parameterized. Is that possible?
[Edit: I'm hoping to put things like 20 and 7.2 in variables so that they are not hard-coded in the format string.]
I've tried using StringContext directly, but it seems I don't understand whatever macro expansion is happening in:
StringContext(...).f(...)

A: Your were not far from the truth:
val amt= 1234.1234d
val name = "James"
println(f"|$name%20s $amt%7.2f|")

yields:
|               James 1234,12|
Regarding passing 20 and 7.2 as parameter: the template can be generated as:
val len = 20
val prec = 7.2
val template = s"$$name%${len}s $$amt%${prec}f"

that yields:
$name%20 $amt%7.2f
But string interpolation does not seem to be the solution as even desugared into StringContext, it is done at compile time, then
s"$template
yields $name%20s $amt%7.2f.
I think I had this working with another language

A: you can implement yours StringContext
note:  s"a=${a},b=${b}" it asStringContext("a=",",b=").s(a,b)
case class Format(t: String)

// this implement is not type safe in Compile time,
implicit class MyFormat(val sc: StringContext) {

  def myFormat(args: Any*) = {
    val partIter = sc.parts.iterator
    var stringFormatArgs = List.empty[Object]
    val sb = new StringBuilder(partIter.next())

    def impl(list: List[Any]): Unit = {
      list match {
        case (_: Format) :: tail                  =>
          throw new Exception("")
        case (any: Object) :: (format: Format) :: tail =>
          sb.append(partIter.next()).append(format.t).append(partIter.next())
          stringFormatArgs = any :: stringFormatArgs
          impl(tail)
        case (any: Any) :: tail                        =>
          sb.append(any.toString).append(partIter.next())
          impl(tail)
        case Nil                                       =>
      }
    }

    impl(args.toList)
    String.format(sb.toString(), stringFormatArgs.reverse: _*)
  }
}

// test
val amt = 1234.1234d
val name = "James"
val len = Format("20s")
val prec = Format("7.2f")

myFormat"$name%$len,$amt%$prec," //"               James,1234.12,"

A: You can do it in two parts.
val name = "Jan"
val nLen = -10  //name length

val amt = 1.1
val ff = 5.3  //float format

s"%${nLen}s".format(name) + s"%${ff}f".format(amt)
//res0: String = Jan       1.100

Or in a single pass.
s"%${nLen}s%${ff}f".format(name, amt)
//res1: String = Jan       1.100


text:
Q: Can I make Launcher icons dark/dim unless app is running (then in color)? To improve visibility of what Launcher-Applications I have running (instead of relying solely on that small right-facing triangle), is it possible to make Launcher-icons default to a black&white/dark/dim state? And then when a launcher-icon is clicked (or the super+# shortcut used) that icon would gain color and backlight signifying the app is running?
If the Launcher icon's app is not running, it is dimmed out. If the icon's app is running, it is showing in color and backlit.
I'd prefer an "inhouse" solution as opposed to having to install additional software, but I'm interested in hearing all options for if this is possible.

A: Give Ubuntu Tweak a try, I find the settings included improve the Unity launcher greatly (Including the back light option).
Here is the web page for download Ubuntu Tweak

A: Unfortunately you can't.
You can customize just a few standard options for unity launcher, as Unity and Compiz are using GConf to store their settings, and not a .css file like gnome-shell does.
The configuration data is saved under ~/.gconf, but modifications should only be made through the GConf daemon.
You can modify the Unity settings directly using gconf-editor and browsing to     /apps/compiz-1/plugins/unityshell/screen0/options.
You will notice that Unity responds to changes instantly, the same as CCSM.
If you want a command line tool to modify these settings, use gconftool-2. For example, to reduce the launcher icon size I can do:
gconftool-2 --set /apps/compiz-1/plugins/unityshell/screen0/options/icon_size --type int 32

A: Although you can't make them greyed out (unless there is a plugin I do not know about), you can make it so they only show the background (called the backlight) if they are open. This provides a similar function.
The easiest way to enable this is to install MyUnity, which is just a program that makes these tweaks more accessible:
sudo apt-get install myunity

Then open it up and on the launcher tab, you will see a dropdown for Backlights. Just set that to "Active icons On". You will instantly notice the change.
To do it from the gconf-editor, simply fire up the editor, navigate to /apps/compiz-1/plugins/unityshell/screen0/options/backlight_mode and set it to 1. 0 is the default.
The command to do it using gconftool-2 would be:
gconftool-2 --set /apps/compiz-1/plugins/unityshell/screen0/options/backlight_mode --type int 1

to set it back:
gconftool-2 --set /apps/compiz-1/plugins/unityshell/screen0/options/backlight_mode --type int 0

A: I just install the CompizConfig Settings Manager (CCSM). Open it, select Ubuntu Unity Plugin, go to the "Experimental" tab. Under backlight mode set "backlight toggles". On launch animation select "Pulse until running".


text:
Q: How can i update layout on kivy? I'm doing a YouTube converter. It's ok but when i download and convert i want to let user know that i'm working: how can i update my interface? I'm using kivy. I tried using a popup, i tried using various kind of loading bar. Now i'm trying to update text in a box in the main interface but nothing, it updates after conversion. Why?
Here's my code:
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.popup import Popup

from pydub import AudioSegment
from pytube import YouTube
import os
import time

class YouTube2mp3App(App):

    def build(self):

        self.mylayout = FloatLayout()
        mylabel = Label(text= "Benvenuto su YouTube2mp3!\nInserisci il link e premi converti", size_hint=(.8,.2),pos_hint={"x":.1, "y":.7}, font_size=20)
        self.txt = TextInput(hint_text="Incolla qui",size_hint=(.9,.1), pos_hint={"x":.05, "y":.4})
        self.pb = Label(text="0%", size_hint=(.9,.2), pos_hint={"x":.1, "y":.1}, font_size=20)
        #self.txt.bind(on_text_validate=self.convert)
        mybutton =Button(text="Nuovo/i video", on_press= self.clearText,size_hint=(.45,.1), pos_hint={"x":.5, "y":.3})
        mybutton2 =Button(text="Converti", on_press= self.convert,size_hint=(.45,.1), pos_hint={"x":.05, "y":.3})
        self.mylayout.add_widget(mylabel)
        self.mylayout.add_widget(self.txt)
        self.mylayout.add_widget(self.pb)
        self.mylayout.add_widget(mybutton)
        self.mylayout.add_widget(mybutton2)
        return self.mylayout

    def clearText(self, instance):
        #clear input
        self.txt.text = ''

    def convert(self, instance):
        try:

        #starting to convert using 3 methods
            self.pb.text="Preparazione... 10%"
            self.mylayout.add_widget(self.pb)
            ns=self.check_spazio(self.txt.text)

            self.pb.text="Conversione... 33%"
            self.mylayout.add_widget(self.pb)
            print(ns)
            links=self.list_of_links(ns)

            self.pb.text="Scaricamento... 80%"
            self.mylayout.add_widget(self.pb)
            print(links)

            self.Tube(links)

            self.pb.text="Fatto!... 100%"
            self.mylayout.add_widget(self.pb)
            content = Button(text='Chiudi', size_hint=(.3,.7))
            popup = Popup(title="Fatto!", content=content, auto_dismiss=False, size_hint=(.3,.2))

            content.bind(on_press=popup.dismiss)
            popup.open()
            self.pb.value="0%"
        except:
            content = Button(text='Chiudi', size_hint=(.3,.7))
            popup = Popup(title="Link non valido", content=content, auto_dismiss=False, size_hint=(.3,.2))
            content.bind(on_press=popup.dismiss)
            popup.open()

    def Tube(self, lista):
        #convert
        for text in lista:
            yt=YouTube(text)
            ys=yt.streams.get_audio_only()

            file=ys.download()
            ya=file[:-1]+"3"
            AudioSegment.from_file(file).export(ya, format="mp3")
            os.remove(file)

    def check_spazio(self, string):
        #check space between input string
        s=list(string)
        strig=[]
        for i in s:
            if i!=" ":
                strig.append(i)
        string = "".join(strig)
        return string

    def list_of_links(self, string):
        #create a list of strings. Each string is a link
        prev=0
        links=[]
        for i in range (len(string)):
            if string[i]=="\n" or string[i]==",":
                links.append(string[prev:i])
                prev=i+1
            elif i==len(string)-1:
                links.append(string[prev:i+1])
        return links

YouTube2mp3App().run()

A: When you run a method on the main thread, as you are doing with convert() method, no updates are made to the GUI until that method returns. This is a common problem and is typically handled by running the long running method in a separate thread. See the threading documentation. Then, from inside that method use Clock.schedule_once() to schedule calls that update the GUI on the main thread.


text:
Q: Binding data to div element and highlight the selected using Angular.js I want to display the data in a div element and highlight the default one as selected when the page is loaded, and when I click the other item which is not selected, the selected item should change the value for this .$scope.selectedItem property.
for e.g. I have this data
Item 1
Item 2

//this is the item list
 this.$scope.items = items;

//this is the selected item
this.$scope.selectedItem = selectedItem;

//html. I don't know how to design this, since I don't know how to bind the data to div element.

if I have a div element, how can I bind the data and display it. And from there, how I can save the selected value when I select an item?
Sorry I am new to Angular.js So I'm confused at the moment.

A: You could have ng-click on the div itself.. something like this:

   Item One

   Item Two

In controller:
 $scope.clicked = function(item) {
      $scope.selectedItem = item;
    };

you can use ng-class to decorate the div to have hilight..


text:
Q: How do I fix empty 44px space in iOS7 view with ViewDeckController? I am in the process of transitioning an app to iOS7. All of the views throughout the app have a 44px empty space at the bottom that appears to be for a bottom toolbar or something, but I am not trying to display a bottom toolbar. This space also exists on views that do have a bottom toolbar and the toolbar just shows directly above it.
The red space shown is actually a view behind the black view. No matter what size I set the frame of the black view to, the red space is always shown. I am also hiding the status bar in plist, so don't know if this is an artifact from that or if it has something to do with navigation bar as they are both normally 44px in height.
I have looked at the transitioning guide and haven't found anything that's worked. Any ideas to what could be causing this and how to fix?
UPDATE:
I have tried setting edgesForExtendedLayout = UIRectEdgeAll and extendedLayoutIncludesOpaqueBars = YES (also tried NO) with no effect. When I look at the subviews of the navigation controller it shows a UIToolBar as hidden, but shows it contains a frame in the exact area the view refuses to resize to even with autolayout constraints.
UPDATE 2:
This is actually a problem with ViewDeckController (https://github.com/Inferis/ViewDeck) and the way it sets it's center view bounds.

A: I believe it has to do with the UINavigationBar. Try toggling the following options in Storyboard and see if it solves the problem. Namely, the 'Extend Edges' options:

These options can also be set in code with the edgesForExtendedLayout and extendedLayoutIncludesOpaqueBars properties on UIViewController.

A: If you are transitioning to iOS 7, you should be using an Auto Layout constraint to anchor to the Bottom Layout guide. Control drag from your view to the Bottom Layout guide and choose Vertical Space from the popup menu.
Using frames in iOS 7 is harder and is the way of the past.
Auto Layout is hard to grasp at first, but it is very powerful once you get the feel.

A: This is actually a problem with third party library ViewDeckController (https://github.com/Inferis/ViewDeck) and the way it sets centerViewBounds for IIViewDeckControllerIntegrated. I was able to figure it out after changing to IIViewDeckControllerContained and seeing the view sized correctly.
In IIViewDeckController.m, just return self.referenceBounds for iOS7 like it does for IIViewDeckControllerContained.


text:
Q: Querying multiple tables in SQL using joins Here's my database, which is meant to contain data on musicians. My database design skills aren't the greatest but hopefully it's alright.

Tags = genres, for example rock.
Skills = guitar or vocalist
User_tags and user_skills are just being used to link the tables together, since a user can have many skills and many tags.
What I'm trying to do is query the database so that I can find users who have certain skills and are interested in certain genres. For example, find all users who are interested in rock and can play guitar. I looked up joins and managed to come up with the following query:
SELECT users.username, skills.skill_name
FROM user_skills
    JOIN users
        ON users.user_ID = user_skills.user_ID
    JOIN skills
        ON skills.skill_ID = user_skills.skill_ID
WHERE skills.skill_name = 'Guitar';

This worked, and I was able to find all users who played the guitar, but I can't figure out how to include the other half of the database as well (the tags). I tried this:
SELECT users.username, skills.skill_name, tags.tag_name
FROM user_skills, user_tags
    JOIN users
        ON users.user_ID = user_skills.user_ID
    JOIN skills
        ON skills.skill_ID = user_skills.skill_ID
    JOIN tags
        ON tags.tag_ID = user_tags.tag_ID
WHERE skills.skill_name = 'Guitar' AND tags.tag_name = 'Rock';

But I got an error: #1054 - Unknown column 'user_skills.user_ID' in 'on clause'
The column is definitely there though so the only thing I can think of that's breaking it is you cant join when you're selecting things from two tables. Every other example I looked at was just selecting data from one table.
Does anyone know how I can query all of my tables?

A: You can still select data from both tables. Give this a shot:
 SELECT DISTINCT
    users.username
 FROM
    users
 INNER JOIN
    user_skills ON users.user_id = user_skills.user_id
 INNER JOIN
    skills ON (user_skills.skill_id = skills.skill_id AND skills.skill_name = 'Guitar')
 INNER JOIN
    user_tags ON users.user_id = user_tags.user_id
 INNER JOIN
    tags ON (user_tags.tag_id = tags.tag_id AND tags.tag_name = 'Rock')


text:
Q: Creating an Exception in Python for improper user id on command line The user needs to enter a path to their file along with an id that is on every line in their file. I have created an exception for a wrong file and I want to do the same if the id that is typed doesn't match what's in the file. How do I do this?
import ConfigParser, os
import csv
import sys, getopt
import time
import datetime

from sys import argv
script, solutionId, input_file = argv

def check_all(f):
    print f.read()

def print_a_line(line_count, f):
    print line_count, f.readline()

try:
    current_file = open(input_file)
    check_all(current_file)
except IOError, e:
    print '%s, please try again.' % e

A: Well just declare your exception:
class WrongId(Exception): pass

And raise it when checking the file integrity:
if not check_id_in_file(input_id):
    raise WrongId()


text:
Q: Sum of alternative binomial coefficients How can I show that $\sum _{n=0}^{p-1} (-1)^n \binom{p}{n+1}=1$ where $p$ is a positive integer?
Is this the rule for this proof?
I could not figure it out even using this.
Probably this may be a well-known result, however I could not find.

A: By the binomial theorem,
$$ 0=(1-1)^p=\sum_{j=0}^p(-1)^j{p\choose j}$$
Note that the $j=0$ term in the sum is $1$. Therefore
$$ 1=-\sum_{j=1}^p(-1)^j{p\choose j}=\sum_{j=1}^p(-1)^{j-1}{p\choose j}$$
and setting $n=j-1$, this becomes
$$ 1=\sum_{n=0}^{p-1}(-1)^n{p\choose n+1}$$


text:
Q: Bootstrap flat-ui glyphs not displaying correctly I'm using bootstrap with flat-ui. Glyphs is displaying correctly if bootstrap and flat-ui files are on the same directory as the site. But when I transfer these files to a different directory and just point the files there from the site (with a different directory), the glyphs are just displaying "E024".
site directory:
/var/www/html/tn
bootstrap/flat-ui directory:
/var/www/html/fui
I have read this Bootstrap 3 unable to display glyphicon properly
Actually the glyphs are displaying correctly on other browsers other than firefox in win7.
but that didn't help. any idea?

A: I had the same issue with Firefox.  In my case, I was loading a bootstrap 3 based HTML5 web application from the local file system, not from a web server.  Apparently Firefox has security settings with this and local fonts - see this other answer:
CSS @font-face not working with Firefox, but working with Chrome and IE
In short, for me I was able to fix this in Firefox by changing the preference security.fileuri.strict_origin_policy to false.


text:
Q: How to find consecutive things in nested expressions? To find things that are consecutive you can use SequenceCases:
SequenceCases[{0, 1, 2, 3, 4},
       {x_, y_} /; (OddQ[x] && EvenQ[y]) :> {x, y}, \[Infinity]]
(*returns {{1, 2}, {3, 4}}*)

But this only works on lists, not for nested things:
nb = Notebook[{CellGroupData[{Cell["0", "Title"],
  Cell["1", "Section"], Cell["2", "Text"]}],
CellGroupData[{Cell["3", "Section"], Cell["4", "Text"]}]}];

SequenceCases[nb, {Cell[a_, "Section"], Cell[b_, "Text"]} :> {a,
   b}, \[Infinity]]
(* I'm trying to get {{1,2},{3,4}}*)

What's would be an efficient way to do this for large notebooks, should I switch to Cases, or use PatternSequence?


text:
Q: Angular way to set Iframe src to base64 data I am trying to set Iframe source to base64 data contains PDF in following format,
JS
$http.get('../../xyz', { token: $scope.token})
   .success( function(response) {
       $scope.reportBase64String = 'data:application/pdf;base64,' + response.data;
   });

HTML

ERROR
Blocked loading resource from url not allowed by $sceDelegate policy.

A: you can go through the doc of Strict Contextual Escaping Doc
but for now i would recommend you to inject $sce
and the file path which you provided change it to
$scope.reportBase64String=$sce.trustAsResourceUrl('data:application/pdf;base64,' + response.data);

A: In Angular 2+
.ts file
import { DomSanitizer } from '@angular/platform-browser';

this.http.get(url).subscribe(res => {
    if (res.data) { //res.data must be base64 data format
      this.src = this.sanitizer.bypassSecurityTrustResourceUrl('data:application/pdf;base64,' + res.data);
    }
  }

.html file

If would like to hide toolbar then just add #toolbar=0 after base64 string like
this.src = this.sanitizer.bypassSecurityTrustResourceUrl('data:application/pdf;base64,' + res.data + '#toolbar=0&navpanes=0');


text:
Q: Customize Clonezilla to simplify choices I am using Clonezilla in a non-profit organization. I wrote a usage guideline, but it needs 38 steps.
Now I wonder whether I could customize my Clonezilla USB Stick so that it does not provide all the options.
E.g. I could get rid of

*

*the language selection. It's totally fine if it's always English

*the keymap choice. It should just select "keep the default" ("don't touch the keymap" on older versions)

*the operation mode choice. We always want "device-image".

*the storage selection. We always need "local_dev".

What would I need to do to configure Clonezilla to get rid of these choices?

A: Clonezilla calls that 'preseeding' as described in that web link. As you pick options, Clonezilla shows the preseed commands in green-on-black as shown here.
For example, the preseeding command should include a language selection command locales=en_US.UTF-8 and a specification for no special keyboard layout with keyboard-layouts=NONE in syslinux.cfg or isolinux.cfg as appropriate.


text:
Q: Sphere-sphere intersection is not a surface In my topology lecture, my lecturer said that when two spheres intersect each other, the intersecting region is not a surface. Well, my own understanding is that the intersecting region should look like two contact lens combine together,back to back. The definition of a surface that I have now is that every point has a neighbourhood which is homeomorphic to a disc. I don't see why the intersecting region is not a surface. It will be better if someone can guide me through picture.

A: A sphere is the surface of a ball. The object you are thinking of is the surface of the intersection of two balls. But the intersection of the spheres is the intersection of the surfaces of those balls, which is not the same. Especially, each point in the intersection must be on both spheres. Now it is easy to see that most points on your lens-like object are only on one of the surfaces, but somewhere inside the other.
Indeed, the intersection of two spheres (assuming they intersect at all and are not identical) is always a circle (possibly a degenerate circle of radius 0, that is, a point, in case the spheres are tangential to each other). That circle is the edge of your lens-like object.

A: The intersection of two spheres is not "two contact lenses": it is only the points in common, where two hollow spheres intersect. They intersect either at a single point (if they are tangent), or else their intersection is what we can envision as the boundary shared by two contact lenses that are joined back to back: i.e. a circle.
Think of it like this: If we were to glue two contact lens "back to back" $()$, we would only apply glue to their edges, because those are the only points at which they join or "connect", and the points at which they join (i.e. intersect) is no more and no less than a circle (see, e.g., the image below). This is true, unless the lens are merely tangent: $\quad)(\quad$
in which case they intersect ("touch") at that single point of tangency.

A: In general 2 spheres on $\mathbb{R}^3$ intersect on a circle which is a curve as you can simply imagine. You don't need to see a picture to visualize that I think..


text:
Q: Problems trying to deploy on azure a sample web application I am trying to deploy an Hello World sample web application on Windows Azure, but I'm running into problems for which I can't find the answer.
First, I can't create a new Hosted Service to deploy it because the "new hosted service window" is bugged as you can see below, the "Choose a subscription" and "Choose a region" dialog are just empty, so I can't upload my package to deploy it.

Then when I go to the "Hosted Service" screen, my 3-month trial is marked as disabled :

And if I try to publish via Visual Studio, I can't import my credentials downloaded from the link in the dialog, as shows the picture below :

If anybody knows how to fix it, I'm would love to hear !
Thanks

A: Because your 3 months trial is disabled, you won't be able to create a hosted service and you won't be able to deploy from Visual Studio. It seems that you've signed up for the trial on 12/22, I would contact support and figure out why your 3 months trial is disabled.


text:
Q: type org.json.JSONObject cannot be converted to JSONArray Android Am trying to use the json data returned from my php code during form validation process and am getting this type org.json.JSONObject cannot be converted to JSONArray Error. i don't seem to know what the problem is at the moment and the error below points to line 80
The Json data looks thus

{
    "code": "VAL500",
    "valError": {
        "username": "The Username field must be at least 5 characters in length.",
        "password": "The Password field must be at least 5 characters in length.",
        "submit": ""
    }
}

And the LoginActivity
package com.example.drawerlayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private EditText username, password;
    private static String URL_REGIST = "http://192.168.43.54/airtimeflip/login/android_login_validate";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);

        Window window = getWindow();
        // clear FLAG_TRANSLUCENT_STATUS flag:
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        // add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        // finally change the color
        window.setStatusBarColor(ContextCompat.getColor(LoginActivity.this,R.color.white));
    }

    public void loginValidate(View v) {
        final String uname = username.getText().toString();
        final String pass = password.getText().toString();
       // Toast.makeText(getBaseContext(), "USERNAME: " + uname + " PASSWORD: "+ pass, Toast.LENGTH_SHORT).show();
        // check if the username and password matches

       if (uname.equals("")) {
            username.setError("Please Enter a Username");
        }
        else if(pass.equals("")) {
           password.setError("Please Enter your Password");
        }else{
           login(uname, pass);
       }
    }

    private void login(final String uname, final String pass){
        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String code = jsonObject.getString("code");
                            // form validation Error
                            if (code.equals("VAL500")){
                                JSONArray jsonArray = jsonObject.getJSONArray("valError");
                                for (int i = 0; i < jsonArray.length(); i++){
                                    JSONObject error = jsonArray.getJSONObject(i);
                                    username.setError(error.getString("username").trim());
                                    password.setError(error.getString("password").trim());
                                }
                            }
                            // invalid user information provided
                            if (code.equals("UEX400")){
                                String errMsg = jsonObject.getString("userDataError");
                                Toast.makeText(LoginActivity.this, errMsg, Toast.LENGTH_SHORT).show();
                            }

                            // valid user infroomation provided
                            if (code.equals("UEX200")){
                                JSONArray jsonArray = jsonObject.getJSONArray("details");
                                for (int i = 0; i < jsonArray.length(); i++){
                                    JSONObject details = jsonArray.getJSONObject(i);
                                    String name = details.getString("username").trim();
                                    String email = details.getString("email").trim();
                                    String type = details.getString("type").trim();
                                    String manager = details.getString("account_manager").trim();
                                    String status = details.getString("status").trim();

                                    Intent dashboard = new Intent(LoginActivity.this,MainActivity.class);
                                    dashboard.putExtra("username", name);
                                    dashboard.putExtra("email", email);
                                    dashboard.putExtra("type", type);
                                    dashboard.putExtra("manager", manager);
                                    dashboard.putExtra("status", status);
                                    startActivity(dashboard);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.d(TAG, "onResponse: Clicked." + e.toString());
                            // Toast.makeText(LoginActivity.this, "Login Error! "+ e.toString(), Toast.LENGTH_SHORT).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(LoginActivity.this, "Login Error! "+ error.toString(), Toast.LENGTH_SHORT).show();
                    }
                })

        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("username", uname);
                params.put("password", pass);
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

}

and am displayed with the error
09-17 22:28:06.100 3994-3994/com.example.drawerlayout W/System.err: org.json.JSONException: Value {"username":"","password":"The Password field must be at least 5 characters in length."} at valError of type org.json.JSONObject cannot be converted to JSONArray
09-17 22:28:06.100 3994-3994/com.example.drawerlayout W/System.err:     at org.json.JSON.typeMismatch(JSON.java:100)
09-17 22:28:06.102 3994-3994/com.example.drawerlayout W/System.err:     at org.json.JSONObject.getJSONArray(JSONObject.java:588)
09-17 22:28:06.102 3994-3994/com.example.drawerlayout W/System.err:     at com.example.drawerlayout.LoginActivity$1.onResponse(LoginActivity.java:80)
09-17 22:28:06.102 3994-3994/com.example.drawerlayout W/System.err:     at com.example.drawerlayout.LoginActivity$1.onResponse(LoginActivity.java:72)
09-17 22:28:06.102 3994-3994/com.example.drawerlayout W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
09-17 22:28:06.102 3994-3994/com.example.drawerlayout W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
09-17 22:28:06.102 3994-3994/com.example.drawerlayout W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
09-17 22:28:06.102 3994-3994/com.example.drawerlayout W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
09-17 22:28:06.102 3994-3994/com.example.drawerlayout W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
09-17 22:28:06.102 3994-3994/com.example.drawerlayout W/System.err:     at android.os.Looper.loop(Looper.java:135)
09-17 22:28:06.103 3994-3994/com.example.drawerlayout W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5293)
09-17 22:28:06.103 3994-3994/com.example.drawerlayout W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
09-17 22:28:06.103 3994-3994/com.example.drawerlayout W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
09-17 22:28:06.103 3994-3994/com.example.drawerlayout W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
09-17 22:28:06.103 3994-3994/com.example.drawerlayout W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-17 22:28:06.103 3994-3994/com.example.drawerlayout D/LoginActivity: onResponse: Clicked.org.json.JSONException: Value {"username":"","password":"The Password field must be at least 5 characters in length."} at valError of type org.json.JSONObject cannot be converted to JSONArray

A: valError is not a Array. It is an object. You should get it like
JsonObject jsonValError = jsonObject.getAsJsonObject("valError")

And for that you can get the field username for example like
String username = jsonValError.getString("username")

A: Your code is correct
Your Json format is not , your are missing [] in your array
Try this :
{
    "code": "VAL500",
     "valError": [{
            "username": "The Username field must be at least 5 characters in length.",
            "password": "The Password field must be at least 5 characters in length.",
            "submit": ""
        }]
    }

EDIT :

in php to have a proper json format use :
echo json_encode($response);


text:
Q: React "TypeError: product.name.includes(...).map is not a function" when attempting to filter through product list I have a React application that displays a list of products when getting product data from a database using an axios.get call. That part works perfectly, but today I've tried implementing a search feature to only display product names that matches the search query but when I attempt to type even a single letter the application crashes and I get this:
TypeError: product.name.includes(...).map is not a function

function productList() {
  40 |        if(searchTerm) {
> 41 |            return products.filter(product => product.name.includes(searchTerm).map(function(currentProduct, i) {
     | ^  42 |                return <Product product={currentProduct} key={i} />;
  43 |            }));
  44 |        } else {

How can I implement this correctly? I was trying to follow this previously answered question as a guide.
productListPublic.js:
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { CardColumns, Card, Row, Col, ListGroup, Form } from "react-bootstrap";
import axios from "axios";

function ProductListPublic(props) {
    const [isError, setIsError] = useState(false);
    const [products, setProducts] = useState([]);
    const [searchTerm, setSearchTerm] = useState("");

    const Product = props => (
        <Card>
            <Row>
                <Col md={{ span: 4 }}>
                    <Card.Title className="mt-4 text-center">
                        <Link to={`/products/list/${props.product._id}/`}>{props.product.name}</Link>
                    </Card.Title>
                </Col>
                <Col md={{ span: 8 }}>
                <ListGroup>
                    <ListGroup.Item className="text-truncate">{props.product.description}</ListGroup.Item>
                    <ListGroup.Item>{props.product.stock} in stock</ListGroup.Item>
                </ListGroup>
                </Col>
            </Row>
        </Card>
    )

    useEffect(() => {
        axios.get("http://localhost:4000/products/")
        .then(res => {
            setProducts(res.data);
        }).catch(function(err) {
            setIsError(true);
        })

    }, []);

    function productList() {
        if(searchTerm) {
            return products.filter(product => product.name.includes(searchTerm).map(function(currentProduct, i) {
                return <Product product={currentProduct} key={i} />;
            }));
        } else {
            return products.map(function(currentProduct, i) {
                return <Product product={currentProduct} key={i} />;
            })
        }
    }

    return (

            <Form>
                <Form.Row>
                    <Form.Group as={Col}>
                        <Form.Label htmlFor="formSearch">Search Products</Form.Label>
                        <Form.Control
                                    controlid="formSearch"
                                    type="text"
                                    value={searchTerm}
                                    onChange={e => {
                                        setSearchTerm(e.target.value);
                                    }}
                                    placeholder="Product Name"
                                    />
                    </Form.Group>
                </Form.Row>
            </Form>

Products List

            <CardColumns>
                { productList() }
            </CardColumns>
            { isError &&
Something went wrong with getting the products!
 }

    )
}

export default ProductListPublic;

A: Close the filter parentheses then use map on the resultant list.
return products.filter(product => product.name.includes(searchTerm)).map((currentProduct, i) => {
    return <Product product={currentProduct} key={i} />;
});


text:
Q: Webpack 5 does not support polyfills for Node.js I have an npm package that works on Angular as well as on Node.js.
Lately, I have started to use my package with Angular v12 projects.
I am getting errors like:

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it.

I need those packages (e.g. 'path'), and I cannot switch to the Webpack alternative (e.g. 'path-browserify') since I need this to work on nodejs.
The error says:

If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
- install 'path-browserify'

Installing 'path-browserify' is easy. However, the error does not state where to add the fallback. I found in some posts that suggest I need to add it to Webpack.config.js. But in the Angular project, there is no such file; adding it did not have any effect. And even if there were such a file, it would not help me because I am an npm package, and I cannot change files in the application that uses me.
I can write a workaround for the 'path' package. However, other packages raised that error. Some of the packages (e.g., suppertest) are not meant to work from webpack, and I am not using them when running on angular, but since they are in my code, the webpack still raises this error. I am also using other packages that use themselves problematic packages like 'path' or 'stream,' and I cannot change them. How can this issue be solved?

A: As the error states, you should add resolve.fallback: { "path": require.resolve("path-browserify") } in your webpack config file.
// webpack.config.js

module.export = {
  ...
  resolve: {
    fallback: {
      path: require.resolve("path-browserify")
    }
  }
  ...
}


text:
Q: How can I style readonly selects to appear disabled? I have a select field:
<select class="form-control" data-admin--reports-form-target="sendFrequencySelect" name="automated_digest_task[send_frequency]" id="automated_digest_task_send_frequency"><option value="86400">1 day</option>
<option value="259200">3 days</option>
<option value="604800">7 days</option>
<option value="1209600">14 days</option>
<option value="2629746">1 month</option>
<option value="7889238">3 months</option>
<option value="15778476">6 months</option>
<option value="31556952">1 year</option></select>

...which I am setting to readonly via JS (I use Stimulus):
this.sendFrequencySelectTarget.readOnly = true;

I want to use readonly instead of disabled because disabled causes the select to not be submitted with a form, and I want it submitted.
Setting to readonly does indeed make the field readonly, but it doesn't cause the select to appear any different.
What I want is the field to be readonly, but its appearance to be that of a disabled select. That is, the background color dims to a gray and the cursor changes to not-allowed on mouseover.
I have tried applying styles to selectors like select[readonly], select:read-only, select[readonly="readonly"], input[type="select"]:read-only, but none of these selectors seem to work.
For example...
select[readonly] {
  cursor: not-allowed;
}

... has no effect.
How can I style readonly selects to appear disabled?


text:
Q: Selection Sort, For Java I am having trouble understanding this pseudocode, and implementing it into my program. Can anybody explain it better or show me how the code would look? Thanks.
A - an array containing the list of numbers
numItems - the number of numbers in the list

for i = 0 to numItems - 1
    for  j = i+1 to numItems
        if A[i] > A[j]
            // Swap the entries
            Temp = A[i]
            A[i] = A[j]
            A[j] = Temp
        End If
    Next j
Next i

A: Well, let's translate the pseudo-code to pseudo-English.
A - an array containing the list of numbers
numItems - the number of numbers in the list

for i = 0 to numItems - 1
    for  j = i+1 to numItems
        if A[i] > A[j]
            // Swap the entries
            Temp = A[i]
            A[i] = A[j]
            A[j] = Temp
        End If
    Next j
Next i

which might read
Count through each item, from the beginning to the end, calling it X
  While considering item X, count through each item after it, from just
  after X to the end, calling it Y
    If X is bigger than Y, swap the two, temporarily storing X in Temp
      so it doesn't get lost when we copy Y into X.  Copy Y into X, and then
      Copy the temporarily stored old value of X (remember it is in Temp)
      back into Y.  Now the values of X and Y are swapped (so X is now smaller
      than Y)

Now it's your job to write it in code.

A: The name of the algorithm tells you a whole lot about it. It first selects the smallest element of the list and puts it in the first spot. Then it selects the second and puts it in the second, etc.
How do you find the smallest element? Well you look through the list, and if the element you're looking at is smaller than the element at the beginning of the list, swap it in.
How do you find the second smallest? You know that the smallest element is already in the first spot. So that means the second smallest must be the smallest element between the second element and the end of the list. So you go through and do the appropriate swaps again.
Lather, rinse, and repeat.
If you're wondering how elements are swapped. Just think about how you would do it by hand. You pick element 1 up and put it in a safe place, put element 2 in element 1's old spot, then put element 1 in element 2's old spot. The temporary variable used would represent the safe place you put element 1.
Wikipedia has a nice article on it.

A: If all you want to do is sort an array of ints into a specific order and your professor doesn't mind you using a utility class then Go Here.
However, if you are required to write the sorting algorithm yourself then Go Here there are explanations and examples.


text:
Q: CSS counters don't work inside other elements This problem is not a duplicated of CSS counter-increment is not working for nested div and h3 elements
I have a problem using CSS counters when the element on which is applied is inside other elements:
HTML:

HTML/CSS Tutorials

HTML

CSS

Bootstrap

Scripting Tutorials

JavaScript

jQuery

React

CSS:
body {
  counter-reset: section;
}

h1 {
  counter-reset: subsection;
}

h1::before {
  counter-increment: section;
  content: "Section " counter(section) ". ";
}

h2::before {
  counter-increment: subsection;
  content: counter(section) "." counter(subsection) " ";
}

For the second section it's working fine, but for the first one, the subsection keeps reseting and it's always showing 1. Please advise, thanks!

A: If you add a class to the h1 parent div, you can do it this way:

h1::before, h2::before {
    color: red;
}
div.heading {
    counter-increment: item;
    counter-reset: item2;
}
div.heading + div {
    counter-increment: item2;
}

div ~ div {
    counter-increment: item2;
}

h1::before {
    content: "Section " counter(item) ". ";
}

h2::before {
    content: counter(item) "." counter(item2) " ";
}

HTML/CSS Tutorials

HTML

CSS

Bootstrap

HTML/CSS Tutorials

HTML

CSS

Bootstrap


text:
Q: NodeJS - Return client ip address instead of server's Problem Information
I'm using cors to make sure that only specific IP's can GET and POST data on my REST API.
The IP that is returned , everytime someone want to GET or POST data, is the IP of the server where the application is hosted on, not the person's own IP address.
At this moment everyone can access the REST API because my front-end is running on the same server, the front-end needs to have the permission to GET and POST data so I whitelisted the server's IP address.
Since everyone, who's trying to connect, its ip address is automatically the server's address, everyone has access the REST API.
Technical Information
My REST API is running using pm2 on port 8080, I re-route it using Nginx to port 8877 that's using SSL. The 8877 is the endpoint of my rest api, perhaps that's the reason why the client ip address is automatically the server's ip address?
# General HTTP to HTTPS
server {
        listen 80;
        listen [::]:80;
        server_name www.example.com default_server;

        location / {
                return 302 https://$host$request_uri;
        }
}

#Web Application
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name www.example.com default_server;

    root /var/www/example.com;
    index index.html;

    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_certificate /etc/nginx/ssl/example.com/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com/example.com.key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

    location / {
                #...
                try_files $uri $uri/ /index.html$is_args$args;
                #...
    }
}

#Rest API http to https
server {
    listen 8877 ssl;
    listen [::]:8877 ssl;
    server_name example.com;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_certificate /etc/nginx/ssl/example.com/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com/example.com.key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

    location / {
            proxy_pass http://example.com:8080;
    }
}

Rest API cors
const whitelist = [
    '::ffff:111.11.11.111', etc.];

var corsOptions = {
    origin: (origin, callback) => {
        let trafficAllowed = {};
        console.log("IP: ", origin);
        if (whitelist.indexOf(origin) !== -1) {
            trafficAllowed = {origin: false}
        } else {
            trafficAllowed = {origin: true}
        }
        callback(null, trafficAllowed)
    }
};

app.use((req, res, next) => {
    req.headers.origin =
        req.connection.remoteAddress ||
        req.headers['x-forwarded-for'] ||
        req.socket.remoteAddress ||
        (req.connection.socket ? req.connection.socket.remoteAddress : null);
    next();
});

app.use(cors(corsOptions));

Possible ways to solve it

*

*Is it possible to assign SSL directly to the 8080 port (the REST API is using pm2)?

*How to get the client's ip address instead of the server his.

A: Try putting these configurations in your nginx:
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $proxy_x_forwarded_proto;

Without this, your backend will only receive nginx IP address.


text:
Q: SSIS variable not getting set when assigning it from C# I have a SSIS package have some variables defined in it (say for example, TempTableName). I am creating a temp table in my C# code (windows service) and assigning the name of that temp table to a package variable. On calling the SSIS package, the package fails with the error message saying  the temp table name is invalid, actually it is blank. What I don't understand is why the variable is not getting set from C#?
My C# code
oPkg = oApp.LoadPackage(mySSISPackagePath, null);
Variables vars= null;
if (oPkg.Variables.Contains("User::TempTableName"))
{
   oPkg.VariableDispenser.LockOneForWrite("User::TempTableName", ref vars);
   vars["User::TempTableName"].Value = "MyTempTableName";
}


text:
Q: C# Testing Exceptions in N-Unit I am having a hard time figuring out what my Assert statement should look like to test the Exception and/or the User Message in the "default" code block below. Any ideas?
public void LoadLanguage(string language)
        {
            switch (language)
            {
                case "Spanish":
                    ShouldPrintSpanish = true;
                    break;
                case "English":
                    ShouldPrintEnglish = true;
                    break;
                case "Both":
                    ShouldPrintSpanish = true;
                    ShouldPrintEnglish = true;
                    break;
                default:
                    string ex = "AgreementDetailViewModel.LoadFormsForSelectedLanguage() failed to execute correctly";
                    ExceptionLog.LogException(new Exception(ex),Environment.MachineName, null, "");
                    ShowError("User should have been able to select a language from the dropdown");
                    throw new Exception(ex);
            }
        }

Exception Logging Code
public static ExceptionLog LogException(Exception exception)
        {
            return new ExceptionLog(exception, "", "", "", "");
        }

private ExceptionLog (Exception exception, string environmentVariables, string computerName, string ipAddress, string createdBy)
        {
            if (exception == null)
                throw new ArgumentException("The exception cannot be null.");

            _Exception = exception;
            CreateAndSaveParentException(computerName, environmentVariables, ipAddress, createdBy);
            CreateAndSaveChildExceptions();
        }

A: Use Assert.Throws<ExceptionType>.
https://github.com/nunit/docs/wiki/Assert.Throws


text:
Q: Compute the conditional expectation of a standard normal random variable X given X>a $X$ is a standard normal random variable with density $\phi(x)=\frac{1}{\sqrt{2\pi}}exp(-\frac{x^2}{2})$ and $a$ is a given constant. Denote $p=P[X>a]$.
My question is how to derive $E[X|X>a]=\frac{\phi(a)}{p}$.

A: hint
This is equivalent to showing $$ \int_a^\infty x\phi(x)dx = \phi(a).$$ From here, use the fact that $\phi'(x) = -x\phi(x).$


text:
Q: Error de python con condicionales elif no tomado en cuenta El error es que cuando ejecuto mi código con la condicional if lo ejecuta bien pero cuando pruebo el elif no lo toma en cuenta y va directo al if por alguna razón. Aquí el código:
nombre_usuario=str(input("como debo de llamarte usuario?... "))

verificacion=str(input("excelente, vuestro nombre es "+str(nombre_usuario)+"

correcto??? responde de manera afirmativa para si, negativa para no "))

if verificacion=="si "or"SI"or"Si"or"S"or"s":

    print("afirmativo verificacion confirmada "+str(nombre_usuario))

elif verificacion=="no"or"NO"or"No"or"N"or"n":

    print("afirmativo nombre no valido...reiniciando protocolo_inicio")

A: Otra alternativa donde lo haces más simple y no tienes que poner tantos 'or' en la sentencia if sería utilizando una lista (list) con los diferentes repuestas que puede dar el usuario:
nombre_usuario = str(input("como debo de llamarte usuario?... "))

verificacion = str(input("excelente, vuestro nombre es "+str(nombre_usuario)+"correcto??? responde de manera afirmativa para si, negativa para no "))

palabras_no = ['no', 'No', 'n', 'NO', 'oN']
palabras_si = ['si', 'SI', 'Si', 'S', 'sI']

if verificacion in palabras_no:
    print('Hago lo que sea no.')

if verificacion in palabras_si:
    print('Hago lo que sea si.')

Y para no tener que tener tantas opciones puedes siempre pasar lo que el 'usuario' escribe a minúsculas con la función lower() que es una práctica que se suele realizar.
nombre_usuario = str(input("como debo de llamarte usuario?... "))
verificacion = str(input("excelente, vuestro nombre es "+str(nombre_usuario)+"correcto??? responde de manera afirmativa para si, negativa para no "))

palabras_no = ['no', 'n']
palabras_si = ['si', 's']

if verificacion.lower() in palabras_no:
    print('Hago lo que sea no.')

if verificacion.lower() in palabras_si:
    print('Hago lo que sea si.')


text:
Q: Access async store data before vue-router runs beforeEach (navigation guard) I want to use a navigation guard but my store data is async and its allways to late, so the beforeEach runs before  my auth status is loaded. I tried to load my auth status in the created() hook of my vue app, then I tried to load it before new Vue in main.js or in router.js before the beforeEach runs... I even tried it with waiting for the promise...
Here my async action
export default {
async setIsAuthenticated(context) {
    await auth.onAuthStateChanged(function(user) {
        if (user) {
            context.commit('setIsAuthenticated', true);
            context.dispatch('user/setUserData', user.uid, {
                root: true,
            });
        }
    });
}

The setIsAuthenticated action triggers this mutation
    setIsAuthenticated(state, payload) {
        state.isAuthenticated = payload;
},

This is my router.js beforeEach()
router.beforeEach((to, from, next) => {
if (to.path !== '/userauth' && !store.getters['auth/isAuthenticated']) {
    next('/userauth'):
} else {
    next();
}

And I tried to dispatch at it with waiting for the promise
store.dispatch('auth/setIsAuthenticated').then(log => {
console.log(log);
});
console.log(store.getters['auth/isAuthenticated']);

But isAuthenticated is allways null. Only when the site is completely loaded I can console.log it and its true

A: I already found a solution. Maybe it will help someone:
I created a init action that returns a promise and dispatches my action which gets me the auth status before I do anything else.
    store.dispatch('init').then(() => {
       new Vue({
          vuetify,
          router,
          store,
          render: h => h(App),
       }).$mount('#app');
    });

And this is the action init:
  actions: {
    init(context) {
        return new Promise(resolve => {
            setTimeout(() => {
                context.dispatch('auth/setIsAuthenticated', null, {
                    root: true,
                });
                resolve('Done');
            }, 1000);
        });
    },


text:
Q: Decimal places in NumericUpDown control I am sorry if this has been answered before. I searched around and couldn't find a suitable answer.
I have a numericupdowncontrol that takes user input. Right now I have set decimalPlaces property set to 2.
If user enters 1.23, it stays correct. However if user enters 1.2, then it displays 1.20. That is not what I want. It should display 1.2 and not 1.20. Is there a way to do this?
If user enters 1, then it should be 1 and not 1.00. How do do this?
Thanks much!

A: If you don't mind customizing your NumericUpDown, you can do this which is very easy, short and reliable:
//You can use this class instead of the standard NumericUpDown
public class CustomNumericUpDown : NumericUpDown
{
    //Override this to format the displayed text
    protected override void UpdateEditText()
    {
        Text = Value.ToString("0." + new string('#', DecimalPlaces));
    }
}


text:
Q: Mobile Safari grayscale filter adds blur I'm desaturating images with these filters:
img {
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
    filter: gray;
    -webkit-filter: grayscale(1);
}

It works nicely, though the filter seems to pixellate images on Mobile Safari. I don't know why that is. Is there a secret method of retaining clarity? Or must I live with this browser shortcoming? As an example, here are some juxtaposed screenshots, taken from iOS Simulator:

A: A little bit too late but this should do the trick:
-webkit-transform: translateZ(0);

source: http://matthewhappen.com/fixing-css3-filter-blur-on-retina-displays/

A: I don't know whether mobile safari is picking up the filter style or the -webkit-filter.
I don't believe that -webkit filters allow you to specify filter resolution, so if you want to over-ride this default behavior, you have to add a filterRes=400 to the filter definition or the alternative is to go to inline svg and specify an explicit filterRes for your filter aka.
<svg>
   <defs>
     <filter id="greyscale" filterRes="1278">
        <feColorMatrix etc...>
     </filter>
   </defs>

Images...

</svg>


text:
Q: Is it possible to use ISR on-demand validation with multiple instances of NextJS? I had a problem recently, there are 2 instances of NextJs in different servers, and there is an API for revalidating paths "/api/revalidate", but the problem is when using a load balancer with the servers, I can only reach and revalidate only one server, the other server would still use the old html. Is there a way around this? I'm using 'generateBuildId' to use the same buildID with shared storage, but it does not work with static html.

A: Ok, turns out that the build is really cached inside the memoy. in-memory cache can be disabled using this in "next.config.js":
module.exports = {
experimental: {
  // Defaults to 50MB
   isrMemoryCacheSize: 0,
  },
}


text:
Q: webpack - export all folders with html inside How i can export all my .html files and folders in .dist folder?

I use this script in webpack.config.js, but it doesn't work with files in folders.

function generateHtmlPlugins(templateDir) {
  const templateFiles = fs.readdirSync(path.resolve(__dirname, templateDir));
  return templateFiles.map(item => {
    const parts = item.split('.');
    const name = parts[0];
    const extension = parts[1];
    return new HTMLWebpackPlugin({
      filename: `${name}.html`,
      template: path.resolve(__dirname, `${templateDir}/${name}.${extension}`),
      inject: false,
    })
  })
}

const htmlPlugins = generateHtmlPlugins(environment.paths.src.html)


text:
Q: React-native app keeps stopping on emulator
I am not getting any error in my app while running (npx react-native
  run-android) and react-native start but it is showing on the emulator
  that your app keeps stopping.


text:
Q: QueryBuilder - Use Select in an innerJoin can someone help me.
I need to change my sql query to a querybuilder. I don't know how to use select inside a innerJoin.
Here my sql query:
SELECT
      user.id,
      analytic_youtube_demographic.age_group,
      analytic_youtube_demographic.percentage
FROM
    user
INNER JOIN user_youtube ON user_youtube.id = user.id
INNER JOIN analytic ON analytic.id = user_youtube.analytic_id
INNER JOIN analytic_youtube_demographic ON analytic_youtube_demographic.analytic_id = analytic.id
INNER JOIN
(
SELECT analytic_youtube_demographic.id as id, MAX(analytic_youtube_demographic.percentage) max
from user
INNER JOIN user_youtube ON user_youtube.id = user.id
INNER JOIN analytic ON analytic.id = user_youtube.analytic_id
INNER JOIN analytic_youtube_demographic ON analytic_youtube_demographic.analytic_id = analytic.id
GROUP BY user.id
) AS T ON analytic_youtube_demographic.percentage = T.max
WHERE analytic_youtube_demographic.age_group IN ('18-24')

Thanks a lot for your help.


text:
Q: Ratio of answer types Related to post:
Etiquette for answering your own question
As far as I can tell, Stack Overflow is semantically both of a) a place to share information and b) a nerd battleground.
Users do not care about the system when they do battle. They care about their own life which is the respect they get by being awesome and careers based on their skills. They can affect this enormously by asking new questions that nobody has asked and producing answers they already know. This is legal according to the FAQ.
However, we could show some status information on HOW MUCH a user has asked and answered his own questions, as this would expose question manufacturers. For example, 0.1% would tell us that every one answer in a thousand is a self-answer.
The FAQ says:

It's also perfectly fine to ask and answer your own programming question

However FAQ does not say that information about the ratio of answers should be hidden.

A: Let's say this actually happens a lot. Why would I care? If the question is good, and the answer is wonderful, please have my upvotes. If the question is bad and the answer as well, hey, I get to downvote you twice. Crappy question but great answer? I might just close your question, no matter how much effort you put into your answer.
So what would such a ratio tell me? What is it that such a ratio should make me aware of? How should that influence me as another user?
I'll just judge the content. And if that is all good, I couldn't care less. If it's all crap, bans will happen.


text:
Q: Can an arbitrary spin state be written uniquely in a Dicke state basis? Consider a system of e.g. $N=3$ spin-1/2 particles. The state of the system $\vert\psi\rangle$ lives in a Hilbert space of dimension $2^N=8$.
Now, consider the collective spin operator
$$\mathbf{J} = \sum\limits_{i=1}^{N}\mathbf{j}^{(i)}.$$
From this operator one can define the Dicke states $|J,M\rangle$ as the simultaneous eigenstates of
$$\mathbf{J}^{2}|J,M\rangle = J(J+1)|J,M\rangle,$$
$$\mathbf{J}_{z}|J,M\rangle = M|J,M\rangle.$$
For three spins we have the six possible states $|3/2,3/2\rangle$, $|3/2,1/2\rangle$, $|3/2,-1/2\rangle$, $|3/2,-3/2\rangle$, $|1/2,1/2\rangle$, $|1/2,-1/2\rangle$. Here, note that the operator $\mathbf{J}$ lives in a 8-dimentional space, and the two apparently missing eigenstates come from the fact that $|1/2,1/2\rangle$ and $|1/2,-1/2\rangle$ come with multiplicity two. Therefore, the six Dicke states listed before form a basis for the 8-dimensional Hilbert space of $N=3$ spins.
(further references: Collective angular momentum , Dicke states and indistinguishable particles)
As Dicke states form a basis, I would expect the possibility to write uniquely any spin state in this basis. However, this is not possible as the basis has degenerate vectors. It seems that initial information on the symmetry under particle exchange is lost in this basis change.
For example, three spin can combine as listed here: Adding 3 electron spins . As you can see from the rows dealing with $N=3$ spins, there are two states compatible with $|1/2,1/2\rangle$ and two compatible with $|1/2,-1/2\rangle$. Which is because they have different permutational symmetry.
Is this reasoning correct? Therefore, what can one say about the basis formed by Dicke states? Is there a typical operator to use, compatible with $\mathbf{J}^{2}$ and $\mathbf{J}_{z}$, whose eigenstates brake the above degeneracy?


text:
Q: Spring Bean Dependence - How to Configure Core beans depends On A Web Tier Bean In a web configuration, I have a bean, Thymeleaf's TemplateEngine, which relays on servlet. The templateEngine also is used for an Emailservice. And several service beans depend on the EmailService. My Spring configuration is in the following structure:
public class WebAppInitializer extends
    AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class<?>[] { WebSecurityConfig.class, JPAConfig.class,
            CoreConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return new Class<?>[] { WebConfig.class };
}

//....
 }

I have tried various approaches without a luck. How to solve this dependence problem?


text:
Q: Is there a way to draw a arrow inside a circle elegantly I am trying to plot a unit vector in a unit circle.
here is the code
vunit = 1/np.sqrt(2)
vec1 = [vunit,vunit]
thetas = np.arange(-np.pi, np.pi, .05)
coordinates = np.vstack((np.cos(thetas),np.sin(thetas)))

plt.figure(figsize = (6,6))
plt.xlim(-3,3)
plt.ylim(-3,3)
plt.scatter(coordinates[0,:],coordinates[1,:],s=.1)
plt.arrow(0, 0, vec1[0], vec1[1], head_width=0.15, color='r')

everything is OK, except the head of arrow is outside the circle.
so, I modify the vec1 ugly
vec1 = [vunit-.1,vunit-.1]

the figure looks better and I can modify the vec1 more finely, but the fix seem to be ugly. is there a way to have the arrow inside the circle elegantly

A: Use length_includes_head=True:
import numpy as np
import matplotlib.pyplot as plt

vunit = 1/np.sqrt(2)
vec1 = [vunit,vunit]
thetas = np.arange(-np.pi, np.pi, .05)
coordinates = np.vstack((np.cos(thetas),np.sin(thetas)))

plt.figure(figsize = (6,6))
plt.xlim(-3,3)
plt.ylim(-3,3)
plt.scatter(coordinates[0,:],coordinates[1,:],s=.1)
plt.arrow(0, 0, vec1[0], vec1[1], head_width=0.15, color='r', length_includes_head=True)
plt.show()

A: One might use a FancyArrowPatch instead of a FancyArrow (which is the object produced by plt.arrow).
The difference here is marginal, but for other cases, and hence consistency, FancyArrowPatch offers a lot of nice features that are not present for FancyArrow. One main difference is observed when zooming the plot; the FancyArrow's head is defined in data coordinates, it will hence look skewed when shown in non equal aspect plots.

So here is the complete code with FancyArrowPatch, where we get the head tip at the end coordinate via shrinkB argument.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch

vunit = 1/np.sqrt(2)
vec1 = [vunit,vunit]
thetas = np.arange(-np.pi, np.pi, .05)
coordinates = np.vstack((np.cos(thetas),np.sin(thetas)))

plt.figure(figsize = (6,6))
plt.xlim(-3,3)
plt.ylim(-3,3)
plt.scatter(coordinates[0,:],coordinates[1,:],s=.1)

arrow = FancyArrowPatch(posA=(0,0), posB=vec1,
                        arrowstyle='-|>', mutation_scale=20,
                        shrinkA=0, shrinkB=0, color='r')
plt.gca().add_patch(arrow)

plt.show()


text:
Q: How to specify remote address for websocket connection in html In vertx example websocket url hardcoded in html as localhost:
 socket = new WebSocket("ws://localhost:8080/myapp");

Which is the correct, "production" way for specifying the remote address in html, especially in vertx?

A: This is not specific to Vert.x at all, but you can use window.location.host to get the current (page) host:
socket = new WebSocket("ws://" + window.location.host + "/myapp");

A: Based on environment you can load websocket :
 if(location.origin.includes("localhost")){
       this.wsUrl = "http://localhost:8080/myapp";
    }else{
      this.wsUrl = location.origin +"/myapp";
    }

   socket = new WebSocket(this.wsUrl);

you can use sockjs-client to open websocket : sockjs-client
Have a look at this example .
I hope this will help you :)