text:
Q: Can Service Fabric State be replicated across Partitions and/or Clusters? Can Service Fabric partitioning be used to actively manage the geographical location of subsets of the application state? I want to make sure a given partition is deployed within a specific region only.

A: If you're using an Azure based cluster, it uses Storage Accounts to store the Virtual Machines' disks, which contain the Service Fabric state.
Storage Accounts can be configured to store data redundantly in one (LRS) or two (GRS) Azure Regions.
You control where your Storage Accounts are created, so you decide where your data will be stored.

A: If you're using Service Fabric to maintain application state, then you can not duplicate that state across multiple Service Fabric Clusters. This applies to hosting multiple Azure Service Fabric Clusters both on-premises as well as in the same or multiple Azure Regions.
It is my understanding that the state within a Service Fabric Partition is not shared or sharable between multiple partitions.

A: If you have an Azure Service Fabric cluster that spans multiple Azure Regions (most people don't) then you can constrain or optimize the location of a particular named service instance via placement policies.
The options are:

*

*Invalid domains

*Required domains

*Preferred domains

*Disallowing replica packing

Example snippet:
ServicePlacementInvalidDomainPolicyDescription invalidDomain = new ServicePlacementInvalidDomainPolicyDescription();
invalidDomain.DomainName = "fd:/DCEast"; //regulations prohibit this workload here
serviceDescription.PlacementPolicies.Add(invalidDomain);

Grab your favorite reflector and look at the things that derive from ServicePlacementPolicyDescription


text:
Q: ZF2 is not letting me make anchor tag in a string CODE
 $responeHTml .= '
 url("delete-export-rt", array("sid" => $sid, "row"=>$var->export_history[$i]["id"])).'>

Delete

error

Catchable fatal error:  Object of class Zend\Mvc\Controller\Plugin\Url could not be converted to string

A: You are using controller helper and not view helper as you think you are.
By calling $this->url(); in controller you get the helper instance. Then you should call fromRoute method to get the url.
$this->url()->fromRoute("delete-export-rt", array("sid" => $sid, "row"=>$var->export_history[$i]["id"]))

This is the plugin you're trying to use.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Factors of a number? I'm studying for the SAT on collegeboard.org, and I came across the problem: What is the least positive integer that has the same number of positive factors as 175?
The answer was 12, explained as:
The number 175 is equal to 5 x 7 x 5. It has a total of 6 positive factors: 1, 5, 7, 25, 35, and 175. The numbers with 6 positive factors are of the form$p_1^2*p_2$or$p^5$. The least number of the first form is 12. The least number of the second form is 32. Thus, the answer is 12, which has the  positive factors 1, 2, 3, 4, 6, and 12.
I've never learned anything about the number of factors for a number, so this line: The numbers with 6 positive factors are of the form$p_1^2*p_2$or$p^5$ doesn't make sense to me. Out of context, I understand that $p_1$ is 2, but I don't understand where those two formulas came from or what p is supposed to be the set of.

A: $p_1$, $p_2$, and $p$ in your quote stand for primes - arbitrary primes. That is, if $p$ is any prime whatsoever, then $p^5$ has exactly 6 factors; and if $n$ has exactly 6 factors, then either $n=p^5$ for some prime $p$, or $n=p_1^2p_2$ for some primes $p_1$ and $p_2$. Everything rests on a formula for the number of factors: if $$n=p_1^{a_1}p_2^{a_2}\cdots p_r^{a_r}$$ where the $p_i$ are distinct primes and the $a_1$ are positive integers, then the number of factors of $n$ is $$(a_1+1)(a_2+1)\times\cdots\times(a_r+1)$$
You can find this explained in any good introductory number theory textbook.

A: I'll try to approach this from a layman's perspective, shying away from the $p_1^{a_1}$ notation in favor of a more conversational approach...
Note: When they say "factor", they mean what most of us would call "divisor". I might switch between the two without warning.
We have a few tasks. The first is to determine the number of positive divisors of $175$. We could just list and then count them (and if you have to do this at most one time on the SAT, then this might be your best bet...) to arrive at $1, 5, 7, 25, 35, 175$. This much you could do.
On the other hand, we could look at the prime factorization of $175$ as $5^2 \cdot 7^1$ and determine how many divisors we could make from these numbers. Since a prime that divides $175$ must be among the primes in $175$, we can only choose combinations of powers of $5$ and of $7$. Since a divisor of $175$ can't be bigger than $175$, we can't make the exponents bigger than what we have in $5^2 \cdot 7^1$ (so the max exponent of $5$ is $2$ and the max exponent of $7$ is $1$). Note that $0$ is the smallest exponent of a prime that we can use.
So we choose a power of $5$ and a power of $7$ and multiply them together to get a divisor of $175$ ... only if the exponent of $5$ is $0, 1, 2$ and the exponent of $7$ is $0, 1$. There are three choices for our first exponent and two for our second exponent, leaving us with $3 \cdot 2 = 6$ divisors. The divisor $1$ corresponds to taking both exponents to be zero; the divisor $175$ corresponds to taking both exponents to be as large as possible (as outlined above).
This is where Gerry gets the formula for "number of factors". The most the exponent of a certain prime can be is just whatever that exponent is in the number we're inspecting ($175$ up till now). But it could also be as low as zero, so there are (exponent + 1) options for each prime. Multiplying these together gives us the total number of factors/divisors.

Once we have the number of divisors ($6$ in our example), we need to find the divisors of this number! Since $6 = 1 \cdot 6 = 2 \cdot 3$, we either multiplied together one and six, or two and three in the above calculation of the number of divisors of the original number ($175$). If it was one and six, then we had an exponent of $5$ (since this is $6 - 1$) for our prime. If it was two and three, then we had exponents of $1$ and $2$ for our primes. Keep in mind that we don't know what these primes are yet.
But if we take the smallest possible primes, we could have $2^5$ (for the case of one prime to the fifth power), $2^1 \cdot 3^2$ or $2^2 \cdot 3^1$ for the case of one to the first power, one to the second power). The smallest of these three numbers is $12$.

Now for a more involved example, in hopes that you can generalize from here, incorporating the other answers:

What is the least positive integer that has the same number of positive factors as 2048?

Since $2048 = 2^{11}$, there are $11 + 1 = 12$ positive divisors/factors of $2048$. So we want the smallest positive integer $n$ that has $12$ positive divisors.
But when we factor $12$, it gets a little more complicated!
For $12 = 12 \cdot 1$, we have $n = $ (some prime to the eleventh power, which we already know is) $2^{11}$.
For $12 = 2 \cdot 6$, we have $n = p^1 \cdot q^5$, the smallest two being $2 \cdot 3^5$ and $3 \cdot 2^5$.
For $12 = 3 \cdot 4$, we have...
But there's one more!
For $12 = 2 \cdot 2 \cdot 3$, we could have $p^1 \cdot q^1 \cdot r^2$. I won't belabor this further, but you can see that the number of candidates for smallest $n$ grows rapidly.

A: This seems a little hard for the SATs.  I assume there were multiple choices?  This might have been one case where you might have tried working backwards, counting the factors of each answer starting with the least.


text:
Q: how to connect to web host mysql db from localhost I have a problem to connect to my webhost MYSQL from my localhost.
I have a host (www.printcity24.com) with mysql db and I use this code to connect to mysql db :
<?php
    $db_path = mysqli_connect('printcity24.com', 'myuser', 'mypass', 'mydb', '3306');
    if(!$db_path) {
        echo mysqli_connect_error();
    }else{
        echo "Connected successfully";
    }

?>

when i call this code from printcity24.com every thing is OK and connect to mysql db successfully.
but i created a localhost by xampp on my computer and when i call this code i got this error :

Warning: mysqli_connect(): MySQL server has gone away in C:\Program
  Files\XAMPP\htdocs\index.php on line 2
Warning: mysqli_connect(): (HY000/2006): MySQL server has gone away in
  C:\Program Files\XAMPP\htdocs\index.php on line 2 MySQL server
  has gone away

I talk to my web host admin and opened 3306 port on my host and added % to Manage Access Hosts on CPanel > remote MYSQL
but i still have problem to connection.


text:
Q: Show snapshots from camera Flex I created a flex application that snapshot a picture of the webcam. Im trying now to save every snapshop and display it directly when the image has been capture. But I cant seems to understand how to.
I want the images to be display in the Thumbnail box.
 Any help ? or any sites I can found some help on ?
This is what I have for the moment
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="top"
                horizontalAlign="center" paddingTop="0" viewSourceURL="srcview/index.html">
    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;
            import mx.core.UIComponent;

            private function videoDisplay_creationComplete() : void
            {
                var camera:Camera = Camera.getCamera();

                if (camera)
                {
                    videoDisplay.attachCamera(camera);
                }
                else
                {
                    Alert.show("Oops, we can't find your camera.");
                }
            }

            private function capture_click() : void
            {
                var snap:BitmapData = new BitmapData(320, 240, true);
                var snapBmp:Bitmap = new Bitmap(snap);

                snapBmp.width = 320;
                snapBmp.height = 240;

                if(snapshotHolder.numChildren > 0)
                    snapshotHolder.removeChildAt(0);

                snapshotHolder.addChild(snapBmp);
                snap.draw(videoDisplay);
            }
        ]]>

    </mx:Script>
    <mx:HBox>
        <mx:Panel title="Video">
            <mx:VideoDisplay id="videoDisplay" creationComplete="videoDisplay_creationComplete();" width="320" height="240" />
        </mx:Panel>

        <mx:Panel title="Snapshot">
            <mx:UIComponent id="snapshotHolder" width="320" height="240" />
        </mx:Panel>

    </mx:HBox>
    <mx:HBox>
        <mx:Button label="reload camera" click="videoDisplay_creationComplete();"/>
        <mx:Button label="capture" click="capture_click();"/>
    </mx:HBox>

    <mx:HBox>
        <mx:Panel title="Thumbnails">
        <mx:UIComponent id="snapshotHolderTN" width="128" height="96" />
        </mx:Panel>
    </mx:HBox>

</mx:Application>

A: Pls try with this when u click for image snaps.
     var bmp:BitmapData = new BitmapData(videodisplay.width,videodisplay.height);
     bmp.draw(drawArea);

     var jpgEncode:JPEGEncoder = new JPEGEncoder(50);
     var imageByte:ByteArray = jpgEncode.encode(bmp);

     var fileRef:FileReference = new FileReference;
     fileRef.save(imageByte);


text:
Q: Calculate $\int_0^1\ln{(\sqrt{1+x}+\sqrt{1-x})}dx$ I am looking for the fastest possible way to calculate:
$$\int_0^1\ln{(\sqrt{1+x}+\sqrt{1-x})}dx$$
The integral appeared on an integration bee where only a few minutes are given to calculate it, so please do not hesitate to use shortcuts in your solution, even if they involve advanced mathematics. Thank you in advance.

A: Note
$$ (\sqrt{1+x}+\sqrt{1-x})^2=2(1+\sqrt{1-x^2})$$
and so
\begin{eqnarray}
&&\int_0^1\ln(\sqrt{1+x}+\sqrt{1-x})dx\\
&=&\frac{1}{2}\int_0^1\ln\left[2\left(1+\sqrt{1-x^2}\right)\right]dx\\
&=&\frac{1}{2}\ln2+\frac12\int_0^1\ln\left(1+\sqrt{1-x^2}\right)dx\\
&=&\frac{1}{2}\ln2+\frac12\int_0^{\pi/2}\ln(1+\cos t)d\sin t\\
&=&\frac{1}{2}\ln2+\frac12\bigg[\ln(1+\cos t)\sin t\bigg|_0^{\pi/2}+\int_0^{\pi/2}\frac{\sin^2t}{1+\cos t}dt\bigg]\\
&=&\frac{1}{2}\ln2+\frac12\int_0^{\pi/2}(1-\cos t)dt\\
&=&\frac{1}{2}\ln2+\frac12\left(\frac{\pi}{2}-1\right)\\
\end{eqnarray}

A: Hint:
$$\int_0^1\ln{(\sqrt{1+x}+\sqrt{1-x})}dx=\int_0^1\ln\sqrt{1+x}\left({1+\dfrac{\sqrt{1-x}}{\sqrt{1+x}}}\right)dx$$
and  after separation for second integral let $x=\cos2t$.

A: $\begin{align}J=\int_0^1\ln{(\sqrt{1+x}+\sqrt{1-x})}dx\end{align}$
Perform the change of variable $\displaystyle y=\frac{1-x}{1+x}$,
$\begin{align}J&=\ln 2\int_0^1 \frac{1}{(1+x)^2}\,dx-\int_0^1 \frac{\ln(1+x)}{(1+x)^2}\,dx+2\int_0^1 \frac{\ln(1+\sqrt{x})}{(1+x)^2}\,dx\\
&=\ln 2\left[\frac{-1}{1+x}\right]_0^1+\left(\left[\frac{\ln(1+x)}{1+x}\right]_0^1-\int_0^1\frac{1}{(1+x)^2}\,dx\right)+2\int_0^1 \frac{\ln(1+\sqrt{x})}{(1+x)^2}\,dx\\
&=\left(-\frac{\ln 2}{2}+\ln 2\right)+\frac{\ln 2}{2}+\left[\frac{1}{1+x}\right]_0^1+2\int_0^1 \frac{\ln(1+\sqrt{x})}{(1+x)^2}\,dx\\
&=\ln 2-\frac{1}{2}+2\int_0^1 \frac{\ln(1+\sqrt{x})}{(1+x)^2}\,dx\\
&=\ln 2-\frac{1}{2}+2\left(\left[-\frac{\ln(1+\sqrt{x})}{1+x}\right]_0^1+\int_0^1\frac{1}{2(1+x)(1+\sqrt{x})\sqrt{x}}\,dx\right)\\
&=-\frac{1}{2}+\int_0^1\frac{1}{(1+x)(1+\sqrt{x})\sqrt{x}}\,dx\\
\end{align}$
Perform the change of variable $\displaystyle y=\sqrt{x}$,
$\begin{align}J&=-\frac{1}{2}+\int_0^1\frac{2}{(1+x^2)(1+x)}\,dx\\
&=-\frac{1}{2}+\int_0^1\left(\frac{1}{1+x}+\frac{1}{1+x^2}-\frac{x}{1+x^2}\right)\,dx\\
&=-\frac{1}{2}+\Big[\ln(1+x)\Big]_0^1+\Big[\arctan x\Big]_0^1-\frac{1}{2}\Big[\ln(1+x^2)\Big]_0^1\\
&=-\frac{1}{2}+\ln 2+\dfrac{\pi}{4}-\frac{1}{2}\ln 2\\
&=\boxed{\dfrac{\pi}{4}+\frac{1}{2}\ln 2-\frac{1}{2}}
\end{align}$

A: First note that $\sqrt a+\sqrt b=\sqrt{a+b+2\sqrt{ab}}$ and then rewrite the integral as
$$\int \ln(\sqrt{1+x}+\sqrt{1-x})dx=\int \ln \left(\left(2+2\sqrt{1-x^2}\right)^{1/2}\right)dx$$
$$=\frac{1}{2}\int \ln\left(2+2\sqrt{1-x^2}\right)dx$$
Substitute $x=\sin t \implies dx=\cos t dt$
$$=\frac{1}{2}\int \ln(2+2\cos t)\cos t dt$$
This can easily be integrated by parts:
$$=\frac{1}{2}\ln(2+2\cos t)\sin t-\int\frac{-\sin^2 t}{2+2\cos t}dt$$
$$=\frac{1}{2}\ln(2+2\cos t)\sin t-\int \frac{(\cos t+1)(\cos t-1)}{2(1+\cos t)}dt$$
$$=\frac{1}{2}\ln(2+2\cos t)\sin t-\frac{1}{2}\int(\cos t-1)dt$$
$$=\frac{1}{2}\ln(2+2\cos t)\sin t+\frac{t-\sin t}{2}+C$$
When evaluating the original integral, remember to change integration limits to $0\to\pi/2$.


text:
Q: Is it possible to write to a remote file via FTP in iOS? My application (which I'm trying to speed up) currently creates a local temp file and FTP uploads it to an ftp site.  Is there functionality to allow me to open a remote file on the FTP and write to it directly?  I believe android supports this.
Also if somebody could point me to a library/sample code that would be awesome.

A: CFWriteStreamCreateWithFTPURL() (see "CFFTPStream Reference") can be used to write data to a remote FTP file.
Apple provides the SimpleFTPSample sample project which demonstrates how to use CFFTPStream.


text:
Q: What does "on-line" mean, as used in man(1)? On my system (Darwin 15.5.0), man(1) opens as follows:
NAME
       man - format and display the on-line manual pages

The file the page is formatted from, however, is clearly on disk:
% man -w man
/usr/share/man/man1/man.1
% file `man -w man`
/usr/share/man/man1/man.1: troff or preprocessor input text

So, "on-line" in this case does not mean "online," as in, "somewhere else accessible over the Internet."
Does "on-line" just mean that my system is powered on?  If so, why bother specifying that in the first place, i.e., isn't it obvious that I'm reading a page that the formatter processed?  Or, when the description was written, was it a huge deal to have a manual on disk because most "manuals" then were paper volumes?  Is this usage of "on-line," hyphen and all, still common in computing?

A: In contrast to a printed (hard-copy) manual, which you could read off-line (while not using a computer).
The term dates back (at least) to time-sharing systems.  Users may have had a terminal which could be used for typing text, punching paper tapes.  But they were only able to use the computer when they were on-line (the "line" referring to the communications link from the terminal to the computer).
Lots of English is that way: you likely use terms which on reflection you might not consider up-to-date.

A: The word "on-line" is used in the sense "operating under the direct control of, or connected to, a main computer."  Reading a manual "on-line" is therefore the same as reading it "on the computer".
This is in contrast to "off-line" in the sense "operating independently of, or disconnected from, an associated computer." Reading a manual "off-line" is therefore the same as reading it by some other means, probably on paper (or asking the in-house wizard who knows every manual by heart).

A: Indeed in this context "online" means "on a computer" as opposed to printed on paper.
Source:  I was responsible for getting new versions of those manuals printed and reproduced at the MIT Lab for Computer Science back in the 70s.


text:
Q: Can a table have a value associated to IT? Kind of like a static variable in an analogy to classes.
For example, lets say i have a table for keeping people. Then for each row I have a bunch of columns: age, sex, name...
But I would like a value to be associated to the table itself, lets say, minimum allowed age = 18. Then, whenever I would add a new person I would check if their age is bigger than Table.minimum_allowed_age. This way I could easely change that value, without beign hard coded anywhere.
The only way I can do it now is by creating a (very ugly) ENUM column that has only one option, 18, and then every row has it. This is obviously not the way to do it, especially if you want to change that value often (which is my case in my application).

A: Not really. Some database servers let you attach a few bits of metadata to a table (e.g, the AUTO_INCREMENT value in MySQL, or the COMMENT field in various SQL databases), but they are not suitable for general-purpose data storage.
In your case, the value that you're describing (minimum allowed age) isn't a property of the table at all -- it's a property of your application logic. If it's going to be constant over the long term, write it as a constant in your code; if it will be changed more often, create a separate table which stores configuration key/value pairs for the whole application.

A: Static variables are technically globals. How about using another table to store global properties?
A string for the primary key, another string that is CAST to an integer in a nested query fetching the value would work.
You might as well use an integer value if sufficient or several, differently-typed maybe-NULL columns if you want type safety (you may COALESCE and CAST the result to a string for a fully generic string->string view).
For globals that are associated with tables you could establish an appropriate convention, e.g. prefixing the key with the table name and some separator.

A: You can try writing insert triggers. Inside the trigger code,you can check if the minimum age is 18 and if not, you can set it to 18.


text:
Q: PostgreSQL pg_restore error from pgadmin4 showing role doesn't exist I am trying to restore a database from one schema to another schema in postgresql using pgadmin backup and restore utility. The backup is successful for the database A but when I try to do the restore of this to another database B I get the error as shown below.
Do anyone know about this or have faced an issue like this before?
I tried changing the restore options like

*

*Do not save owner as yes

*Privileges yes etc but still there was no luck.

Sample:

pg_restore: creating TABLE "public.app_role" pg_restore: [archiver
  (db)] Error from TOC entry 227; 1259 197811 TABLE app_role schedule
  pg_restore: [archiver (db)] could not execute query: ERROR: role
  "schedule" does not exist Command was: ALTER TABLE public.app_role
  OWNER TO schedule;

Thanks

A: In PostgreSQL, users and tablespaces are not part of the database, so they are not included in pg_dump output.
You'll have to run pg_dumpall -a to get a dump of these objects. Apply that dump first, then it should work.
Alternatively, use the options -O -x of pg_restore to skip restoring ownership and permissions. Then the objects will belong to the user who ran pg_restore.


text:
Q: Why is every fiber bundle over $S^1$ a mapping torus? Let $f:X\to X$ be a homeomorphism. Consider the mapping torus $T_f=X\times I/(x,0)\sim (f(x),1)$ for $x\in X$. Then $X\to T_f\to S^1$ is a fiber bundle. I can see this.

Every fiber bundle over $S^1$ is a mapping torus.

The above statement was said as a side note in the class. I tried to prove it but I'm quite new in this subject. I can't see any reference of the above statement on Google. Could you help?

A: Despite what was said in comments, I don't think that homotopic properties such as the homotopy extension property are going to be enough for us here, because we need to use that we have a fiber bundle (and not merely a fibration) in an essential way. Instead we'll use the fact that fiber bundles over a contractible base are trivial, proved perhaps on this site and e.g. this is Corollary 1.8 on p21 of Hatcher's VBKT (note that this is stated for vector bundles, but Hatcher remarks that the same proof for fiber bundles is fine).
If you're comfortable with the definition of a mapping torus and the basic construction below then I think you'd be safe saying that your question is a "trivial corollary" of this result about fiber bundles, but we're going to check everything very carefully.

To begin, let's think of $S^1$ as a quotient of $I = [0, 1]$ with $p : I \to S^1$ the quotient map and let $\pi : E \to S^1$ be a fiber bundle. Let $s_0 := p(0) \in S^1$ be a basepoint. We can then build the pullback bundle $p^* \pi : p^* E \to I$, and remember the associated bundle map $\widetilde{p} : p^* E \to E$ for later. Since $p^* \pi$ is a fiber bundle over a contractible base it is trivial, so let $\phi(t, x) : p^* E \to I \times F$ be a bundle isomorphism with $F := \pi^{-1}(s_0)$ a standard fiber. Then we can build the composite
$$
f : \pi^{-1}(s_0)
\xrightarrow{(\widetilde{p}\rvert_{(p^*\pi)^{-1}(0)})^{-1}} (p^* \pi)^{-1}(0)
\xrightarrow{\phi^{-1}} \{0\} \times F
\to \{1\}\times F
\xrightarrow{\phi} (p^* \pi)^{-1}(1)
\xrightarrow{\widetilde{p}} \pi^{-1}(s_0).
$$
Every map in this composite is a homeomorphism, so the entire composite is as well.
(The intuition is that this map: fixes an element $x$ of the fiber $F$ above $s_0 \in S^1$, chops the $S^1$ to get a fiber bundle over $I$, then "untwists" the bundle, pushes $x \in F$ from above $0 \in I$ in $I \times F$ to now sit above $1 \in I$---which essentially does nothing---then retwists the bundle and glues it back together. We return to a point in the fiber above $s_0$, but we need not have gotten $x$ back. Allowing $x \in F$ to vary in this procedure yields a homeomorphism $F \to F$.)
With the map $f : F \to F$ in hand, it remains to show that $\pi : E \to S^1$ is isomorphic to $M_f$. But this isn't so bad: by definition $M_f$ is a quotient of $I \times F$, so upon composing with the quotient map $q : I \times F \to M_f$ we have a bundle map $p^* E \xrightarrow{\phi} I \times F \xrightarrow{q} M_f$ which is a fiberwise isomorphism. This composite descends to a map $E \to M_f$ now over the same bases, hence an isomorphsim of fiber bundles, exactly when for all $y_1, y_2 \in p^* E$ such that $\widetilde{p}(y_1) = \widetilde{p}(y_2)$ we have $(q \circ \phi)(y_1) = (q \circ \phi)(y_2)$. (Don't forget the map $\widetilde{p} : p^* E \to E$ from the beginning, and if you like the condition we are checking is just the universal property of quotients.)
So, if we write $y_1 = (t_1, z_1) \in I \times E$ and $y_2 = (t_2, z_2)$ similarly then $\widetilde{p}(y_1) = \widetilde{p}(y_2)$ just says $z_1 = z_2$ and $p(t_1) = p(t_2)$. Obviously if $t_1 = t_2$ there is nothing to check, and the only way that $t_1 \not = t_2$ is if one is $0$ and the other is $1$. WLOG we can assume $t_1 = 0$ and $t_2 = 1$, in which case the elements $\phi(y_1) = \phi(0, z_1) = (0, x_1)$ and $\phi(y_2) = \phi(1, z_1) = (1, x_2)$ of $I \times F$ become equal in the quotient defining $M_f$ exactly when $f(x_1) = x_2$. But following the successive composites defining $f$ we trace out
$$
x_1 \mapsto (0, x_1) \mapsto \phi^{-1}(0, x_1) = y_1 \mapsto y_2 \mapsto \phi(y_2) = (1, x_2) \mapsto x_2,
$$
exactly as desired. This completes the proof.


text:
Q: How to limit page pagination I'm looking for a way to show only 15 pages in a category. I have around 50 pages, but I don't want the old pages to be accessible. Only the first 15 pages. How to achieve that?
Thank you!


text:
Q: How to make purchase order number optional in checkout page magento 2.3 Is there any way to make purchase order optional in checkout page??

A: I had to this very same thing today - you need to remove the validation from the input itself as described above by localising;
/m2root/app/design/frontend/NameSpace/Theme/Magento_OfflinePayments/web/template/payment/purchaseorder-form.html

Change;
<input type="text"
                           id="po_number"
                           name="payment[po_number]"
                           data-validate="{required:true}"
                           data-bind='
                            attr: {title: $t("Purchase Order Number")},
                            value: purchaseOrderNumber'
                           class="input-text"/>

To;
<input type="text"
                           id="po_number"
                           name="payment[po_number]"
                           data-validate="{required:false}"
                           data-bind='
                            attr: {title: $t("Purchase Order Number")},
                            value: purchaseOrderNumber'
                           class="input-text"/>

That gets you passed client-side javascript validation, but you additionally need to override the validation function in model class;
Magento\OfflinePayments\Model\Purchaseorder

Use a plugin.  In your custom modules /etc/di.xml file add;
<type name="Magento\OfflinePayments\Model\Purchaseorder">
    <plugin name="purchase_order_validate" type="ModuleNamespace\ModuleName\Plugin\Model\Purchaseorder" />
</type>

Then create the file
ModuleNamespace\ModuleName\Plugin\Model\Purchaseorder.php

With this - note I've added a helper class in as in my instance I need to make it required based on a customer attribute - you can leave that bit out if you dont need it.
namespace ModuleNamespace\ModuleName\Plugin\Model;
use Magento\Framework\Exception\LocalizedException;

class Purchaseorder {

protected $cHelper;

public function __construct(
    \ModuleNamespace\ModuleName\Helper\Customer $cHelper
) {

    $this->cHelper = $cHelper;
}

public function aroundvalidate($subject,$proceed)
{

    // Use whatever function you want if you want to conditionally make PO number required
    $needsValidation = $this->cHelper->getIsPoNumRequired();
    if(!$needsValidation) {
        // Validation avoided here
        return $this;
    }

    // Still here?  You will get empty PO number validation then
    if (empty($subject->getInfoInstance()->getPoNumber())) {
        throw new LocalizedException(__('Purchase order number is a required field.'));
    }

    return $this;
  }

}

A: You can edit below file to make Purchase Order Number optional
copy

mage2root/vendor/magento/module-offline-payments/view/frontend/web/template/payment/purchaseorder-form.html

to

app/design/frontend/{Package}/{theme}/Magento_OfflinePayments/web/template/payment/purchaseorder-form.html

in the above file, you need to remove data-validate="{required:true}" from input box.
After that you need to clear cache, Remove static content and if in production module, deploy content

A: I know this is an old question, but the problem is still relevant. The backend validation in the above answers don't seem to work anymore with M2.4.3 (at least not with me). I wish there would be a core configuration option to make it optional, but I guess we will have to make a workaround for now.
After some digging in the M2 source code I made a solution, which is not the prettiest but it works! You will still have to override the template for the frontend validation, please see the other answers for that.
The backend validation of the PO number field takes place in Magento\OfflinePayments\Plugin\ValidatePurchaseOrderNumber
public function beforeSubmit(
    QuoteManagement $subject,
    Quote $quote,
    array $orderData = []
): void {
    $payment = $quote->getPayment();
    if ($payment->getMethod() === Purchaseorder::PAYMENT_METHOD_PURCHASEORDER_CODE
        && empty($payment->getPoNumber())) {
        throw new LocalizedException(__('Purchase order number is a required field.'));
    }
}

So I've overwritten the class in a module and made the method body empty:
namespace CompanyName\OptionalPoNumber\Plugin\Model;

use Magento\OfflinePayments\Plugin\ValidatePurchaseOrderNumber;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\QuoteManagement;

class ValidatePurchaseOrderNumberOverride extends ValidatePurchaseOrderNumber
{
    public function beforeSubmit(
        QuoteManagement $subject,
        Quote $quote,
        array $orderData = []
    ): void {}
}

di.xml:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\OfflinePayments\Plugin\ValidatePurchaseOrderNumber" type="CompanyName\OptionalPoNumber\Plugin\Model\ValidatePurchaseOrderNumberOverride" />
</config>

A: @jrswgtr's answer is not the recommended way to disable the backend logic. Preferences should be avoided if possible. The recommended way would be to disable the plugin in di.xml:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Quote\Model\QuoteManagement">
        <plugin name="validate_purchase_order_number" disabled="true"/>
    </type>
</config>


text:
Q: Só cadastra uma vez e depois para Estou fazendo uma loja virtual de vendas usando HTML/CSS/PHP para o trabalho do curso e estou recebendo o seguinte BUG:
Criei o código para o processamento do cadastro de usuário, quando crio o primeiro usuário dá certo e cria o dado no banco da dados. Funciona tudo lindo, mas quando vou criar outro usuário não dá certo, não cria.
<?php
// Vai incluir/importar a função/método que está no Conexao.php
    include 'Includes\Conexao.php';

// Receber o login, senha, nome, cpf, endereco e telefone
    $login = $_POST["login"];
    $senha = $_POST["senha"];
    $nome = $_POST["nome"];
    $cpf = $_POST["cpf"];
    $endereco = $_POST["endereco"];
    $telefone = $_POST["telefone"];

// Consulta se o login já é existente no banco de dados
    $consulta = mysql_query ("SELECT loginUser FROM usuarios WHERE loginUser = '$login'");
    $linhas = mysql_num_rows ($consulta); // Coloca na variável um valor com a quantidade de linhas encontradas na consulta feita anteriormente

// Se o resultado for verdadeiro, se existir o login no banco de dados, ele retornará uma mensagem e volta para a página Cadastra_User.php
    if ($linhas == 1) // ou true - Se o login existir
    {
        echo "<script> alert ('Login ja cadastrado com algum usuario. Tente novamente!') </script>";
        echo "<script> location.href = ('Cadastra_User.php') </script>";
        exit(); // se for verdadeiro, o fluxo para aqui!
    }
    else // Se o login não existir
    {
        $cadastrar = mysql_query("INSERT INTO usuarios (loginUser, senhaUser, nomeUser, cpfUser, endereco, telefone) VALUES ('$login', '$senha', '$nome', '$cpf', '$endereco', '$telefone')");

        if ($cadastrar == true)
        {
            echo "<script> alert ('$nomeUser cadastrado com sucesso!') </script>";
            echo "<script> location.href = ('Cadastra_User.php') </script>";
            exit(); // se for verdadeiro, o fluxo para e retorna para a página de cadastra_user
        }
        else
        {
            echo "<script> alert ('Ocorreu um erro no servidor. Tente novamente!') </script>";
        }
    }
?>

O que aparece quando eu tento criar um segundo usuário:

A: Geralmente, esse tipo de erro de não conseguir cadastrar mais de um registro numa tabela é ocasionado quando você define uma primary key (por exemplo, no campo id) e esquece de colocá-lo como AUTO_INCREMENT.
O que vai acontecer se você não definí-la como AUTO_INCREMENT é uma inserção de um valor 0 para o campo id, já que você definiu ele como INTEGER. Quando não se tem AUTO_INCREMENT, o valor padrão de uma coluna INTEGER não informada é sempre 0.
Ou seja, você está esperando que o MYSQL incremente para você, mas ele não foi definido para incrementar. Como você definiu id como Primary key, ao inserir o registro, o 0 fica como Primary Key. Se tentar inserir outro registro, ele tentará inserir como 0 novamente, mas isso gerará um erro devido Primary Keys não podem se duplicar.


text:
Q: HTML checkbox - allow to check only one checkbox I have some checkboxes in each row in my table. Each one checkbox has name='myName' because I want to select only one checkbox in each row. But something I'm missing because I'm able to check all of them:

but I want that result:

what am I missing here ?

A: The unique name identifier applies to radio buttons:
<input type="radio" />

change your checkboxes to radio and everything should be working

A: Checkboxes, by design, are meant to be toggled on or off.   They are not dependent on other checkboxes, so you can turn as many on and off as you wish.
Radio buttons, however, are designed to only allow one element of a group to be selected at any time.
References:
Checkboxes:  MDN Link
Radio Buttons:  MDN Link

A:  $(function () {
     $('input[type=checkbox]').click(function () {
         var chks = document.getElementById('<%= chkRoleInTransaction.ClientID %>').getElementsByTagName('INPUT');
         for (i = 0; i < chks.length; i++) {
            chks[i].checked = false;
         }
         if (chks.length > 1)
            $(this)[0].checked = true;
     });
 });

A: sapSet = mbo.getThisMboSet()
sapCount = sapSet.count()
saplist = []

if sapCount > 1:
   for i in range(sapCount):`enter code here`
     defaultCheck = sapSet.getMbo(i)
     saplist.append(defaultCheck.getInt("HNADEFACC"))
   defCount = saplist.count(1)
   if defCount > 1:
      errorgroup = " Please Note: you are allowed"
      errorkey = "  only One Default Account"
   if defCount < 1:
      errorgroup = " Please enter "
      errorkey = "  at leat One Default Account"
else:
   mbo.setValue("HNADEFACC",1,MboConstants.NOACCESSCHECK)

A: $('#OvernightOnshore').click(function () {
    if ($('#OvernightOnshore').prop("checked") == true) {
        if ($('#OvernightOffshore').prop("checked") == true) {
            $('#OvernightOffshore').attr('checked', false)
        }
    }
})

$('#OvernightOffshore').click(function () {
    if ($('#OvernightOffshore').prop("checked") == true) {
        if ($('#OvernightOnshore').prop("checked") == true) {
            $('#OvernightOnshore').attr('checked', false);
        }
    }
})

This above code snippet will allow you to use checkboxes over radio buttons, but have the same functionality of radio buttons where you can only have one selected.


text:
Q: Use Rails 4 Syntax For Associations in Rails 3.2 Is there any way I can support the Rails 4 syntax for defining associations in Rails 3.2?
I currently have the following Rails 4 syntax:
has_many :clients, -> { where("client_type = 'temp'").order("name DESC") }, through: :user

I want my Rails 3.2 app to support that syntax. In essence, it's as if I had written the following in Rails 3.2:
has_many :clients, conditions: "client_type = 'temp'", order: "name DESC", through: :user

Is there a library/gem that enables this support? Any ideas on how to accomplish this?


text:
Q: How to set background color of a View I'm trying to set the background color of a View (in this case a Button).
I use this code:
// set the background to green
v.setBackgroundColor(0x0000FF00 );
v.invalidate();

It causes the Button to disappear from the screen.   What am I doing wrong, and what is the correct way to change the background color on any View?
Thanks.

A: I use at API min 16 , target 23
Button WeekDoneButton = (Button) viewWeeklyTimetable.findViewById(R.id.week_done_button);

WeekDoneButton.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorAccent));

A: mButton.setBackgroundColor(getResources().getColor(R.color.myColor));

A: You can simple use :
view.setBackgroundColor(Color.parseColor("#FFFFFF"));

A: You can simple use :
view.setBackgroundColor(Color.rgb(0, 198, 255));

A: You can set the hex-color to any resource with:
View.setBackgroundColor(Color.parseColor("#e7eecc"));

A: This question talks about changing the background color of a view. In one of the answers, the person explains how to change the background color during runtime. Obviously you are going to look into how to modify other objects on the screen, but this should give you a good start by at least allowing you to modify the background color of the view on button click.

A: Stating with Android 6 use ContextCompact
        view.setBackgroundColor( ContextCompat.getColor(this, R.color.your_color));

A: This works for me
v.getBackground().setTint(Color.parseColor("#212121"));

That way only changes the color of the background without change the background itself. This is usefull for example if you have a background with rounded corners.

A: You made your button transparent. The first byte is the alpha.
Try v.setBackgroundColor(0xFF00FF00);

A: In kotlin you could do it like this:
val backgroundColor = R.color.whatever_color_you_like
view.setBackgroundColor(getColorCompat(backgroundColor))

Where getColorCompat() is an extension function:
/**
 * Extension method to provide simpler access to {@link ContextCompat#getColor(int)}.
 */

 fun Context.getColorCompat(color: Int) = ContextCompat.getColor(this, color)

A: // set the background to green
v.setBackgroundColor(0x0000FF00 );
v.invalidate();

The code does not set the button to green. Instead, it makes the button totally invisible.
Explanation: the hex value of the color is wrong. With an Alpha value of zero, the color will be invisible.
The correct hex value is 0xFF00FF00 for full opacity green. Any Alpha value between 00 and FF would cause transparency.

A: When you call setBackgoundColor it overwrites/removes any existing background resource, including any borders, corners, padding, etc.
What you want to do is change the color of the existing background resource...
View v;
v.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);

Experiment with PorterDuff.Mode.* for different effects.

A: Several choices to do this...
Set background to green:
v.setBackgroundColor(0x00FF00);

Set background to green with Alpha:
v.setBackgroundColor(0xFF00FF00);

Set background to green with Color.GREEN constant:
v.setBackgroundColor(Color.GREEN);

Set background to green defining in Colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="myGreen">#00FF00</color>
    <color name="myGreenWithAlpha">#FF00FF00</color>
</resources>

and using:
v.setBackgroundResource(R.color.myGreen);

and:
v.setBackgroundResource(R.color.myGreenWithAlpha);

or the longer winded:
v.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.myGreen));

and:
v.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.myGreenWithAlpha));

A: For setting the first color to be seen on screen, you can also do it in the relevant layout.xml (better design) by adding this property to the relevant View:
android:background="#FF00FF00"

A:
and what is the correct way to change
  the background color on any View?

On any View? What you have is correct, though you should drop the invalidate() call.
However, some Views already have backgrounds. A Button, for example, already has a background: the face of the button itself. This background is a StateListDrawable, which you can find in android-2.1/data/res/drawable/btn_default.xml in your Android SDK installation. That, in turn, refers to a bunch of nine-patch bitmap images, available in multiple densities. You would need to clone and modify all of that to accomplish your green goals.
In short, you will be better served finding another UI pattern rather than attempting to change the background of a Button.

A: try to add:
setBackgroundColor(Color.parseColor("#FF0000"));

A: view.setBackgroundColor(R.color.primaryColor);

Adds color to previous color value, so i have a different color.
What works for me is :
view.setBackgroundResource(R.color.primaryColor);

A: Let suppose we have a primary color in values=>colors.xml as:
<resources>
    <color name="primary">#FDD835</color>
</resources>

so if we want to use our custom color into setBackgroundColor(@ColorInt int Color) then we just need an annotation @SuppressLint("ResourceAsColor") with constructor/method which will be used as:
    @SuppressLint("ResourceAsColor")
    public _LinearLayout(Context context) {
        super(context);

        // Formatting our layout : )
        super.setBackgroundColor(R.color.primary);

        ....

    }

A: You must pass an int in the argument.
First Example:
view.setBackgroundColor(-500136)

Second Example:
int colorId = R.color.green;

view.setBackgroundResource(colorId);

A: This should work fine: v.setBackgroundColor(0xFF00FF00);

A: I tried all the above ways. But I havent achieve what i need. Here is my try.
If you are using hexcode for color and want to set the color as background of image, then this is the kotlin code.
val bitmap = Bitmap.createBitmap(30, 30, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val colorCode = "#ffffff"
canvas.drawColor(Color.parseColor(colorCode))
mImageViewLogo.setImageBitmap(bitmap)

A: When calling setBackgroundColor on a view you need to set the alpha value to a non-zero value (e.g. 0xFF), otherwise the color will not show up.
TextView tv = (TextView)findViewById(R.id.myTextview);
int rgb = 0xF05922; // Orange
tv.setBackgroundColor(0xFF000000|rgb); // Use bitwise OR to add alpha to RGB value


text:
Q: How to increment a date in a Bash script I have a Bash script that takes an argument of a date formatted as yyyy-mm-dd.
I convert it to seconds with
startdate="$(date -d"$1" +%s)";

What I need to do is iterate eight times, each time incrementing the epoch date by one day and then displaying it in the format mm-dd-yyyy.

A: startdate=$(date -d"$1" +%s)
next=86400 # 86400 is one day

for (( i=startdate; i < startdate + 8*next; i+=next )); do
     date -d"@$i" +%d-%m-%Y
done

A: Just another way to increment or decrement days from today that's a bit more compact:
$ date %y%m%d ## show the current date
$ 20150109
$ ## add a day:
$ echo $(date %y%m%d -d "$(date) + 1 day")
$ 20150110
$ ## Subtract a day:
$ echo $(date %y%m%d -d "$(date) - 1 day")
$ 20150108
$

A: Increment date in bash script and create folder structure based on Year, Month and Date to organize the large number of files from a command line output.
for m in {0..100}
do
    folderdt=$(date -d "Aug 1 2014 + $m days" +'%Y/%m/%d')
    procdate=$(date -d "Aug 1 2014 + $m days" +'%Y.%m.%d')
    echo $folderdt
    mkdir -p $folderdt
    #chown <user>:<group> $folderdt -R
    cd $folderdt
    #commandline --process-date $procdate
    cd -
done

A: There is another way similar to this, may not be as fast as adding 86400 seconds to the day, but worth try -
day="2018-07-01"
last_day="2019-09-18"
while [[ $(date +%s -d "$day") -le $(date +%s -d "${last_day}") ]];do
    echo $i;
    # here you can use the section you want to use
    day=$(date -d "$day next day" +%Y-%m-%d);
done

A: Use the date command's ability to add days to existing dates.
The following:
DATE=2013-05-25

for i in {0..8}
do
   NEXT_DATE=$(date +%m-%d-%Y -d "$DATE + $i day")
   echo "$NEXT_DATE"
done

produces:
05-25-2013
05-26-2013
05-27-2013
05-28-2013
05-29-2013
05-30-2013
05-31-2013
06-01-2013
06-02-2013

Note, this works well in your case but other date formats such as yyyymmdd may need to include "UTC" in the date string (e.g., date -ud "20130515 UTC + 1 day").

A: It is not that easy to increment days. Normally it is done by converting the Gregorian date into a Julian day number. Then you can increment the day. And after that you calculate the Gregorian date. Here is example code:
http://it.toolbox.com/wiki/index.php/Convert_a_date_to_a_Julian_day
http://it.toolbox.com/wiki/index.php/Convert_a_Julian_day_to_a_date


text:
Q: Error in accessing file uploaded file in google colab I upload final_half.sqlite file in google colab. While reading the file it is giving me the error as below. Could anyone tell me how to solve this?
DatabaseError: database disk image is malformed
I uploaded the file in google colab as follows
import pandas as pd
import sqlite3
from google.colab import files
uploaded = files.upload()

I checked the status of the uploaded file
for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))

User uploaded file "final_half.sqlite" with length 7208960 bytes
for name, data in uploaded.items():
  with open('final_half.sqlite', 'wb') as f:
    f.write(data)
    print ('saved file', name)
    con = sqlite3.connect(name)
    print(con)
    sorted_data = pd.read_sql_query("""SELECT * FROM Reviews_half""", con)

Error:
DatabaseError                             Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/pandas/io/sql.py in execute(self, *args, **kwargs)
   1408             else:
-> 1409                 cur.execute(*args)
   1410             return cur

DatabaseError: database disk image is malformed

A: Change these lines
for name, data in uploaded.items():
  with open('final_half.sqlite', 'wb') as f:
    f.write(data)
    print ('saved file', name)
    con = sqlite3.connect(name)

To just
con = sqlite3.connect('final_half.sqlite')

The file is already saved, you don't need to write it again.


text:
Q: Failed in loading csv data to Elasticsearch, translation issue I am trying to import CSV file to elastic file, but it is failed and threw an error

Pipeline aborted due to error {:pipeline_id=>"main",
  :exception=>#,
  :backtrace=>["/usr/local/Cellar/logstash/7.6.1/libexec/vendor/bundle/jruby/2.5.0/gems/logstash-filter-mutate-3.5.0/lib/logstash/filters/mutate.rb:222:in
  block in register'", "org/jruby/RubyHash.java:1428:ineach'",
  "/usr/local/Cellar/logstash/7.6.1/libexec/vendor/bundle/jruby/2.5.0/gems/logstash-filter-mutate-3.5.0/lib/logstash/filters/mutate.rb:220:in
  register'",
  "org/logstash/config/ir/compiler/AbstractFilterDelegatorExt.java:56:in
  register'",
  "/usr/local/Cellar/logstash/7.6.1/libexec/logstash-core/lib/logstash/java_pipeline.rb:200:in
  block in register_plugins'", "org/jruby/RubyArray.java:1814:in
  each'",
  "/usr/local/Cellar/logstash/7.6.1/libexec/logstash-core/lib/logstash/java_pipeline.rb:199:in
  register_plugins'",
  "/usr/local/Cellar/logstash/7.6.1/libexec/logstash-core/lib/logstash/java_pipeline.rb:502:in
  maybe_setup_out_plugins'",
  "/usr/local/Cellar/logstash/7.6.1/libexec/logstash-core/lib/logstash/java_pipeline.rb:212:in
  start_workers'",
  "/usr/local/Cellar/logstash/7.6.1/libexec/logstash-core/lib/logstash/java_pipeline.rb:154:in
  run'",
  "/usr/local/Cellar/logstash/7.6.1/libexec/logstash-core/lib/logstash/java_pipeline.rb:109:in
  `block in start'"],
  "pipeline.sources"=>["/Users/user/Document/Esk-Data/xudaxia.conf"],
  :thread=>"#"}

Below is the conf file
input
{
    file{
    path => ["/test.csv"]
    start_position => "beginning"
    }
}
filter{
    csv{
        separator => ","
         columns => ["comment_time","comment", "id", "video_time"]
       }
    mutate{
        convert => {
            "comment_time" => "date_time"
            "comment" => "string"
            "id" => "integer"
            "video_time" => "float"
      }
    }
}
output{
    elasticsearch{
        hosts => ["localhost:9200"]
        index => "test"
    }
}

test.csv
comment_time         comment        id        video_time
2020/03/22 15:59:41  バイ             a        123.100
2020/03/22 15:59:45  บาย             b        100.100
2020/04/22 15:59:50  ByeBye          c        80.210

can anyone help?

A: According the documentation the option date_time doesn't exist for convert action on mutate plugin - doc here.
However this plugin is used to cast a type into another one, that it isn't your use case. If comment_time is not recognized as date field you should trasform it with date plugin - doc here.
So you should remove this block:
mutate{
    convert => {
        "comment_time" => "date_time"
        "comment" => "string"
        "id" => "integer"
        "video_time" => "float"
  }
}

and replace it with this one:
date {
    match => [ "comment_time", "yyyy/MM/dd HH:mm:ss"
}


text:
Q: Tests repeats the code with Mockito
My tests just repeats the code. For method
public void start(Context context) {
    context.setA(CONST_A);
    context.setB(CONST_B);
    ...
}

I wrote test using Mockito
@Test
public void testStart() throws Exception {
    Context mockContext = mock(Context.class);

    action.start(mockContext);

    verify(mockAction).setA(Action.CONST_A);
    verify(mockAction).setB(Action.CONST_B);
    ...
}

Or for
public void act() {
   state.act();
}

test
@Test
public void testAct() throws Exception {
    State mockState = mock(State.class);
    context.setState(mockState);

    context.act();

    verify(mockState).act();
}

Are such tests useful? Such methods need to be tested and how to test them?

A: In my opinion, you should not try to have a 100% test coverage in general. Having a high test coverage is good, having a perfect coverage is useless and wastes your time. Any method that just sets, gets or delegate work to another method should not be tested, because it will cost you much to write and even more when refactoring. Finally, it won't add more anti-regression value or any help for anyone using your API.
Prefer testing method with real intelligence, risky or sensitive. The cases you submitted are test more Mockito than your own code. This will take build time and won't help you.

A: Personally I don't consider verify() useful at all since it directly tests the implementation instead of the result of your method. This will give you false failures when you change the implementation while the result is still correct.
As to whether this is useful: there is no logic to test so no, it's not particularly useful.

A: According to the comments I left in other answers
public void start(Context context) {
  context.setA(CONST_A);
  context.setB(CONST_B);
  ...
}

should not be tested with Mockito, rather
@Test
public void testStart() throws Exception {
   Context context = new Context();

   action.start(context);

   assertThat(context.getA(), equalTo(Action.CONST_A));
   assertThat(context.getB(), equalTo(Action.CONST_B));
}

Its not much different, but in comparison with verify it can also get true, if start manages to reach this state without calling a setter or getter.


text:
Q: WPF Style Storyboard To Another Objects Value Here I have a button style in appliction resources
<Style x:Key="ClickableText" TargetType="{x:Type Button}">
        <Setter Property="BorderBrush" Value="{x:Null}"/>
        <Setter Property="FontFamily" Value="/Tasks;component/Assets/Fonts/#Abel"/>
        <Setter Property="Background" Value="Transparent" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border Background="{TemplateBinding Background}">
                        <StackPanel VerticalAlignment="Center">
                            <ContentPresenter x:Name="Text" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                            <Rectangle x:Name="Rect1" Width="{Binding ActualWidth, ElementName=Text}" Height="2" Fill="{DynamicResource LightGrey}"/>
                        </StackPanel>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="White"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

In the style I have added a underlining rectangle to the text in the button.
<Rectangle x:Name="Rect1" Width="{Binding ActualWidth, ElementName=Text}" Height="2" Fill="{DynamicResource LightGrey}"/>

I have binded the rectangles width to be the same width as the text so that it adds a underline effect.
I now want to add an effect so that when you hover the button the rectangle reveals by spliting out.
I have got this far by adding this under the trigger tag
<Trigger.EnterActions>
    <BeginStoryboard>
        <Storyboard>
             <DoubleAnimation Duration="0:0:0.300" From="0" To="{Binding ActualWidth, ElementName=Text}" Storyboard.TargetName="Rect1" Storyboard.TargetProperty="Width" />
        </Storyboard>
    </BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
    <BeginStoryboard>
         <Storyboard>
             <DoubleAnimation Duration="0:0:0.300" From="{Binding ActualWidth, ElementName=Text}" To="0" Storyboard.TargetName="Rect1" Storyboard.TargetProperty="Width" />
         </Storyboard>
    </BeginStoryboard>
</Trigger.ExitActions>

I want to link the to and from part of the double animation to the binding I used in the rectangle but it keeps producing errors. How can I do this effect?
I also want to use this as a reusable style I can distribute and keep in Application resources. I have seen other people do this through workarounds in code but am not sure if you can do this in application resources
Any help or guidance is greatly appriciated!!

A: LayoutTransform animation is Better for this effect.
I would do this animation in this way:

<Style x:Key="ClickableText" TargetType="{x:Type Button}">
<Setter Property="BorderBrush" Value="{x:Null}"/>
<Setter Property="FontFamily" Value="/Tasks;component/Assets/Fonts/#Abel"/>
<Setter Property="Background" Value="Transparent" />
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type Button}">
            <Border x:Name="MainBorder" Background="{TemplateBinding Background}">
                <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="2"/>
                    </Grid.RowDefinitions>
                    <ContentPresenter x:Name="Text" Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    <Rectangle x:Name="Rect1" Grid.Row="1" Height="2" Width="{Binding ElementName=Text, Path=ActualWidth}" Fill="LightGray">
                        <Rectangle.LayoutTransform>
                            <ScaleTransform ScaleX="0"/>
                        </Rectangle.LayoutTransform>
                    </Rectangle>
                </Grid>
            </Border>
            <ControlTemplate.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" TargetName="MainBorder" Value="White"/>
                    <Trigger.EnterActions>
                        <BeginStoryboard>
                            <Storyboard>
                                <DoubleAnimation Storyboard.TargetName="Rect1" Storyboard.TargetProperty="(ContentPresenter.LayoutTransform).(ScaleTransform.ScaleX)" From="0" To="1" Duration="0:0:0.2" />
                            </Storyboard>
                        </BeginStoryboard>
                    </Trigger.EnterActions>
                    <Trigger.ExitActions>
                        <BeginStoryboard>
                            <Storyboard>
                                <DoubleAnimation Storyboard.TargetName="Rect1" Storyboard.TargetProperty="(ContentPresenter.LayoutTransform).(ScaleTransform.ScaleX)" From="1" To="0" Duration="0:0:0.2" />
                            </Storyboard>
                        </BeginStoryboard>
                    </Trigger.ExitActions>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Setter.Value>
</Setter>


text:
Q: Webdrivers not working with Selenium (Python) I have tried various SO solutions on going about this.
System Config:

*

*MacOS Catalina

*Python 3.7.6 (Anaconda)

*Selenium 3.141

*Chrome v81, ChromeDriver v81.
Error: Can not connect to the service chromedriver.
I have tried the same with various driver and browers: Gecko/Firefox(Fresh install), Safaridriver/Safar - all with the same error.
The chromedriver, geckodriver are in PATH as well as usr/local/bin.
Code to reproduce:
from selenium import webdriver
chromedriver = '/usr/local/bin/chromedriver'
driver = webdriver.Chrome(chromedriver)

I have also tried various solutions, executable_path=chromedriver and hosts file with localhost 127.0.0.1 entry.
chromedriver by itself runs perfectly, without any issues, it just can't seem to connect to Selenium.
Any help, if possible will be appreciated.
Expected results: Selenium connects to driver
Actual Results: raise WebDriverException("Can not connect to the Service %s" % self.path)
selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service /usr/local/bin/chromedriver
Solutions already tried:

*

*https://stackoverflow.com/questions/41047957/selenium-and-python3-chromedriver-raises-message-can-not-connect-to-the-service

*Chromedriver not working on python selenium

*Python Selenium "Can not connect to the Service %s" % self.path in linux server
And other solutions on SO.

A: While experimenting to make this work, I somehow messed up while creating venv and docker images. Python as a whole got corrupted, along with chrome drivers. Had to reset the system.
That somehow has solved my problem with selenium. If anyone else finds the answer to this bug, be sure to drop your solution.
Until then, this was my update about how I got it working.


text:
Q: How to get the info about the incoming call when the calling party starts We need to get the info about the incoming call when the calling party starts to hear the welcome message from IVR. Could you please advise how can we achieve that.

A: Since you tagged that question with [jtapi] I assume you would like to use it.
You didn't mention where you would like to receive or how to use that information so I can give you only a brief overview.
If you need it in the IVR and it is a Avaya Experience Portal then you just add the CTI integration to your project and use the CTI Call Info node to have access to call data.
Or you can develop custom application in Java with JTAPI. You start monitoring IVR incoming extensions and when a new call is answered you store call data and the IVR script can get this data via web service calls for example.


text:
Q: How can I specify a different directory in my SQL Server connection string? I have the following connection string in my web.config
<add name="xxx"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=xxx;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\xxx.mdf"
providerName="System.Data.SqlClient" />

I have now moved my mdf file from:
C:\K\ST18 Mar 4\WebUx\App_Data\xxx.mdf

to:
C:\K\ST18 Mar 4\xxx.Data.Store\App_Data\xxx.mdf

I tried to put that into the web.config but it will not accept the "C:\" etc.
How can I change my web config so the AttachDBFilename is correct. Note that xxx.Data.Store is a sister
project within the same solution so I want to make my path go up one directory and then down into xxx.Data.Store\App_Data


text:
Q: 'exec' command blocks the running of php script when execute SchTasks I use the following script php to schedule task of archive :
$archive_command = 'SchTasks /Create /SC monthly /MO lastday /TN archive'.date('Y_m').' /TR PHP_BINARY." ".$SCRIPT_DIR.archive.php /M * /ST 23:30';
exec("$archive_command 2>&1");

but when execute SchTasks to recreate the same task it blocks the execution of the php script.
How to avoid this blocking  ?

A: Try with this
pclose(popen("$archive_command 2>&1 &", "r"));

UPDATE:
I have picked this function from another site :
function bgExec($cmd) {
    if(substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen("start /B ". $cmd, "r"));
    } else {
        exec($cmd . " > /dev/null &");
 }
}

A: There is a way to force shell to return immediately by appending ampersand to the command line with popen:
#                            ⇓
popen("$archive_command 2>&1 &", "r");

If this is OK with you, fine. If not, let me know. There is another more complicated way to resolve an issue with starting shell in another thread.


text:
Q: ARC Incompatible types casting I am using a Core Foundations method I borrowed from Apple's useful UIElementUtilities app. The problem is that I wish to update this borrowed method so that it runs under Apple's new Automatic Reference Counting (ARC) system. I have made some progress adapting most of my borrowed methods by inserting the '__bridge' qualifier before variables, however with the method shown below I get the following error after attempting to convert to ARC:  "error: Incompatible types casting 'NSString __strong *' to 'CFTypeRef *' (aka 'const void **) with a __bridge cast". How do I make make an acceptable pointer to the 'actionDescription' buffer so that its contents is recast to an NSString?
+ (NSString *)descriptionOfAction:(NSString *)actionName ofUIElement:(AXUIElementRef)element {

NSString * actionDescription = nil;

AXUIElementCopyActionDescription(element, (__bridge CFStringRef)actionName, (__bridge CFStringRef *)&actionDescription);

return actionDescription;

//return [actionDescription autorelease];

}

A: Interesting question.
In ARC when you assign a reference to a variable ARC needs to know what to do with the previous value of the variable. If the variable is __strong then the old reference needs to be released, if it is __unsafe_unretained it can just discard the old reference, etc. All this happens most of the time without you needing to be concerned.
When you pass a pointer to a variable containing a reference it gets a bit more complicated, ARC needs to know the qualifier on the pointed at variable. Objective-C uses a technique termed pass-by-writeback, which can involve using hidden temporary variables to make sure it all works correctly, for details see Objective-C Automatic Reference Counting. Core Foundation does not have an equivalent of this and this is what is tripping up your conversion.
The solution is to pass the function a pointer to a Core Foundation typed variable and then to the transfer to Objective-C and ARC after the call:
+ (NSString *)descriptionOfAction:(NSString *)actionName ofUIElement:(AXUIElementRef)element
{
   CFStringRef actionDescription = nil;

   AXUIElementCopyActionDescription(element, (__bridge CFStringRef)actionName, &actionDescription);

   return (__bridge_transfer NSString *)actionDescription;
}

Note the use of __bridge_transfer - the Copy in the function name indicates that the returned CFStringRef is owned by the caller and must be released after use, the __bridge_transfer hands that ownership to ARC which will then be responsible for releasing the reference.
HTH


text:
Q: react-router: How does a  render is triggered when route change? Ok so I made an early issue on the react-router github issue tracker about my <Link /> not updating.
https://github.com/reactjs/react-router/issues/3522
After trying to reproduce in a simple example, I realize it doesn't seem to be a bug with react-router. My next potential guilty are either my complicated set-up or just the mix with react-router & react-router-redux.
To continue my investigation, I was looking for help to understand how the Link render method is triggered when the route change since the props don't seem to change. (I'm only looking for the activeStyle to adapt properly)
I actually found a workaround by adding
Link.componentDidMount = () => {
  this.context.router.listen(() => this.setState({}))
}

but I think it would be better to have a clean fix :P


text:
Q: Creating a non-zero-degree sequence by picking from given sequences This question is about cyclic sequences of the digits 1, 2 and 3. We can consider each digit as one vertex of a triangle. Then, each sequence is like a path from 1 to 1 on the triangle. For example, the sequence "12312" is a path that starts at node 1, makes a full trip around the triangle through 2 and 3 back to 1, then goes to 2 and back to 1.
Define the degree of a sequence as the net number of times it surrounds the triangle in the direction 1-2-3. For example, the degree of "12312" is $+1$, the degree of "3213213" is $-2$, and the degree of "1231321" is $0$.
A sequence is called "good" if its degree is non-zero.
Now for the question.
There are three good sequences of the same length. We have to create a new good sequence by picking, for each position, a digit from one of the three sequences. We are not allowed to pick two consecutive digits from the same sequence. Is it always possible to create a new good sequence in this way?
For example, suppose the three good sequences are:

*

*A: 123111  [degree +1]

*B: 111321  [degree -1]

*C: 321111  [degree -1]

Then we can construct a good sequence by picking in the order:

*

*ACACAC

which gives the good sequence:

*

*123111  [degree +1]

Is this always possible?

A: I don't think so.  Consider

*

*A: 123111111

*B: 111123111

*C: 111111123

No matter how you pick digits, every non-1 digit in the resulting sequence is preceded and succeeded by the digit 1, so the degree would be zero.


text:
Q: What is the LCM of a and b if $(a+2 \sqrt{2} )/b$ is the ration of the area of larger circle and smaller circles?

Radius of all four smaller circles is $R$. If the ratio between the
  area of the larger circle and the sum of areas of the smallest circles
  is $(a+2 \sqrt{2} )/b$ then find the LCM of $a$ and $b$.

Source: Bangladesh Math Olympiad 2014 Junior Category
I don't know how to get the ration between the area of the larger circle and sum of the area of the smaller circles. Can anyone help me with a hint or formula so that I can overcome this problem?

A: Draw in the centers and the segments between them:

Now, can you find the distance $OO_1$ between the center of the big circle and the center of one of the small circles, in terms of $R$? Can you get the radius of the big circle from that?

A: Centers of small circles form a square with side $2R$. Diameter of the big circle is $2R+2R\sqrt2$. Radius of the big circle is therefore $R(1+\sqrt2)$. Check jmerry's picture.
Ratio of big circle area and small circles area is:
$$\frac{R^2(1+\sqrt2)^2\pi}{4R^2\pi}=\frac{3+2\sqrt2}{4}=\frac{a+2\sqrt2}{b}$$.
$$b=\frac{4a+8\sqrt2}{3+2\sqrt2}\cdot\frac{3-2\sqrt2}{3-2\sqrt2}$$
$$b=12a-32-\sqrt2(8a-24)$$
$b$ has to be integer and therefore $a=3, b=4.$


text:
Q: Is there a way to auto-generate a JWG file/compile an Openscript file through ANT or some other build automation system? Openscript compiles the source code file along with its assets etc. and generates a .jwg file when saving the script through IDE.
I want an external method to compile the script, thus eliminating the need to open it in Openscript.
Is there a way this could be achieved through Ant or some other build automation software?
P.S.: There is a batch file bundled along with the software (osclti.bat) which achieves the purpose on Windows. I am specifically looking for something on Linux.

A: OpenScript script can only be compiled in Windows. As of 12.3, there is no support to create/compile scripts in Linux.


text:
Q: MySQL: how to subtract an update i need to subtract an mysql update. here is the code:
<?php
session_start();
//=============Configuring Server and Database=======
$host        =    'localhost';
$user        =    'root';
$password    =    '';
//=============Data Base Information=================
$database    =    'login';

$conn        =    mysql_connect($host,$user,$password) or die('Server Information is not Correct'); //Establish Connection with Server
mysql_select_db($database,$conn) or die('Database Information is not correct');

//===============End Server Configuration============

//=============Starting Registration Script==========

$username    =    mysql_real_escape_string($_POST['txtusername']);

//=============To Encrypt Password===================

//============New Variable of Password is Now with an Encrypted Value========

$insert = "UPDATE `users` SET `points` = (`points`-5) WHERE `username` = '".$username."'";
$insert = "UPDATE `users` SET `lodd` = (`lodd` +1) WHERE `username` = '".$username."'";

 mysql_query($insert);

header('location: succes.php');
?>

the +1 work perfect but it dont work to -5... how can i do so that they get -5 points?

A: the +1 work correctly because the query with -5 will never be called as it is overwritten by the query that has +1.
you should have this code, (Although this is not the correct one)
$insert = "UPDATE `users` SET `points` = (`points`-5) WHERE `username` = '".$username."'";
mysql_query($insert);

// other codes

$insert = "UPDATE `users` SET `lodd` = (`lodd` +1) WHERE `username` = '".$username."'";
mysql_query($insert);

follow-up question: what are the dataypes of the two columns? are they unsigned or signed?

A: You're overwriting the first statement with the second.  Try this:
$insert = "UPDATE `users` SET `points` = (`points`-5), `lodd` = (`lodd` +1) WHERE `username` = '".$username."'";
mysql_query($insert);


text:
Q: Generate multiple plots with for loop; display output in matplotlib subplots Objective: To generate 100 barplots using a for loop, and display the output as a subplot image
Data format: Datafile with 101 columns. The last column is the X variable; the remaining 100 columns are the Y variables, against which x is plotted.
Desired output: Barplots in 5 x 20 subplot array, as in this example image:
Current approach: I've been using PairGrid in seaborn, which generates an n x 1 array: .
where input == dataframe; input3 == list from which column headers are called:
for i in input3:
    plt.figure(i)
    g = sns.PairGrid(input,
             x_vars=["key_variable"],
             y_vars=i,
             aspect=.75, size=3.5)
    g.map(sns.barplot, palette="pastel")

Does anyone have any ideas how to solve this?

A: To give an example of how to plot 100 dataframe columns over a grid of 20 x 5 subplots:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

data = np.random.rand(3,101)
data[:,0] = np.arange(2,7,2)
df = pd.DataFrame(data)

fig, axes = plt.subplots(nrows=5, ncols=20, figsize=(21,9), sharex=True, sharey=True)
for i, ax in enumerate(axes.flatten()):
    ax.bar(df.iloc[:,0], df.iloc[:,i+1])
    ax.set_xticks(df.iloc[:,0])

plt.show()

A: You can try to use matplotlob's subplots to create the plot grid and pass the axis to the barplot. The axis indexing you could do using a nested loop...


text:
Q: Moving to a previous statement inside for loop I have a for loop similar to the one given below.
for(int i=0; i<10; i++)
{
   boolean condition = checkCondition();    /* line 3 */

   if(condition)
   {
     if(some other condition A)
     {
       move to line 3;
     }
     else if(some other condition B)
     {
      call_method_B();
     }
     else
     {
      call_method_C();
     }
  }
  else
  {
    call_method_D();
  }
}

How do I make the program go back to line 3 within the if statement as above? I don't want to break the iteration. Needs to be in the same iteration and only need move back to line 3.

A: to be in the same iteration, just subtract i by 1 before you call continue.
do note that this will get you into an infinite loop if the condition is never changed.
for(int i=0; i<10; i++)
{
   boolean condition = checkCondition();    /* line 3 */

   if(condition)
   {
     if(some other condition A)
     {
       move to line 3;
       i--;  //this will cancel out the i++ in the for loop
       continue; //this will bring you back to line 3
     }

     ... the rest of your codes

A:
I don't want to break the iteration. Needs to be in the same iteration and only need move back to line 3.

I think you need a while loop. Then you have more control over when you iterate. When you get the conditionA check, then i doesn't change, and the loop repeats, otherwise you can say i++.
int i = 0;
while (i < 10) {
    if (checkCondition()) {
        if (some other condition A) {
            // continue the iteration
        } else if (some other condition B) {
            call_method_B();
            i++;
        } else {
            call_method_C();
            i++;
        }
    } else {
        call_method_D();
        i++;
    }
}

A: I believe your problem seems to need a recursive approach instead of an iterative approach.
The above problem can be solved using a recursive approach in the following way:
public void checkRecursive()
{
    boolean condition = checkCondition();

    if (base_condition_to_avoid_recursion)
        return;

    if (condition)
    {
        if (some other condition A)
        {
            checkRecursive();
        }
        else if (some other condition B)
        {
            call_method_B();
        }
        else
        {
            call_method_C();
        }
    }
    else
    {
        call_method_D();
    }
}


text:
Q: Padding looks different on Mac than on Windows For some reason, the padding appears different on all windows computers. My icons aren't located properly in the middle nor is the text in my buttons. It is working perfectly on windows.
https://imgur.com/a/3XMkL9N - here is an example picture
See more at: https://cobury.dk/
The CSS/HTML I use:

i.icon-facebook, i.icon-instagram, i.icon-linkedin, i.icon-youtube {
    padding-top: 8px;
    padding-bottom: 8px;
    padding-left: 6px;
    padding-right: 6px;
    border-radius: 99px;
    background: #19191b;
    color: #fff;
    margin-right: 5px;
}

[icon type="icon-facebook"][icon type="icon-instagram"][icon type="icon-linkedin"][icon type="icon-youtube"]

The padding is perfect in Chrome on Windows, but looks weird on both Chrome/Safari on Mac. I am using the same padding top and bottom, as you can see. What am I missing? Is it something about my divs? Line height? A bug?
I am using the paid font Gilroy.


text:
Q: How to log user name with elasticsearch jetty plugin? I am using elasticsearch  jetty plugin in order to log queries , what I want to do is to add just a new log to my actuals logs, that is " the name of the user who made the query".
Can you please tell me if this is possible? And how I can do that ?
Thanks

A: Can log the remoteUser using the "json" option of jetty plugin


text:
Q: Tooltip load error I have this strange issue when it comes to first loading a tooltip in Ubuntu 17.04.  When I do hover, it displays as the following... funky tooltip rendering
Any suggestions of what to do or how to handle this?

A: Are you using Google Chrome? It seems it's an old bug of Google Chrome.
I don't think there is an official way to fix this bug at this moment.
But there are some patches made by users.
See: https://bugs.freedesktop.org/show_bug.cgi?id=90264


text:
Q: How much control did Sidious have over the Clone Wars? Was Sidious able to control exactly every major event that transpired (let's be real, it does sound possible if we're talking about him), exactly how long the war will last and exactly how it will end? Or did he let it develop organically and just intervene when he wishes a certain goal to be achieved but wouldn't happen in the status quo?
Has there ever been any occurrence during the Clone Wars that did not happen as he had foreseen and was serious enough to worry him?

A: In Episode II, Jar Jar is heavily influenced by Palpatine to move a vote on giving the chancellor emergency power. This allows him to create (although it was already created) the clone army and also gives him full control over it. At this point Palpatine is also mostly trusted by the Jedi Council.
If I remember correctly, Darth Sidious also has the Trade Federation and the Separatist Council in his pocket giving him full control of the droid army.
Spoiler alert:

 Palpatine = Darth Sidious

This gives him control of both major sides in the war, so I think it's very reasonable to assume he Darth Sidious was indeed able to control every major event in the war. Since the war essentially ended with order 66, Sidious ended it himself when giving that order.

A: Absolute, or almost absolute is the answer to your question. He obivously wasn't able to direct every micromanagement move but almost. This is realized through four things:
((My answer contains spoilers from this point onwards.))

*

*Separatist Movement - or the Confederacy of Independent Systems:
The separatist movement is comprised of of planets and system under the control of the trade federation(Introduced in EP I, Orbit above Naboo), the Techno Union(Introduced in EPII, Geonosis), the Banking Clan(Introduced in EP II, Geonosis) and many other minor planetary bodies / companies.

What we learn in Episode One is that the Vice Roy of the Trade Federation - Nute Gunray - obivously is under complete control of Darth Sidious - he obeys his will and lets him direct the course of actions taken, obivously thinking he will - somehow - benefit from the pact with the Darth. However, it is obivous to me that he didn't knew what he was getting himself into when he signed said pact as later on when Darth Sidious introduces him and his advisor to Darth Maul who is his apprentience, the both of them discuss:

DARTH SIDIOUS : (Cont'd) ...Viceroy, this is my apprentice. Lord Maul. He
  will find your lost ship.
NUTE : Yes, My Lord. The hologram fades off.
NUTE : (Cont'd) This is getting out of hand...now there are two of them.
RUNE : We should not have made this bargain. What will happen when the Jedi
  become aware of these Sith Lords?

Making this move, Darth Sidious ensures that Darth Maul oversees every move of the vice roy as soon as they meet up with him on Naboo and thus he cannot just cancel their initial agreement and let the Sith down.
-> He ensures the control over the Trade Federation which up to this point is the core of the intended separatist movement
As the events of Episode I unfold, Darth Maul gets killed and the Vice Roy alongside his advisors are arrested and put to trial which, as Darth Sidious influences it this way, is won by them and they are released later on.
What we learn in Episode II is that Count Dooku, now known as Darth Tyranus, left the Order of the Jedi and became the - up to this point - last of the lost jedi. Prior to his, the one way or the other, thats actually not backed by the movie canon, Darth Sidious learns of the clone army that is prepared for the republic by Sifo-Dyas the Jedi Master and sends Darth Tyranus their way to proove his loyality. He kills Sifo-Dyas and ensures the army of the republic is not discovered prior to his own intends by sending him back to Coruscant where he deletes everything concerning Kamino (location of the clone army) including its location after which he leaves Coruscant and the actual Jedi Order to start forming the separatist movement on behalf of Darth Sidious who was busy undermining the republic meanwhile.
Darth Tyranus unites the Banking Clan(Money), the Techno Union(Technology) and the Trade Federation(Ressources) under the banner of the CIS on Geonosis.
Given these three factions make up the bulk of the CIS at first with Darth Tyranus being their obivous leader (I strongly believe that only Nute Gunray and his advisors knew of Darth Sidious at this point and that Darth Tyranus was acting on his behalf.) Darth Sidious ensured absolute control of every movement of said factions.
As the events of Episode II unfold, the clone wars start with an initial defeat of the CIS - the war has started. The war, as we will learn later on, isn't a real war but rather a masterpiece of art.
In Episode III we learn:
Darth Tyranus who was ordered by Darth Sidious orders General Grievous, a Kaleesh cyborg-warlord, to caputre chancellor Palpatine - further distracting people from the assumption that Palpatine might be Darth Sidious (See the clone wars series for a few references as to how the jedi started to actually figure out who Darth Sidious might be over time.). General Grievous, by then defacto 3IC of CIS, knew of Darth Sidious but he didn't knew Palatine = Darth Sidious either. Playing Darth Sidious into the cards, Obi-Wan and Anakin come to "his rescue". Count Dooku gets killed (More on this later.) and Grievous replacing him as 2IC of CIS.
Darth Sidious balanced and directed the war, making it look like every side was close to winning but in fact, no side made real advances. However, with time coming, Darth Sidious fears raised that the Jedi might come behind his secret plot plus he did fear that the CIS might surrender against his will because even General Grievous started to worry about the course of the war. He moved the leaders of the separatist alliance to Mustafar and sacrificies Grievous by telling Anakin about the position of the CIS council, who informs the Jedi Council who sends out Obi-Wan and a large number of clones to eliminate the enemy at once.

A hologram of Darth Sidious appears.
GENERAL GRIEVOUS: Yes, Lord Sidious.
DARTH SlDIOUS: General Grievous, I suggest you move the Separatist leaders >to Mustafar.
GENERAL GRIEVOUS: It will be done, My Lord.
DARTH SlDIOUS: The end of the war is near, General, and I promise you, >victory is assured.
The hologram of Sidious talks to GRIEVOUS about the death of Count Dooku.
GENERAL GRIEVOUS: But the loss of Count Dooku?
DARTH SlDIOUS: His death was a necessary loss, which will ensure our >victory. Soon I will have a new apprentice . . . one far younger and more >powerful than Lord Tyranus.

the fact that Grievous assumed the position of Count Dooku and thus has authority over the council of CIS members (And thus, being Darth Sidious minion, he still has direct control of CIS) is symbolized in the following scene:

GENERAL GRIEVOUS stands before the COUNCIL OF SEPARATISTS, including NUTE >GUNRAY, RUNE HAAKO. POGGLE THE LESSER, SHU MAI, SAN HILL PO NUDO, WAT >TAMBOR, and PASSEL ARGENTE. OBI-WAN hides above the assembly and watches >intently.
GENERAL GRIEVOUS: It won't be long before the armies of the Republic track >us here. I am sending you to the Mustafar system in the Outer Rim. It is a >volcanic planet which generates a great deal of scanning interference. You >will be safe there.
NUTE GUNRAY: Safe? Chancellor Palpatine managed to escape your grip, >General, without Count Dooku. I have doubts about your ability to keep us >safe.
GENERAL GRIEVOUS: Be thankful, Viceroy, you have not found yourself in my >grip . . . Your ship is waiting.

This being said, Darth Sidious ensured the war could go on, if something failed in the last step of his plan.
As the events of Episode II unfold, Grievous gets killed, Darth Sidious reveals his true ambitions to Anakin and Anakin in the end kills the remaining CIS head, informing the CIS forces that they have to immediately surrender to the forces of the Republic.
-> Darth Sidious had complete control of the CIS. From its formation to the end of the faction.

*

*Republic

What we learn in Epsiode I: Palpatine starts his career on Naboo and after some failed elections (Extended Universe information here!) makes it to become Senator of Naboo and is granted a seat in the senate. Once this is done, he starts to influence people his way: He has wisdom and is smart, his old appearance (Which is actually a force mask, more to this later on.) makes it look like he knows what he is doing. By sending the Trade Federation to create the blockade of Naboo and turning in a desire for an investigation on the matter by the senate, he achives two things:
(1) he makes himself known to the senate members
(2) he manages to have Amidala believing the current chancellor was weak and unable to bring a decision in favor of democracy and first and foremost - Naboo. He always tells people that he wants to stop and reduce bureaucracy but infact, he encourages it behind the scenes. During the discussion for the investigation, the Trade Federation representatives do not want the investigation to happen and want to form a commission to check out whats going on in Naboo for real:

AMIDALA : Honorable representatives of the Republic, distinguished
  delegates, and Your Honor Supreme Chancellor Valorum, I come to you under
  the gravest of circumstances. The Naboo system has been invaded by force.
  Invaded...against all the laws of the Republic by the Droid Armies of the
  Trade...
LOTT DOD : I object! There is no proof. This is incredible. We recommend a
  commision be sent to Naboo to assertain the truth.
VALORUM : Overruled.
LOTT DOD : Your Honor, you cannot allow us to be condemned without
  reasonable observation. It's against all the rules of procedure.
A third box representing Malastare moves into the center of the room. AKS
  MOE, the Ambassador, addresses the convention.
AKS MOE : The Congress of Malastare concurs with the honorable delegate
  from the Trade Federation. A commision must be appointed...that is the law.

Obivously the chancellor does not like the idea and wants to object, but a guy, Mas Amedda, who is on the paylist of Darth Sidious by then, steps into it, symbolizing the rule of bureaucrats to Queen Amidala steps in and everything, es seen below is conducted as Darth Sidious wants it to take part:

VALORUM : The point...
VALORUM confers with several of his AIDES and VICE CHAIRMAN MAS AMEDDA.
  PALPATINE whispers something to the QUEEN.
PALPATINE : Enter the bureaucrats, the true rulers of the Republic, and on
  the payroll of the Trade Federation, I might add. This is where Chancellor
  Valorum's strength will dissapear.
VALORUM : The point is conceded...Section 523A take precedence here. Queen
  Amidala of the Naboo, will you defer your motion to allow a commission to
  explore the validity of your accusations?
QUEEN AMIDALA is angry but remains composed.
AMIDALA : (angrily) I will not defer...I have come before you to resolve
  this attack on our sovereignty now. I was not elected to watch my people
  suffer and die while you discuss this invasion in a committee. If this body
  is not capable of action, I suggest new leadership is needed. I move for a
  "vote of no confidence"...in Chancellor Valorum's leadership.
VALORUM : What?...No!

As the events of Episode I unfold, Valorum gets the boot and Darth Sidious replaces him as the supreme chancellor of the republic.
What we learn in Episode II is that Darth Sidious, as chanellor of the republic makes it look like he had no real power in the senate either. By starting the formation of the CIS "by Darth Tyranus" he finds himself a reason to be elected towards emergency rights that allow him to form an army and even more. Just in time, as it appears, to win the battle of Geonosis.
What we learn in Episode III is that Darth Sidious is almostly taking over the entire republic and thus, he is able to coordinate the republics entire course of war. Soldiers are sent out on his recommendations, war is conducted following his course. In the end, as we all know, Palpatine takes over and is applauded by the audiences for doing so.
-> As soon as he claimed the chair of chancellor, he took over the republic completely and there surely was no turning back.
The Jedi
The Jedi do not include his plot in Episode I and II at a large scale, even though his final goal is their annihilation. In Episode I and II, he learns of Anakin and senses his power through the force and slowly lures him over to the dark side, by first pretending to be the father figure he never had in his life and later on planting dark thoughts into his mind.
In Episode III, his plans for the Jedi, namely their destruction unfolds:
The Jedi are used as Generals, against their initial will:

MACE WINDU
  But if they do, you must realise
  there aren't enough Jedi to
  protect the Republic. We are
  keepers of the peace, not soldiers.
And thus loose reputation during the course of the war.
  He also starts to directly influence Anakin. He realizes the last phase of his plan is about to begin when he convinces Anakin to kill Darth Tyranus after he has beaten said Darth:
PALPATINE: Good, Anakin, good. I knew you could do it. Kill him. Kill him >now!
ANAKIN: I shouldn't . . .
PALPATINE: Do it!!
ANAKIN cuts off COUNT DOOKU's head.

After this, Darth Sidious knows its time for Anakin to turn and knowing of his fears for Padme (Because he acutally implanted these visions or at least, made them stronger since he knew about Anakin havin' such visions when his mother died by the Tusken) he found the perfect way. He informed Anakin that Grievous is at Utapau, who in turn informs the Council of the Jedi who send out Obi-Wan Kenobi to finish off Grievous. After Obi-Wan reports to have killed Grievous, the Jedi council see the time come that negotitations should be started with the CIS so that they can surrender because they're left with a military leader - they want the chancellor to give back the emergency rights he gained so that the senate can start the process of peace making.
Remember, the Jedi at this point, as its before Anakin informing them Palpatine = Darth Sidious, didn't know who Darth Sidious was for real, Master Windu was the only person to think he was just evil and still had no clue who Darth Sidious was. So, knowing of the rule of two:

MACE WINDU : There is no doubt. The mysterious warrior was a Sith.
  YODA : Always two there are....no more...no less. A master and an
  apprentice.
  MACE WINDU : But which one was destroyed, the master or the apprentice?

they have suspected by then that Darth Tyranus was the Sith who was either apprentience or master to Darth Maul because, by then, it seemed clear that Darth Tyranus was an evil guy, even wearing the title and name of Darth Tyranus publically.
So, assuming the CIS was without a head, they went up to the office of Darth Sidious and wanted him to give back his power. One their way, Anakin catches up with them and tells them that Palpatine = Darth Sidious. The four Jedi march up to the office and it seems that for a moment, Mace Windu beats Palpatine which is, given all the discussion that arise around this crucial moment, taken as granted not the fact. Palpatine pretends to be beaten JUST the moment Anakin arrives = he could have continiued to fight and kill Mace Windu with as much ease as he killed the other three Jedi but he didn't. Joining the scene, Anakin, meanwhile Darth Sidious' unwilling servant, arrives in time to see Mace deflecting Darth Sidious' lightning and crippling Darth Sidious. Infact, Darth Sidious was crippled before, he used Sith alchemy to build a force mask to conceal his Dark Side crippled body - a mask that was destroyed by the reflected lightning. (As I can see the usual arguments pop up at this place - Look at Luke or Anakin when the get hit with lightning, they obivously have pain and some of their skin might be burned, but lightning does not transform their eyes and their teeths, whilst, in Episode III after killing the younglings, Anakins eyes start to turn and match the ones of Palpatine - so he was clearly wearing a force mask.) Anakin, only caring about Darth Sidious surviving because of Padme, disables Mace who is, in turn, shocked down the window and down to the streets of Coruscant by the "I'm so weak - POWERRRRRRRRRRRRRR! UNLIMITED POWERRRRR!" - Darth Sidious. Resulting in order 66, resulting in the almost anihilation of the Jedi.
-> Palpatine had full control of the Jedi, sent them out where he wanted to, made it look like they're bad and as soon as they noticed his betrayal - it was too late for any reaction.

*

*Spies

The last thing he obivously did was placing spies everywhere. You can rest assured that in each planning room either someone directly answering to him in a way or someone answering to someone who answered to him in a way was placed so that he knew of events long before they unfolded in the war and thus he could manipulate almost everything according to his own desires.


text:
Q: jQuery: display divs with numbers ranging from/to? I'm trying to figure out a way to display divs ranging from/to numbers using a select dropdown list.
I have created this jsfiddle to explain the issue: http://jsfiddle.net/chd836b8/2/
basically, each div has a data-price="" and they have different values in them as you can see in the jsfiddle!
i need to select the price rang from the dropdown list and display the divs accordingly. so far I haven't been able to figure out a way to do this.
Could someone please advise on this issue?
Thanks in advance.

A: You can achieve this by adding data attributes to the option elements that determine the min/max price for that selection:
<select id="priceRange" style="width:101px; height:49px; background:#eeeeee; border-radius:8px;">
    <option data-price-min="0" data-price-max="49">Under 50</option>
    <option data-price-min="50" data-price-max="100">50 - 100</option>
    <option data-price-min="100" data-price-max="250">100 - 250</option>
    <option data-price-min="250" data-price-max="500">250 - 500</option>
    <option data-price-min="500" data-price-max="1000">500 - 1000</option>
    <option data-price-min="1000" data-price-max="9999">Over 1000</option>
</select>

Then in JS, you can read those attributes when the select is changed, and find the relevant .drag elements whose data-price falls between those extents:
$('select').on('change', function () {
    var $option = $(this).find('option:selected');
    var min = $option.data('price-min');
    var max = $option.data('price-max');
    $('.drag').hide().filter(function() {
        var price = $(this).data('price');
        return price >= min && price <= max;
    }).show();
});

Working example

A: First of all, you need to add data-min and data-max to your options:
<select id="priceRange">
<option data-min="0" data-max="49">Under 50</option>
<option data-min="50" data-max="100">50 - 100</option>
<option data-min="100" data-max="250">100 - 250</option>
<option data-min="250" data-max="500">250 - 500</option>
<option data-min="500" data-max="1000">500 - 1000</option>
<option data-max="1000">Over 1000</option>

This will allow you to limit the visible divs later on.
Next you need to perform a
$(".drag").each(function(){
     var price = $(this).data('price');
     //and then check if it fits between min and max to show it
});

A: Try adding data-* attribute to option elements as array of minimum , maximum values , or range to filter .drag elements

$(function() {
  $("select").on("change", function() {
    var range = $(this.selectedOptions[0]).data("range")
    $(".drag").hide().filter(function(i, el) {
      var n = $(this).data().price;
      return !!range[1] ? n >= range[0] && n <= range[1] : n >= range[0]
    }).show();
  }).change();
});

<select id="priceRange" style="width:101px; height:49px; background:#eeeeee; border-radius:8px;">
  <option data-range='[0, 50]'>Under 50</option>
  <option data-range='[50, 100]'>50 - 100</option>
  <option data-range='[100, 250]'>100 - 250</option>
  <option data-range='[250, 500]'>250 - 500</option>
  <option data-range='[500, 1000]'>500 - 1000</option>
  <option data-range='[1000]'>Over 1000</option>
</select>

2

2

4

7

20

40

100

200

200

500

1000

1100

2000

2000

3000