text:
Q: javascript for loop unexpected behaviour I have couple of questions about the javascript for loop.
First question:
for (i=0; i<=2; i++) {;}
console.log(i);

Output is 3. Shouldn't it be 2?
Second question:
for (var i=0; i<=2; i++) {
    setTimeout(function(){console.log(i);}, i*1000);
}

Timeouts are set correctly: 0, 1000 and 2000. But the output is 3,3,3 (should be 0, 1, 2). Does this mean the delayed functions are executed after the loop exits? Why?
What should I read to understand all this mysterious javascript stuff?
Thank you.

A: First question:
No because the i variable is incremented after the last successful iteration, then the condition is checked and it evaluates to false so the loop ends.
The for statement is composed by:
for ([initialExpression]; [condition]; [incrementExpression])
  statement

And it is executed in the following steps:

*

*The initialExpression is evaluated at the start

*The condition is evaluated, if it evaluates to false, the loop ends, if it evaluates to true, the statement is evaluated.

*Evaluate the statement.

*The incrementExpression is evaluated, go to step 2.

Second question:
The function is executed asynchronously after the loop has ended, at this time as you know i contains 3.
The common workaround for this is to use a function to preserve the value of the looping variable on each iteration, for example:
for (var i=0; i<=2; i++) {
  (function (i) {
    setTimeout(function(){console.log(i);}, i*1000);
  })(i);
}

A: That's because your console.log instruction is outside of the for loop.
This will print it up to two as you intended:
for (i=0; i<=2; i++) {
    console.log(i);
}

For loops will only repeatedly execute what you type within the parentheses. That's why console.log was executed only once.
Source: http://www.kompulsa.com/a-guide-to-for-loops-in-javascript/


text:
Q: WCF Security Header Removal I have read countless forum posts and articles on this issue and am still unable to find a solution.
I am running a WCF service with the following binding:
  <customBinding>
    <binding name="BasicBinding">
      <security authenticationMode="UserNameOverTransport" />
      <textMessageEncoding messageVersion="Soap11" />
      <httpsTransport />
    </binding>
  </customBinding>

Everything is working fine and I am locally able to make requests using the appropriate credentials and the response is served as expected. I have just received information from the consuming client that the Soap security header is causing issues for them:
   <s:Header>
     <o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
     <u:Timestamp u:Id="_0">
        <u:Created>2017-12-20T19:17:29.322Z</u:Created>
        <u:Expires>2017-12-20T19:22:29.322Z</u:Expires>
     </u:Timestamp>
  </o:Security>

They inform me that the 'mustunderstand' part is incompatible with their system. I have read that changing to a custom binding will fix it, however as you can see above this has been done and is still showing the security header.
I have read about interceptors and manipulating the response object but I've been unable to see how it all fits together. Has anyone actually solved this problem completely? I am basically looking to remove all header information from the response.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Startup Disk Creator tool for Debian I was trying to create a USB bootable in Debian to install my new system. I couldn't find any easy to use tool in Debian. I tried downloading the hybrid ISO image from the Debian site and copied it to the USB using the dd command as said in Debian site, but it didn't boot.
Next, I used the Startup Disk Creator tool in Ubuntu and it worked like a charm. Is there any similar tool in Debian? I know that there is Unetbootin, but it's difficult to install.

A: For Debian Stretch (9.x) you can use gnome-multi-writer. The interface is a bit confusing (you need to click the [x] button on the left to select ISO) but in the end it does the trick.

A: Solution with cp
I have used the copy (cp) command for this.  It did take me a couple of tries, though. The trick that seemed to make the difference for me was to plug the usb drive in, format it as MBR, but not create any partitions. In Debian (Gnome), this is easy to do from gnome-disks (called simply Disks in the GUI, while the package name is gnome-disk-utility). It can also be done using the gparted GUI program. Of course, you will lose any data currently on the USB drive when you format it.
Then, if your USB drive is /dev/sdd, just issue the copy command in the terminal:
sudo cp debian-xxx-yyy.iso /dev/sdd
So you're copying to a drive (that is unmounted), not to a particular partition. Then in the Disks GUI, when you click on the newly created partition on the USB drive, you should see (Bootable) next to the entry for Partition Type. If not, it may help to do the following:

*

*With the partition selected, click on the Gears icon

*Click Edit Partition...

*Check the Bootable box.

Alternate solution
Another way that has worked for me with bootable Ubuntu iso images is to use the Disks GUI itself:

*

*In the top 'three bars' menu, choose Restore Disk Image...

*Under Image to Restore, choose your .iso file with a double-click

*Make sure the Destination reflects your USB drive

*Click Start Restoring. Upon completion, make sure the new partition is bootable as above.

Notes

*

*The OP's link from the Debian site specifically advises against using unetbootin for this purpose.

*The cp method is officially sanctioned in the Debian docs. They add the command sync after to ensure writing has finished.

A: Unetbootin is a debian package, also available on many other distributions and systems.
It does install an ISO image as a bootable USB drive.

A: You can try MultiSystem or LiveUSB.
Pendrivelinux.com is a very useful resource for this sort of thing.

A: Win32DiskImager, or rufus.
You may find either of these are the below links, respectively:
http://sourceforge.net/projects/win32diskimager/
http://rufus.akeo.ie/

A: Also, now there is Balena Etcher:
https://www.balena.io/etcher/


text:
Q: Removing comments from a group of php files via command line in Windows I have a bunch of files and I would like to send them to deployment sans any comments but with whitespace intact (so that I can make any quick changes in production in emergency cases).
The comments can be either single line comments (#, //) or multi line syntax /**/ and at any indentation level.
I want to create a batch file that when executed from any directory reads all php files and strips their comments.
I am not even sure what to try. I know I can fetch all the files with .php extension easily and loop through them. Replacing their content is easy enough as well. What I am stuck on is how to remove the comments.

A: There's multiple ways to do it, but I think the most efficient will be to use regular expressions.
I'm not a RegExp guru, but I know that you can use grep (or any powerfull text editor such as Notepad++, sublimetext, et...) to replace expressions highlighted to empty string.
For example, in Sublime Text, I've tested this regular expression, which find any multiple lines comment :
\/\*([\s\S]*?)\*/|//.*|#.*

Quick Explanation :

*

*the regexp is made of 3, with an OR symbol inside ( the pipe symbol |)

*the first expression mean "something starting with /*, any character, or any blank character , and finishing with */"

*the second means "any expression starting with // and any character following

*the third means "any expression starting with # and any character following

Once you've set this search expression in sublime text, you can replace what it did return with a "blank" replacement.


text:
Q: Every almost-Lebesgue measurable set is Lebesgue measurable. The following problem is from exercise 8  of Tao's introductory measure theory book.
$\textbf{Prove:}$
If for all $\epsilon > 0$ one can find a Lebesgue measurable set $E_{\epsilon}$ such that $m^*(E_{\epsilon} \Delta E) \leq \epsilon$, then $E$ itself must be Lebesgue measurable.

The hint that the book gives is: use the $\epsilon/2^n$ trick to show that $E \subset E_{\epsilon}'$ where $E_{\epsilon}'$ is measurable and $m^*(E_{\epsilon}' \Delta E) \leq \epsilon$; then I should take countable intersections to show that $E$ differs from a Lebesgue measurable set by a null set.

The follow Lemma 10 will probably be useful:
(i) Every open set is Lebesgue measurable.
(ii) Every closed set is Lebesgue measurable.
(iii) Every set of Lebesgue outer measure zero is measurable. (Such sets are called null sets.)
(iv) The empty set is Lebesgue measurable.
(v) If $E \subset {\bf R}^d$ is Lebesgue measurable, then so is its complement ${{\bf R}^d \backslash E}$.
(vi) If ${E_1, E_2, E_3, \ldots \subset {\bf R}^d}$ are a sequence of Lebesgue measurable sets, then the union ${\bigcup_{n=1}^\infty E_n}$ is Lebesgue measurable.
(vii) If ${E_1, E_2, E_3, \ldots \subset {\bf R}^d}$ are a sequence of Lebesgue measurable sets, then the intersection ${\bigcap_{n=1}^\infty E_n}$ is Lebesgue measurable.

I am not sure at all how to follow the hint. Specifically I have been unable to come up with an $E_{\epsilon}'$ which satisfies the properties that I want. I find it very hard to work with $m^*(A \Delta B)$ in general. Does anyone have any tips how to construct $E_{\epsilon}'$? My guess is that we use the fact that $E_{\epsilon}$ is Lebesgue measurable in some way to approximate it from the outside, perhaps by an open set which contains $E$?

A: Let $\epsilon>0$ be arbitrary. For each $n\in\Bbb N$, there is a measurable set $E_n$ such that $m^*(E_n\Delta E) \le \epsilon/2^n$. We claim that after neglecting a set of measure $0$, in fact $E\subset\bigcup_{n=1}^\infty E_n$. That is, that the set $E-\bigcup E_n$ has measure $0$. Indeed, for every $N\in\Bbb N$,
\begin{align*}
  m^*(E-\bigcup E_n) &\le m^*(E\cap E_N^c) \\
  &\le m^*(E\Delta E_N) \le \epsilon/2^N.
\end{align*}
Since this holds for every $N$, our claim is proved. Let $\tilde E =
\bigcup E_n-E$. Then $\tilde E \subset \bigcup E_n$ and $m^*(\bigcup E_n\Delta \tilde E) = m^*(\bigcup E_n- \tilde E) \le \sum \epsilon/2^n = \epsilon$. Put $E_\epsilon' = \bigcup E_n$. By outer regularity, $\tilde E$ differs from a measurable set by a null set (pick a sequence $E_{\epsilon}'\searrow \tilde E$ as $\epsilon\to 0$), and is thereby measurable. Since $E$ is measurable if and only if $\tilde E$ is measurable, $E$ is also measurable, and the claim is proved.

A: This is a problem in Folland stated in terms of premeasures and associated outer measures (defined by taking the infimum over premeasures of countable covers). The construction of the Lebesgue measure from lengths of intervals will be a special case. I have to sleep in the near future so I'll sketch what I did when I did this for homework, and if you need further clarification, I'll come back to this thread tomorrow.
The first step is to show that if $E \subset X$, $\mathscr{A}$ is an algebra on $X$ and $\epsilon > 0$ is given, there is an $A \in \mathscr{A}_\sigma$ such that $E \subset A$ and $\mu^*(A) \leq \mu^*(E) + \epsilon$. Since the outer measure is the infimum, there is a countable cover of $E$ such that $\sum \mu_0(A_i) \leq \mu^*(E) + \epsilon$. If you take $A$ to be the union over this sequence, this is in $\mathscr{A}_\sigma$, contains $E$ by construction, and since the elements $A_i$ need not be disjoint, and premeasurable sets are outer measurable, it follows that $\mu^*(A) \leq \sum \mu_0(A_i) \leq \mu^*(E) + \epsilon$
This doesn't quite finish the argument, but it's an important first step. Since $\epsilon$ is arbitrary, we can find $B_n \in \mathscr{A}_\sigma$ so that $\mu^*(B_n) \leq \mu^*(E) + 1/n$ by the above argument. Now define $B = \cap_n B_n$. $E$ is contained in each $B_i$ and so is contained in $B$. You can do so some set algebra to prove that $\mu^*(B- E) \leq 1/n$ for every $n$, and this shows that in fact the measure is $0$.
This finishes it since in $E \subset B$ implies that $E \Delta B = B - E$, and so this is what you want to prove.
Hope this helps!

A: HINT:
Let $E_{\epsilon}$ a set that approximates $E$. For every $A$ subset we have
$$
A \cap E \subset (A \cap E_{\epsilon} ) \cup(E \backslash E_{\epsilon})\\
A \backslash E \subset (A\backslash E_{\epsilon}) \cup (E_{\epsilon} \backslash E)
$$
We get for the outer measure
$$\mu^{\star}(A\cap E)+ \mu^{\star}(A\backslash E) \le \mu^{\star}(A\cap E_{\epsilon}) + \mu^{\star}(A\backslash E_{\epsilon}) +\mu^{\star}(E\backslash E_{\epsilon}) + \mu^{\star}(E_{\epsilon} \backslash E) $$
If $E_{\epsilon}$ is measurable then we have $\mu^{\star}(A\cap E_{\epsilon}) + \mu^{\star}(A\backslash E_{\epsilon}) = \mu^{\star}(A)$. Also, we have $\mu^{\star}(E\backslash E_{\epsilon}) + \mu^{\star}(E_{\epsilon} \backslash E)\le 2 \mu^{\star}(E\Delta E_{\epsilon})\le 2 \epsilon$.
Since $\epsilon>0$ is arbitrary we get
$$\mu^{\star}(A\cap E)+ \mu^{\star}(A\backslash E) \le \mu^{\star}(A)$$ and since the opposite inequality holds, we get equality for all $A$. Hence $E$ is measurable.


text:
Q: Why does WolframAlpha's expression for $\int\frac{dx}{x\sqrt{x^4-4}}$ disagree with my own? $$\int\frac{1}{x\sqrt{x^4-4}}$$
My teacher gave us these notes and I'm unsure if they're correct. Wolfram gives a different answer, and when I derive I might have messed up.
Thanks.

A: Differentiating both the expression $$\frac{1}{4} \text{arcsec } \frac{x^2}{2} + C$$ derived in the question and the expression $$-\frac{1}{4} \arctan \frac{2}{\sqrt{x^4 - 4}} + C$$ given by WolframAlpha yields the original integrand, so both are correct. We can use a little easy trigonometric to see how this can be:
At least when $u \geq a > 0$, the quantity $$\text{arcsec } \frac{u}{a}$$ is (more or less by definition) the measure of the red angle denoted $\color{red}{\theta}$ in the below diagram.

On the other hand, we could just as well (again by definition) write $\color{red}{\theta}$ as $$\arctan \frac{\sqrt{u^2 - a^2}}{a},$$ and using the identity $$\arctan v + \arctan \frac{1}{v} = \frac{\pi}{2}$$ (which holds for $v > 0$, as similar considerations involving an appropriately labeled right triangle reveal) gives that we can also write $\color{red}{\theta} = \text{arcsec } \frac{u}{a}$ as $$\frac{\pi}{2} - \arctan \frac{a}{\sqrt{u^2 - a^2}}.$$
Now, taking $u = x^2$ and $a = 2$ as in the derivative in the question gives
$$\int \frac{dx}{x \sqrt{x^4 - 4}} = \text{arcsec } \frac{x^2}{2} + C = \frac{1}{4}\left(\frac{\pi}{2} - \arctan \frac{2}{\sqrt{x^4 - 4}}\right) + C.$$
Distributing the factor of $\frac{1}{4}$ and absorbing the constant $\frac{\pi}{8}$ into the constant of integration shows that the derived answer really does concide with WolframAlpha's answer.
One can see we could just as well have written $\color{red}{\theta}$ in terms of any of the other four inverse trigonometric functions, and each of these would have lead to an equally valid general expression for an antiderivative. These considerations also apply to a wide class of integrals that we solve using trigonometric substitution. (One should take the usual care required when working with inverse trigonometric functions, especially when working outside the "principal branch", as this can affect the antiderivative expressions in nonobvious ways.)

A: It's easy to check the correctness of an antiderivative by differentiating:
$$ \dfrac{d}{dx} \dfrac{1}{4} \text{arcsec}(x^2/2) = \dfrac{1}{x^3 \sqrt{1 - 4/x^4}} = \dfrac{1}{x \sqrt{x^4 - 4}}$$
So $\dfrac{1}{4} \text{arcsec}(x^2/2)+C$ is indeed an antiderivative of
$1/(x \sqrt{x^4-4})$.
I might note for completeness, however, that the domain of both
the function and its antiderivative (assuming you're not interested in complex values) is disconnected: $(-\infty, -\sqrt{2}) \cup (\sqrt{2},\infty)$, and thus the "constant" $C$ might be different in the two intervals.

A: Let $$\displaystyle I = \int \frac{1}{x\sqrt{x^4-4}}dx\;,$$ Let $x^2=2\sec \phi\;,$ Then $xdx = \sec \phi\cdot \tan \phi d\phi$
So Integral $$\displaystyle I = \int\frac{x}{x^2\sqrt{x^4-4}}dx = \int\frac{\sec\phi\cdot \tan \phi}{2\sec \phi\sqrt{4(\sec^2 \phi-1)}}d\phi$$
Using the formula $\bullet\; \sec^2 \phi = 1+\tan^2 \phi\Rightarrow \sec^2 \phi = 1+\tan^2 \phi$
So $$\displaystyle I = \frac{1}{4}\int\frac{\sec \phi\cdot \tan \phi}{\sec \phi\cdot \tan \phi}d\phi = \frac{1}{4}\int 1d\phi = \frac{1}{4}\phi+\mathcal{C}$$
so we get $$\displaystyle I = \frac{1}{4}\sec^{-1}\left(\frac{x^2}{2}\right)+\mathcal{C}$$
so Your answer is Right.


text:
Q: Finding the corresponding pixel using disparity maps I have a stereo pair of images and their ground truth disparity. The gray level in the disparity map tells me how far the object is. How do I use this gray level to find the corresponding pixel of a pixel?
I am sure that the gray levels are not the displacement along the x axis because a pixel in the ground truth disparity map of the left image at (50, 4) has a disparity value of 70 (which cannot the displacement along the x axis for the corresponding pixel in the right image because, the co-ordinate would then be (-20, 4) which is not valid !!)
I got my images and the ground truth from the middlebury dataset
How do I translate these values to find the position of the corresponding pixel in the other image ?
P.S. : The image motion is purely horizontal

A: I think I have figured out the answer !!
I was using the downsized images. I then downloaded the original images and the disparity maps and now they correspond perfectly to each other.
Will get back with how to work with downsized images as soon as I figure it out

A: By definition from here, disparity map tells the shift needed of a pixel in one image to the corresponding pixel in another image of a stereo image pair. Therefore, the first approach you describe is correct to get the corresponding pixel from the disparity map. That means (50, 4) will give (70, 4) or (-20, 4) if the disparity value in the pixel is 70, depends on how you choose 50 is left or right image.


text:
Q: Catastrophic backtracking for largetext Hi I have regular expression to allow alphanumeric, comma(,) and FullStop(.) and for small words (like 10 characters) it is working fine. But for big words around 850 characters the application is hanging.
Below is my regex expression.
/^(([a-zA-Z0-9\s]+[\s,])*\s?[a-zA-Z0-9]+){1}\.{0,1}$/

Some example text:

Excellent communication skills, Currently working with Infosys as
  member L and D team,Conducts V and A trainings, process trainings for
  new hires, involves in call monitoring, soft skill, email etiquettes
  training Identifies training needs and prepare action plans and is
  involved in preparing training contents,Has experience managing
  Competency Based training calendar each month across verticals,Very
  energetic, sincere and has right attitude towards career,Confident in
  her approach and has clear aspirations,Conversation and very good at
  listening,Seems to be a team player and believes in taking extra
  initiatives,Recommending a bit higher salary as she is going through
  her appraisals.Good education background, scored first class
  throughout,Very stable candidate working with Infosys since more than
  5 years

Could you please help me on this?

A: The nested quantifiers and the fact that the same \s can be matched in many different ways by the regex open it up to catastrophic backtracking. Also, some simplifications are possible.
The following fails a lot faster:
^([a-zA-Z0-9]+[\s,]+)*[a-zA-Z0-9]+\.?$

This matches a sentence of one or more alphanumeric words, separated by whitespace and/or commas, with an optional final period. The text you posted as a test subject fails because there is a period in the middle which is not allowed by the regex. If you want to allow periods there as well, just add it to the character class:
^([a-zA-Z0-9]+[\s,.]+)*[a-zA-Z0-9]+\.?$


text:
Q: Common wwwroot folder for multiple websites in MVC 6 I have multiple websites which use /wwwroot/assets folder (html theme, css and javascript files) to load the static content.
Currently I am copying assets folder in each site. All of my projects are sitting under a common parent directory.
I don't want to copy the /wwwroot/assets folder into each website. Is there a way to share one assets folder between all sites. May be by providing a direct file system path or something?

A: At the moment it's not clear from the documentation what sorts of values the webroot key in the project.json file will accept, but so far it would appear that Visual Studio doesn't care for very complicated paths. For example, setting the value to ../wwwroot causes the entry to disappear in the Solution Explorer.
If you look at the kpm code that bundles your project up for deployment, it appears to combine your project's directory with whatever is stored in the wwwroot key, so even though Visual Studio may not understand it, relative paths appear to be supported. Using kpm bundle from the command line confirms this, and a directory above src bundles correctly when using a relative path.
Depending on your particular needs, there is one way that should work that makes kpm and Visual Studio happy, but it will depend on your build environment as to whether that is a good option for you.
Windows, OSX, and Linux all support creating symbolic links for directories, which would allow you to have your assets directory in one location in the filesystem and then create links to it elsewhere. For example, if you had assets in /projects/shared/assets, you could create a link in both of your other projects (e.g. /projects/project1/src/wwwroot/assets) that point to the "real" location.
In Windows, the command would might something like this
mklink /j "C:\link\to\create" "C:\path\to\assets"

So if you did
mklink /j "C:\source\shared\assets" "C:\source\project1\src\wwwroot\assets"

project1 would appear to have an assets directory inside of wwwroot and the build process would be happy since it would appear to each project that the files were local. One thing to note here is that Windows supports a number of different sorts of links. /j specifically creates a junction rather than a true symbolic link. The differences are a bit subtle, but this is a good description of the differences. It is enough to know that if you're working locally, the /j command doesn't require administrative rights and Visual Studio and kpm will both be happy.
In OSX and Linux, the command is similar:
ln -s /link/to/create /path/to/assets

and like Windows, they support different sorts of links.
In any case, under the right circumstances, this might work well without needing any special support from the new ASP.NET project structure, but it would be nice to eventually have that as well.


text:
Q: Delphi Stack Info during Event Handling When debugging events I would like to see the "complete" stack, specifically the actual event or method that triggered an event.
A simple example would be to drop a ComboBox on a form, and write an onChange event.  The onChange event will trigger when a user changes the comboBox (obviously), but it can also get triggered via other routines, eg, at startup, the formActivate will trigger it.
If I place a breakpoint in the OnChange event of the comboBox, I won't see the triggering stack.  Why is this, and how can I get this "other" stack info during debugging?
I know I can step through the event and it will eventually bring me back to the triggering code, this is not what I am looking for.
Thank you!

I thought I would post an image of how enabling dcu's worked.  Note that the FormCreate event actually appears in the stack now.
Here is an image of two different stack traces.  Breakpoint is exactly the same in both, note that after enabling debug dcu's in the second, I get stack information from my code (not just vcl/rtl).

A: I suspect that you are missing the RTL/VCL functions from the stack trace. To make them show up, enabled Debug DCUs in the project options.

A:
After enabling Debug DCU's, I saw my own code in the stack.
  Specifically the FormCreate handler only appeared after enabling debug
  dcus. I was surprised by this.

See this:
Stack frames for frame-based methods
RTL and VCL units are compiled with "Stack Frames" option turned off. This means that any frame-based method will not be able to find short routines in RTL/VCL units.
However, this fact also have less obvious consequence. Consider this code:
procedure TForm1.Button1Click(Sender: TObject);
begin
  TStringList.Create;
end;

This code creates a simple memory leak by leaking instance of TStringList. A tracing tool will detect a leak and build call stack for it. Button1Click routine has stack frame due to "Stack Frames" option being enabled for your project. One may expect that frame-based tracing method will discover a call to Button1Click and add it to the call stack.
This is not so.
The stack frame for Button1Click allows method to identify the caller (in this case: TControl.Click). That's because stack frame does not contain information about routine itself. It contains information about the caller: return address. Return address for Button1Click routine will point to TControl.Click.
But what about Button1Click? Since TStringList is a class from RTL - it's compiled without "Stack Frames" option. Thus, constructor does not have stack frame (because it's very simple code and do not require stack frame). Therefore, it's not possible for frame-based tracing method to identify Button1Click routine.


text:
Q: Make Super User Logo Redirect To Certain Tab? I want to make my superuser browsing a little easier, on firefox is it possible to make it so when you click this home button

It automatically redirects to the tab I use instead of going through questions then newest?

A: A URL redirect plugin will do what you want.
Download this plugin or any URL re-director plugin of your choice.
Set it up like this and you're ready to go.

The only downside is that you can't access https://superuser.com/ without disabling the redirect as it will always redirect to this https://superuser.com/questions?tab=Newest

A: In Windows 10, you can make a shortcut to that page and drag it to the desktop.

*

*Click on the URL.  (It will highlight the URL.)

*Left click on the highlighted url and drag it to the desktop.

*When the icon changes so that it has a shortcut icon, release the mouse button.

*When complete, you will have an icon that looks similar to the following.


text:
Q: Unable to click a link on a website using Selenium and Java I wish to click on the "Requests" link in the left panel of the website using selenium Java.
See the snapshot below where the xpathfinder shows element as:
/html/body/div[1]/nav/div/section/ul[3]/li/a/span[1]

Below is the part of my java code generated by selenium chrome browser IDE.
System.out.println("Title of the page is 7 -> Login");
driver.findElement(By.xpath("//li[@id='tv_3']/a/i")).click();
driver.findElement(By.linkText("Security Test Requests")).click();
driver.findElement(By.id("w0")).click();

Below is the view source of the page with the relevant part of the code having the Requests link.

 Requests

 Security Test Requests

 Exception Requests

 Change Requests

 Decommission Requests

Edit: Uploaded the entire View Source of the webpage here: https://drive.google.com/file/d/1ov4Es3oDC66coaJADw6N1kxTorLmd3M6/view?usp=sharing
The issue is not with the page loading and wait of page. Infact the page gets loaded but the click on "Requests" shows a drop down which is not happening(The click)
I get the below error running my JAVA:
Title of the page is 7 -> Login
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"link text","selector":"Security Test Requests"}
  (Session info: chrome=75.0.3770.100)
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.0', revision: '2ecb7d9a', time: '2018-10-31T20:09:30'
System info: host: 'VMINITSERMAPRAP', ip: '10.9.40.115', os.name: 'Windows Server 2016', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_181'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 75.0.3770.100, chrome: {chromedriverVersion: 75.0.3770.140 (2d9f97485c7b..., userDataDir: C:\Users\axmwiis\AppData\Lo...}, goog:chromeOptions: {debuggerAddress: localhost:64908}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: 3ca2879b253b55a953c0a481ec70ea78
*** Element info: {Using=link text, value=Security Test Requests}
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)

With the suggestion on this post I tried the below:
new WebDriverWait(driver, 40).until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[@class='sidebar-menu']/li[@class='treeview']/a//span[text()='Requests']"))).click();

But, I get the following error:
Title of the page is 7 -> Login
Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for element to be clickable: By.xpath: //ul[@class='sidebar-memu']/li[@class='treeview']/a//span[text()='Requests'] (tried for 40 second(s) with 500 milliseconds interval)
        at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:95)
        at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:272)
        at pack.SynvmRequest.testSynvmRequest(SynvmRequest.java:135)
        at pack.SynvmRequest.main(SynvmRequest.java:398)
Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//ul[@class='sidebar-memu']/li[@class='treeview']/a//span[text()='Requests']"}
  (Session info: chrome=75.0.3770.100)
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.0', revision: '2ecb7d9a', time: '2018-10-31T20:09:30'
System info: host: 'MyHost', ip: '10.9.140.15', os.name: 'Windows Server 2016', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_181'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 75.0.3770.100, chrome: {chromedriverVersion: 75.0.3770.140 (2d9f97485c7b..., userDataDir: C:\Usersxmwiis\AppData\Lo...}, goog:chromeOptions: {debuggerAddress: localhost:53969}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: 979b2c191659cbbba7c43ebe4db9b5b9
*** Element info: {Using=xpath, value=//ul[@class='sidebar-memu']/li[@class='treeview']/a//span[text()='Requests']}
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)

Can you please suggest?

A: There is a space, and that's why selenium can not detect your element by linktext("Security Test Requests")

 Security Test Requests

your element should be
driver.findElement(By.linkText(" Security Test Requests")).click();

or you can use contains the method for XPath
 driver.findElement(By.xpath("//li[contains(text(), 'Security Test Requests')]").click();

A: You need to consider a couple of things as follows:

*

*The  element with text as Requests have a onclick event, so it's a JavaScript enabled element.

*The  nodes with texts Security Test Requests, Exception Requests, Change Requests and Decommission Requests all of them have a leading white-space character. So linkText won't work.

Solution
To click on the element with text as Requests and then on the element with text as Security Test Requests you need to use WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

*

*partialLinkText:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//li[@id='tv_3']/a/i"))).click();
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.partialLinkText("Security Test Requests"))).click();

*xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[@class='sidebar-menu']/li[@class='treeview']/a//span[text()='Requests']"))).click();
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[@class='treeview-menu']//li/a[contains(., 'Security Test Requests')]"))).click();


text:
Q: Who did Rowling give confidental information to about future plots? Was the casting of Alan Rickman as Snape based on the full knowledge of the future of that character? points out that J. K. Rowling gave some information to the actors of Hagrid and Professor Snape about the plots of future books of the Harry Potter series, in order that they can act their roles better.  Quoting the interview from 2001

Lizo: It's been reported that you talked about the "back story" of some of the characters with some of the actors. Is that true?
JK: I'm very secretive about these things, but yes I did. I gave certain people certain information. I gave Robbie Coltrane some background on Hagrid, which I think he used superbly, because I think he's an absolutely fantastic Hagrid.
I also gave Alan Rickman a little bit on Snape.

To which people did Rowling give such secret information about the plot of books before they were published?  If it's known, I'd also like to hear when (before which book) they spoke with them, the purpose why they chose that particular person, and what she told them.  I'm interested only in information given in private to very few individuals, not information in public interviews or similar.

A: The three lead actors were told certain things

Meredith Vieira: Do they know what hap-- did they know before this book came out?
J.K. Rowling: They knew certain things.  I mean, none of them knew the ending.  But-- I told all three of them stuff about their own characters.
Meredith Vieira: Did any of them ask, "Are you going to off me?"
J.K. Rowling: Yeah, Dan did, yeah.
Meredith Vieira: Daniel did?  And did you tell him?
J.K. Rowling: I took him out to dinner … And at one point during dinner, he leaned in and he said, "Look, I've got— I've just got to ask you— do I die?" And I thought quick and then I whispered, so no one else could hear, you— you get a death scene.  But Dan is very smart.  And I'm pretty sure he would have walked away from that dinner thinking, "Yeah, I get a death scene, but what does that mean?" (LAUGHTER) — he dies.  So I hope he's happy.
Meredith Vieira: Yeah, it is his career after all. (LAUGHTER)
"Harry Potter: The Final Chapter - NBC Dateline, July 29, 2007


text:
Q: How to make an if statement do something if a String contains a searched text I want to be able to do this:
var input1 = prompt("INPUT:");
if(input1 === "run"){
alert("You cannot do that");
}

On the prompt lets say you enter "run taco" How would I make the if statement activate if only part of it matched the string.

A: You may use a regular expression:
if (/run/.test(input1)) {

or the indexOf function:
if (input.indexOf("run")!==-1) {

A: You can use .indexOf >= 0
var input1 = prompt("INPUT:");
if(input1.indexOf("run") >= 0){
  alert("You cannot do that");
}

http://www.w3schools.com/jsref/jsref_indexof.asp

A: The JavaScript String.prototype gives you several methods for this:

*

*String.prototype.includes():

The includes() method determines whether one string may be found
  within another string.
Returns true or false as appropriate.

if (input.includes("run")) {

*String.prototype.indexOf():

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex.
Returns -1 if the value is not found.

if (input.indexOf("run")>-1) {

*String.prototype.search():

The search() method executes a search for a match between a regular expression and this String object.
Returns -1 if there's no match found.

if (input.search("run")>-1) {

*String.prototype.match()

The match() method retrieves the matches when matching a string against a regular expression.
Returns an Array containing the matched results or null if there were no matches.

if (input.match("run").length>0) {


text:
Q: how to identify local variable with same name as its parent/Container class Hi i want to develop static code analysis rule so that local variables do not shadow a name in its outer scope.
can you help me hou to identify the if blocks/nested classes using the same names as in its outer scope.and also how to avoid method hiding of the parents' member methods.
Please help me creating an algorithm so that i can develop a static code analysis rule.

A: (EDIT: OP wasn't originally clear about the target language)
Assuming Java, use a Java parser that builds an AST.  Implement the following algorithm:
for all Java source files F of interest
    parse F
    for all nodes N of F
        if N is a "class declaration" for a class C
            for all methods M under N
                for all nodes m in M
                    if m is a declaration with name C
                       report "found " m " in " M " shadowing " C
                    endif
                endfor
           endfor
       endif
   endfor
endfor

This is a little inefficient in that it might scan some subtrees more than once.
Namespaces make this more complex for C# and C++.  If you want to do this
for those languages, I think you will need a full parser along with name resolution (symbol table).
There's no gaurantee that a method is declared "under" the class declaration in those langauges,
so a simple tree search won't do the trick.  In that case, you'll
have to add an additional syntax check for a namespace declaration, and verify that the namespace
refers to a declared class by checking the symbol table.
For C++, you might use Clang or our C++ Front End.
I'm not sure what you can use to this for C#, since you need the symbol table. Perhaps Mono offers you sufficent access, but I didn't think they handled C# 3.0 or 4.0.


text:
Q: How do I couple segmented CF traffic data (SS) with shape data (SHP)? The "Road Shape and Road Class Filters" resource's example seems to imply that CF data is mapped to the current shape. This is because CF and SHP tags are siblings.
<?xml version="1.0" encoding="UTF-8"?>
<TRAFFICML_REALTIME CREATED_TIMESTAMP="2017-06-02T18:10:48Z" MAP_VERSION="" UNITS="imperial" VERSION="3.2" xmlns="http://traffic.nokia.com/trafficml-flow-3.2">
  <RWS EBU_COUNTRY_CODE="1" EXTENDED_COUNTRY_CODE="A0" MAP_VERSION="201702" TABLE_ID="7" TY="TMC" UNITS="imperial">
    <RW DE="Binford Blvd" LI="107+01100" PBT="2017-06-02T18:10:13Z" mid="1fe417f0-f17e-47b8-b0b0-b67a71eec11d|">
      <FIS>
        <FI>
          <TMC DE="E Kessler Boulevard East Dr" LE="1.5983" PC="8367" QD="-"/>
          <SHP FC="3">39.8405,-86.11263 39.84072,-86.11237</SHP>
          <SHP FC="3">39.84072,-86.11237 39.8413,-86.11168</SHP>
          <SHP FC="3">39.8413,-86.11168 39.84181,-86.11106 39.84235,-86.11039 39.84307,-86.10953 39.84487,-86.10738 39.84663,-86.10527 39.84747,-86.10427 39.84793,-86.10369</SHP>
          <SHP FC="3">39.84793,-86.10369 39.84886,-86.10255 39.84949,-86.10172 39.85041,-86.10046 39.85088,-86.09985 39.85137,-86.09926 39.85169,-86.09888 39.85203,-86.09854 39.85237,-86.09821 39.85272,-86.09789 39.85307,-86.09758 39.85343,-86.09729 39.8542,-86.09673 39.85502,-86.09616</SHP>
          <SHP FC="3">39.85502,-86.09616 39.85534,-86.09595 39.85631,-86.09528 39.85691,-86.09487 39.85751,-86.09443</SHP>
          <SHP FC="3">39.85751,-86.09443 39.85808,-86.09399 39.85836,-86.09379</SHP>
          <CF CN="0.97" FF="47.85" JF="1.39455" SP="39.84" SU="39.84" TY="TR"/>
        </FI>
        <!-- ... -->
      </FIS>
    </RW>
  </RWS>
</TRAFFICML_REALTIME>

This is useful, since it tells me the exact road shape and its corresponding traffic data.
This is not the case when the Flow Item is broken up into multiple segments. Here is a sample JSON that I'm working with:
...
{
    "FIS":[
        {
            "FI":[
                {
                    ...
                    "SHP":[
                        {
                            "value":[
                                "51.24274,7.13212 51.24311,7.13263 51.2432,7.13277 "
                            ],
                            "FC":3
                        },
                        {
                            "value":[
                                "51.2432,7.13277 51.24345,7.13314 51.24363,7.13346 51.24382,7.13381 51.24398,7.13408 51.24408,7.13423 51.24418,7.13436 "
                            ],
                            "FC":3
                        },
                    ...
                    ]
                    "CF":[
                        {
                            "SSS":{
                                "SS":[
                                    {
                                        "LE":1.07,
                                        "SP":50.0,
                                        "SU":52.63,
                                        "FF":49.18,
                                        "JF":0.0
                                    },
                                    {
                                        "LE":0.37,
                                        "SP":25.67,
                                        "SU":25.67,
                                        "FF":26.74,
                                        "JF":0.37504
                                    },
                                ...

As you can see, the CF segments are decoupled from the shape of the road, unlike the previous XML example.
Is there any way to interpret this data that couples traffic congestion with the shape of the road?

A: Each traffic flow model consists of a location data of road segment represented in different location references (TMC, SHP)
and a currentFlow (CF) field describing the current traffic conditions.
If there are different traffic conditions within same road segment, then sub segments (SS) are included to provide more granular traffic conditions while CF having aggregated information.
Data model for traffic flow does not provide location data for each subsegment, however it can be derived using length information available on subsegment SS. Example: Traverse to shape points until it matches subsegment length (preferred using percentile length as length may vary due to different map version or length calculated from shape points does not accurately match with map)then continuing it until last SSS


text:
Q: What's the easiest way to draw block matrices? I would like to draw block matrices with special structures like shown in the picture below. What's the easiest way to do that?

A: Well, when I needed to do similar task, I wrote \Rect function
\documentclass{article}
\usepackage{tikz}

\newcommand{\Rect}[5]{
    \draw[#1] (#2,#3) rectangle(#2+#4,#3-#5);
}

\begin{document}

\begin{tikzpicture}
\Rect{}{0}{4}{6}{4}

\Rect{fill=red}{0}{4}{2}{1}
\Rect{fill=red}{2}{4}{2}{1}
\Rect{fill=red}{4}{4}{2}{1}

\Rect{fill=gray}{0}{3}{2}{1}
\Rect{fill=gray}{2}{2}{2}{1}
\Rect{fill=gray}{4}{1}{2}{1}
\end{tikzpicture}

\end{document}

It draws the first image.

[Screenshot added by cfr.]

A: An ordinary tabular and colortbl will do:
\documentclass[11pt, a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[x11names]{xcolor}
\usepackage{array, colortbl}

\begin{document}

\centering
\begin{tabular}{|*{4}{p{0.6cm}|}}
  \hline
  \rowcolor{SlateGray4!60} & & & \\
  \hline
                           & \cellcolor{SlateGray3!40} & & \\
  \hline
                           & & \cellcolor{SlateGray3!40} & \\
  \hline
                           & & & \cellcolor{SlateGray3!40} \\
  \hline
\end{tabular}
\qquad
\begin{tabular}{|*{4}{p{0.6cm}|} >{\columncolor{SlateGray4!60}}p{0.6cm} |}%
  \hline
  \cellcolor{SlateGray3!40} & & & & \\
  \hline
                            & \cellcolor{SlateGray3!40} & & & \\
  \hline
                            & & \cellcolor{SlateGray3!40} & & \\
  \hline
                            & & & \cellcolor{SlateGray3!40} & \\
  \hline
\end{tabular}
\vskip1cm
\begin{tabular}{|*{4}{p{0.6cm}|} >{\columncolor{SlateGray4!60}}p{0.6cm} |}%
  \hline
  \rowcolor{SlateGray4!60} & & & & \\
  \hline
  \cellcolor{SlateGray3!40} & & & & \\
  \hline
                            & \cellcolor{SlateGray3!40} & & & \\
  \hline
                            & & \cellcolor{SlateGray3!40} & & \\
  \hline
\end{tabular}

\end{document}

If you do not want horizontal lines for empty cells, it is easy to do wih hhline:
\documentclass[11pt, a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[x11names]{xcolor}
\usepackage{array, colortbl, hhline}
\usepackage{xparse}
\DeclareExpandableDocumentCommand\emptycell{O{|c|}m}{\multicolumn{#2}{#1}{}}

\begin{document}

\centering
\begin{tabular}{|*{4}{p{0.6cm}|}}
  \hline
  \rowcolor{SlateGray4!60} & & & \\
  \hline
     & \cellcolor{SlateGray3!40} & \emptycell[c|]{2} \\
  \hhline{|~|--|~|}
    \emptycell{2}& \cellcolor{SlateGray3!40} & \\
  \hhline{|~~|--|}
    \emptycell{3} & \cellcolor{SlateGray3!40} \\
  \hline
\end{tabular}
\qquad
\begin{tabular}{|*{4}{p{0.6cm}|} >{\columncolor{SlateGray4!60}}p{0.6cm} |}%
  \hline
  \cellcolor{SlateGray3!40} & \emptycell[c|]{3}& \\
  \hhline{--~~|-}
                            & \cellcolor{SlateGray3!40} & \emptycell[c|]{2} & \\
  \hhline{|~|--~|-}
       \emptycell{2} & \cellcolor{SlateGray3!40} & & \\
  \hhline{|~~|---}
   \emptycell{3} & \cellcolor{SlateGray3!40} & \\
  \hline
\end{tabular}
\vskip1cm
\begin{tabular}{|*{3}{p{0.6cm}|} >{\columncolor{SlateGray4!60}}p{0.6cm} |}%
  \hline
  \rowcolor{SlateGray4!60} & & & \\
  \hline
  \cellcolor{SlateGray3!40} & \emptycell[c|]{2} & \\
  \hhline{--~|-}
    & \cellcolor{SlateGray3!40} & & \\
  \hhline{|~|--|-}
     \emptycell{2} & \cellcolor{SlateGray3!40} & \\
  \hline
\end{tabular}

\end{document}

A: A solution with TikZ matrix was missing!
\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{matrix, positioning}

\begin{document}
\begin{tikzpicture}[%
    mynode/.style={minimum width=1cm, minimum height=0.5cm,
        draw, fill=#1, outer sep=0pt},
    mynode/.default={black!60},
    N1/.style={mynode},
    N2/.style={mynode=black!30},
    mymatrix/.style={draw, column sep=-\pgflinewidth, row sep=-\pgflinewidth, matrix of nodes, inner sep=0pt}
    ]

    \matrix[mymatrix] (A)
    {|[N1]|&|[N1]|&|[N1]|\\
     |[N2]|&       &     \\
           &|[N2]| &     \\
           &       &|[N2]|\\};

    \matrix[mymatrix, right=of A] (B)
    {|[N2]|&      &      &      &|[N1]|\\
           &|[N2]|&      &      &|[N1]|\\
           &      &|[N2]|&      &|[N1]|\\
           &      &      &|[N2]|&|[N1]|\\};

    \matrix[mymatrix, right=of B] (C)
    {|[N1]|&|[N1]|&|[N1]|&|[N1]|\\
     |[N2]|&      &      &|[N1]|\\
           &|[N2]|&      &|[N1]|\\
           &      &|[N2]|&|[N1]|\\};
\end{tikzpicture}
\end{document}

A: Another solution based on the psmatrix environment, from pstricks:
\documentclass[11pt, a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{geometry}
\usepackage[x11names]{xcolor}
\usepackage{pst-node, auto-pst-pdf}

\begin{document}

\centering\noindent
\begin{pspicture}
  \begin{psmatrix}[mnode=p, emnode=p, colsep1.5cm, rowsep=0.4cm]
    [name=A0] & [name=A1] & [name=A2] & [name=A3] & [name=A4] \\
    [name=B0] & [name=B1] & [name=B2] & [name=B3] & \\
    & [name=C1] & [name=C2] & [name=C3] & \\
    & & [name=D2] & [name=D3] & [name=D4] \\
    [name=E0] & & & [name=E3] & [name=E4]
  \end{psmatrix}
  \psset{dimen =middle}
  \psframe(E0)(A4)
  \psset{fillstyle=solid}
  \psframe[fillcolor=SlateGray4!60](B0)(A4)
  \pspolygon[fillcolor=SlateGray3!40](B1)(B2)(C2)(C3)(D3)(D4)(E4)%
  (E3)(D3)(D2)(C2)(C1)(B1)
  \psline(A1)(B1)\psline(A2)(B2)\psline(A3)(B3)
  \hskip1.5cm
  \begin{psmatrix}[mnode=p, emnode=p, colsep1.5cm, rowsep=0.4cm]
    [name=A0] & [name=A1] & & & & [name=A5] \\
    [name=B0] & [name=B1] & [name=B2] & & [name=B4] & [name=B5] \\
    & [name=C1] & [name=C2] & [name=C3] & [name=C4] & [name=C5] \\
    & & [name=D2] & [name=D3] & [name=D4] & [name=D5] \\
    & & & [name=E3] & [name=E4] & [name=E5]
  \end{psmatrix}
  \psframe(A0)(E5)
  \psset{dimen=middle}
  \psframe(E4)(A5)
  \psset{fillstyle=solid}
  \psframe[fillcolor=SlateGray4!60](E4)(A5)
  \pspolygon[fillcolor=SlateGray3!40](A0)(A1)(B1)(B2)(C2)(C3)(D3)(D4)(E4)%
  (E3)(D3)(D2)(C2)(C1)(B1)(B0)(A0)
  \psline(B4)(B5)\psline(C4)(C5)\psline(D4)(D5)
\end{pspicture}
\vskip2cm
\begin{pspicture}
  \begin{psmatrix}[mnode=p, emnode=p, colsep1.5cm, rowsep=0.4cm]
    [name=A0] & [name=A1] & [name=A2] & [name=A3] & [name=A4] \\
    [name=B0] & [name=B1] & [name=B2] & [name=B3] & [name=B4] \\
    [name=C0] & [name=C1] & [name=C2] & [name=C3] & [name=C4] \\
    & [name=D1] & [name=D2] & [name=D3] & [name=D4] \\
    [name=E0] & & [name=E2] & [name=E3] & [name=E4]
  \end{psmatrix}
  \psframe(E0)(A4)
  \psset{fillstyle=solid}
  \pspolygon[fillcolor=SlateGray4!60](A0)(A4)(E4)(E3)(B3)(B0)(A0)
  \pspolygon[fillcolor=SlateGray3!40](B0)(B1)(C1)(C2)(D2)(D3)(E3)(E2)(D2)(D1)(C1)(C0)(B0)%
  \psline(A1)(B1)\psline(A2)(B2)\psline(A3)(B3)
  \psline(B3)(B4)\psline(C3)(C4)\psline(D3)(D4)
\end{pspicture}
\end{document}


text:
Q: How can I get items on sapui5 dynamic table? I have created dynamic table, but while I was trying to show combobox items I could not figured it out. Here is the problem and my code:

As you see above link or picture, I can not see the items, But actually, the result is true(3 items) without text. I tried to solve the problem hardly, but no solve, Please If you see my misssing, tell me.
onCreateTable: function () {
            var summaryDetailData = {
                "subvariants": [{
                    "kontrolNesnesiTanim": "test 1 Tanım",
                    "kontrolNesnesiBelirtim": "test 1 Belirtim",
                    "kontrolSonucu": {
                        "test0": "test00",
                        "test1": "test10",
                        "test2": "test20",
                    },
                    "kontrolEdilecek": 20,
                    "kontrolEdilen": 0,
                    "icon": "sap-icon://accept"
                }, {
                    "kontrolNesnesiTanim": "test 2 Tanım",
                    "kontrolNesnesiBelirtim": "test 2 Belirtim",
                    "kontrolSonucu": {
                        "test0": "test00",
                        "test1": "test10",
                        "test2": "test20",
                        "test3": "test30"
                    },
                    "kontrolEdilecek": 10,
                    "kontrolEdilen": 0,
                    "icon": "sap-icon://decline"
                }, {
                    "kontrolNesnesiTanim": "test 3 Tanım",
                    "kontrolNesnesiBelirtim": "test 3 Belirtim",
                    "kontrolSonucu": {
                        "test0": "test00",
                        "test1": "test10",
                        "test2": "test20",
                    },
                    "kontrolEdilecek": 50,
                    "kontrolEdilen": 0,
                    "icon": "sap-icon://accept"
                }, ]
            };

            var oTable = new sap.m.Table("idRandomDataTable", {
                headerToolbar: new sap.m.Toolbar({
                    content: [new sap.m.Label({
                        text: ""
                    })]
                }),
                columns: [new sap.m.Column({
                    width: "2em",
                    header: new sap.m.Label({
                        text: "Kontrol Nesnesi"
                    })
                }), new sap.m.Column({
                    width: "2em",
                    header: new sap.m.Label({
                        text: "Kontrol Sonucu"
                    })
                }), new sap.m.Column({
                    width: "2em",
                    header: new sap.m.Label({
                        text: "Kontrol Edilecek"
                    })
                }), new sap.m.Column({
                    width: "2em",
                    header: new sap.m.Label({
                        text: "Kontrol Edilen"
                    })
                }), new sap.m.Column({
                    width: "2em",
                    header: new sap.m.Label({
                        text: "Durum/Değerlendirme"
                    })
                }), new sap.m.Column({
                    width: "2em",
                    header: new sap.m.Label({
                        text: "Açıklama"
                    })
                })]
            });

            this.getView().byId("SimpleFormChange480_TrialSonuc").addContent(oTable);

            oTable.bindItems("/subvariants", new sap.m.ColumnListItem({
                cells: [new sap.m.ObjectIdentifier({
                    title: "{kontrolNesnesiTanim}",
                    "titleActive": true,
                    text: "{kontrolNesnesiBelirtim}"
                }),
                new sap.m.ComboBox({
                    items: {
                        path: "kontrolSonucu/",
                        change:"onChange",
                        template: new sap.ui.core.Item({
                            key: "test01",
                            change:"onChange",
                            text: "{test0}"
                        })
                    },
                    change:"onChange",
                })
                // new sap.m.MultiInput({
                //  id:"multiInput3",
                //  showValueHelp:false
                // })
                , new sap.m.Input({
                    value: "{kontrolEdilecek}",
                }), new sap.m.Input({
                    value: "{kontrolEdilen}"
                }), new sap.ui.core.Icon({
                    src: "{icon}"
                        //text: "{Article}"
                }), new sap.m.Input({
                    value: "",
                    // value: "{question}",
                })]
            }));

            oTable.setModel(new sap.ui.model.json.JSONModel(summaryDetailData));
        }

Do you have any idea or suggestion?
Thanks.

A: I have solved the problem
    oTable.bindItems("/subvariants", new sap.m.ColumnListItem({
            cells: [new sap.m.ObjectIdentifier({
                title: "{kontrolNesnesiTanim}",
                "titleActive": true,
                text: "{kontrolNesnesiBelirtim}"
            }),
            new sap.m.ComboBox({
                items: {
                    path: "kontrolSonucu/",
                    change:"onChange",
                    template: new sap.ui.core.Item({
                        key : "{}",
                        change:"onChange",
                        text: "{}"
                    })
                },
                change:"onChange",
            })

As you see above, I should had to write text empty JSON, So I can see all the items.
Thanks anyway.


text:
Q: acf и wp_insert_post - создание формы размещения материалов Использую плагин для WordPress - http://www.advancedcustomfields.com
Каким образом возможно организовать форму размещения новых материалов на определённой странице?
Сама задача просматривается явно: создание формы и передача данных.
С первый этапом задачи не возникает трудностей, вся трудность во втором.
Массив для передачи данных от отдельной страницы может быть выполнен по виду:
$post_data = array(
'post_title'    => wp_strip_all_tags( $_POST['titlee'] ),
'post_content'  => $_POST['content'],
'post_status'   => 'publish',
'post_author'   => $user_id,
'tags_input'    => $_GET['tag'],
'post_category' => '1'
);

Собственно, здесь и возникает вопрос. Какие данные требуются включить в массив, чтобы передать их в материал, в поля плагина acf.
Стандартные данные передать не составляет труда - заголовок, текст материала и прочее. Но вот как поступить с плагином? Возможно, что следует смотреть в сторону "field_groups" - только не до конца определился, каким образом оформить массив для передачи данных.

A: update_field($field_key, $value, $post_id);

Все подробно, с примерами, рассказано в источнике.
Если вкратце:
$field_key — ключ поля, не name!, если вы хотите НОВЫЙ пост. Для обновления существующего может использоваться и name.
$value — значение, которое нужно сохранить. Как обычный текст, так и массив, для полей типа repeater или flexible.
$post_id — ID созданного поста, которое мы получаем в ответ на wp_insert_post. На самом деле в роли post_id может выступать и категория и юзер и что угодно, если необходимо.


text:
Q: Javascript submit textbox on ENTER
Possible Duplicate:
Bind textbox to 'enter' key

I've made a chat system with AJAX and jQuery and there is no <form> tag wrapping the TextBox for chat messages, so I can't submit that message with the ENTER button on the keyboard.
Is there any way I can submit that value from TextBox with javascript?
Thanks.

A: document.getElementById("id_of_your_textbox").addEventListener("keydown", function(e) {
    if (!e) { var e = window.event; }
    e.preventDefault(); // sometimes useful

    // Enter is pressed
    if (e.keyCode == 13) { submitFunction(); }
}, false);

A: $('#textboxId').keydown(function (event) {
    let keyPressed = event.keyCode || event.which;
    if (keyPressed === 13) {
        $(this).closest('form').submit();
    }
});

If you don't have form, then replace $(this).closest('form').submit(); with whatever AJAX/submit logic you have.

A: You will need to listen for the ENTER key press event.  Take a look at Enter key press event in JavaScript for some examples on how it is done.


text:
Q: Unable to resolve No matching version found for gatsby-cli@next I have tried running the following command with and without sudo, I'm unable to install gatsby.
npm install --global gatsby@next gatsby-cli@next
here are my errors.
npm ERR! code ETARGET
npm ERR! notarget No matching version found for gatsby-cli@next.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-10-08T11_08_10_903Z-debug.log

A: @next in npm refers to a tag. In this case, there's no tag for gatsby-cli. By default, if you run:
npm install -g gatsby-cli

It will take the latest version of the gatsby-cli package.
You can check for further details in npm documentation.


text:
Q: Limit `ssh -R` to a single port I understand that the permitopen="host:port" option limits the use of ssh -L to a single remote port. Is there a way to do the same with ssh -R?

A:
is there a way to do the same with ssh -R?

Not really "the same". For the most common usage of ssh -R there is little to no point in having such option, but read this answer to the end.

Analysis
PermitOpen is an option in sshd_config. It affects not only ssh -L, but also ssh -D, ssh -W and ssh -J (at least). I think it's designed as a filter to TCP connections initiated by the SSH server on request of a client.
Imagine you're an admin of the server. The client, for whom SSH may be the only entrance to the system, may be totally untrusted. The system may be a bastion the client should use only to obtain a tunnel to well-defined location(s). You are able to set things up, so the client cannot run arbitrary commands. Then you may want your computer not to initiate connections to random addresses for this client. PermitOpen lets you configure this easily.
An option in sshd_config that would limit the target of client's ssh -R is not useful for you (the admin of the SSH server) because:

*

*In case of ssh -R, any connection to the target address:port will originate from the client's system which is not your concern. Your concern is the interface and the port your system will listen on. There is an option to limit this: PermitListen.

*I don't think ssh (the client's application) even reports this address:port to the SSH server.

*Even if it did, a modified ssh (or anything using the protocol) could lie. The server has no means to tell what ssh does with any data on its end.

*Even if the client's application didn't lie, the client could request address:port you allow and locally use iptables, socat, /etc/hosts or its own DNS server to connect the tunnel to another address and another port.
In short: as an admin of the server you cannot control the client's side anyway. Do not try; it's not your concern.
Maybe you meant an option to limit ssh -R on the client's side, in ssh_config. At first glance such option makes some sense; but think about it and you'll notice that:

*

*It's the client who wants a tunnel to some address:port, so certainly he or she won't be interested in any limiting in ~/.ssh/config.

*An admin of the client's system (where the client may be a regular user) may want to impose some limitations, e.g. in /etc/ssh/ssh_config. But with ssh personal config and command line options take precedence, the client can override any global config. This is by design and you shouldn't fight it because…

*If you're the admin of the client's system and you don't want the client to connect to some address:port then what difference does it make if they try to establish such connection using ssh, nc or anything else? You need a solution with scope broader than the config of ssh.
Note there's asymmetry: on the server side, in cases where SSH is the only entrance for the client to the system, limiting in sshd_config makes sense. On the client's side the client is already in the system, ssh is just a program he or she can use; therefore limiting (if needed) should be more system-wide than in ssh_config.

PermitRemoteOpen
There is one scenario in which the client may be interested in limiting address:port his or her ssh can connect to. And it is with ssh -R; but not the ssh -R that mirrors ssh -L (and I guess this is what you had in mind), but the form of ssh -R that mirrors ssh -D.
With ssh -R, if you (as a client) don't specify any address:port to forward to, then the SSH server will become a SOCKS proxy and it will be your computer who will connect to addresses requested by people using the proxy. It's like ssh -D but the other way around.
In case of ssh -D, whoever uses the proxy chooses address:port the SSH server shall connect to on their behalf. The admin of the server may want to limit this, PermitOpen is the way. In case of ssh -R acting as a SOCKS proxy, similarly whoever uses the proxy chooses address:port the SSH client application shall connect to on their behalf. As a client you may want to limit this because in general these address:ports are not necessarily (in practice: never) your choice, but it's your ssh connecting to them. You can use PermitRemoteOpen in your ~/.ssh/config. This is the option to limit ssh -R, but it only works when ssh -R creates a SOCKS proxy on the server.

Summary

*

*PermitOpen in sshd_config on SSH server limits ssh -L (and ssh -D, ssh -W, ssh -J). PermitRemoteOpen in ssh_config (or ~/.ssh/config) on a client's side limits ssh -R.

*Each option is governed by the person whose application will eventually initiate connections: the admin of the server (owning sshd) and the client (running ssh) respectively. Limiting ssh -R by the admin of the server would be futile.

*Each option works in cases where the governing person is not the person who chooses address:port for the application to connect to. For PermitOpen all cases are like this. For PermitRemoteOpen only ssh -R creating a SOCKS proxy on the server is like this.

*Limiting ssh -R of other types by the client makes no sense (the client would limit himself) and there is no option for it.


text:
Q: Bash output of date in bash script I wrote this script:
#!/bin/bash
target="1.1.1.1"
while true;
do
        ping $target -c 1 -v > /dev/null
        if [[ $? -ne 0 ]]; then
                echo "$(date +"%d/%m/%y %R:%S")" >> netStabilityLog
        fi
        sleep 5s
done

It works almost perfectly, there is just one problem. In the ouptut file netStabilityLog, I get:
28/06/22 17:19:26
28/06/22 17:20:06
28/06/22 17:45
28/06/22 18:36:00
28/06/22 18:51

Sometimes, the seconds are not shown. Why is that?

A: It appears that you may have had multiple, slightly different, copies of the script running at once, each writing to the same output file. At least one running version of the script was not adding the seconds to its output.
As for the script itself, I could possibly give my take on it, which gets rid of the external date utility and which does the conditional outputting and redirection differently.  It also sorts out the missing quoting.
#!/bin/bash

ipaddr=1.1.1.1

while true; do
    if ! ping -c 1 "$ipaddr" >/dev/null 2>&1
    then
        printf '%(%d/%m/%y %T)T\n' -1
    fi
    sleep 5
done >>netStabilityLog

This uses the %(...)T formatting string with printf, introduced in bash release 4.2.  The argument -1 causes printf to use the current time when creating the output timestamp.  It also does not redirect for each printf call but rather once only, for the outer loop.
The code gets rid of the explicit test against $? by using ping directly with if. The ping is not called with -v (for verbose output) as we're discarding the output anyway.


text:
Q: I want to set onClicklistener for an imageView on a cardView that is not present on particular xml file I have the main activity with its XML file that contains the listview
I have an item layout that includes cardview with the imageview and few relative layouts
I have an adapter that populates the listview with data from the database

I have a table in a database, and an adapter that connects my listview now when I try to set an onclicklistener on the imageview as shown below (Image) it shows the error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

A: You are not initializing your imageView. Add following line in getView with other textView's.
ImageView icDownarrow = (ImageView) view.findViewById(R.id.icUparrow);

Remove the following variable globally (line:29)
ImageView icDownarrow,icUparrow;

Final Output will be
TextView timetxt = (TextView) view.findViewById(R.id.timetxt);
TextView codetxt = (TextView) view.findViewById(R.id.codetxt);
TextView moduletxt = (TextView) view.findViewById(R.id.moduletxt);
TextView stafftxt = (TextView) view.findViewById(R.id.stafftxt);
ImageView icDownarrow = (ImageView) view.findViewById(R.id.icUparrow);

icDownarrow.setOnClickListener(new View.OnClickListener() {
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onClick(View view) {
        if (expandedLay.getVisibility() == View.GONE) {
            TransitionManager.beginDelayedTransition(cardView, new AutoTransition());
            expandedLay.setVisibility(View.VISIBLE);
            icDownarrow.setVisibility(View.GONE);
        } else {
            TransitionManager.beginDelayedTransition(cardView, new AutoTransition());
            expandedLay.setVisibility(View.GONE);
        }
    }
});


text:
Q: .Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned I am in a situation where when I get an HTTP 400 code from the server, it is a completely legal way of the server telling me what was wrong with my request (using a message in the HTTP response content)
However, the .NET HttpWebRequest raises an exception when the status code is 400.
How do I handle this? For me a 400 is completely legal, and rather helpful. The HTTP content has some important information but the exception throws me off my path.

A: Try this (it's VB-Code :-):
Try

Catch exp As WebException
  Dim sResponse As String = New StreamReader(exp.Response.GetResponseStream()).ReadToEnd
End Try

A: I know this has already been answered a long time ago, but I made an extension method to hopefully help other people that come to this question.
Code:
public static class WebRequestExtensions
{
    public static WebResponse GetResponseWithoutException(this WebRequest request)
    {
        if (request == null)
        {
            throw new ArgumentNullException("request");
        }

        try
        {
            return request.GetResponse();
        }
        catch (WebException e)
        {
            if (e.Response == null)
            {
                throw;
            }

            return e.Response;
        }
    }
}

Usage:
var request = (HttpWebRequest)WebRequest.CreateHttp("http://invalidurl.com");

//... (initialize more fields)

using (var response = (HttpWebResponse)request.GetResponseWithoutException())
{
    Console.WriteLine("I got Http Status Code: {0}", response.StatusCode);
}

A: An asynchronous version of extension function:
    public static async Task<WebResponse> GetResponseAsyncNoEx(this WebRequest request)
    {
        try
        {
            return await request.GetResponseAsync();
        }
        catch(WebException ex)
        {
            return ex.Response;
        }
    }

A: It would be nice if there were some way of turning off "throw on non-success code" but if you catch WebException you can at least use the response:
using System;
using System.IO;
using System.Web;
using System.Net;

public class Test
{
    static void Main()
    {
        WebRequest request = WebRequest.Create("http://csharpindepth.com/asd");
        try
        {
            using (WebResponse response = request.GetResponse())
            {
                Console.WriteLine("Won't get here");
            }
        }
        catch (WebException e)
        {
            using (WebResponse response = e.Response)
            {
                HttpWebResponse httpResponse = (HttpWebResponse) response;
                Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                using (Stream data = response.GetResponseStream())
                using (var reader = new StreamReader(data))
                {
                    string text = reader.ReadToEnd();
                    Console.WriteLine(text);
                }
            }
        }
    }
}

You might like to encapsulate the "get me a response even if it's not a success code" bit in a separate method. (I'd suggest you still throw if there isn't a response, e.g. if you couldn't connect.)
If the error response may be large (which is unusual) you may want to tweak HttpWebRequest.DefaultMaximumErrorResponseLength to make sure you get the whole error.

A: Interestingly, the HttpWebResponse.GetResponseStream() that you get from the WebException.Response is not the same as the response stream that you would have received from server.  In our environment, we're losing actual server responses when a 400 HTTP status code is returned back to the client using the HttpWebRequest/HttpWebResponse objects.  From what we've seen, the response stream associated with the WebException's HttpWebResponse is generated at the client and does not include any of the response body from the server.  Very frustrating, as we want to message back to the client the reason for the bad request.

A: I had similar issues when trying to connect to Google's OAuth2 service.
I ended up writing the POST manually, not using WebRequest, like this:
TcpClient client = new TcpClient("accounts.google.com", 443);
Stream netStream = client.GetStream();
SslStream sslStream = new SslStream(netStream);
sslStream.AuthenticateAsClient("accounts.google.com");

{
    byte[] contentAsBytes = Encoding.ASCII.GetBytes(content.ToString());

    StringBuilder msg = new StringBuilder();
    msg.AppendLine("POST /o/oauth2/token HTTP/1.1");
    msg.AppendLine("Host: accounts.google.com");
    msg.AppendLine("Content-Type: application/x-www-form-urlencoded");
    msg.AppendLine("Content-Length: " + contentAsBytes.Length.ToString());
    msg.AppendLine("");
    Debug.WriteLine("Request");
    Debug.WriteLine(msg.ToString());
    Debug.WriteLine(content.ToString());

    byte[] headerAsBytes = Encoding.ASCII.GetBytes(msg.ToString());
    sslStream.Write(headerAsBytes);
    sslStream.Write(contentAsBytes);
}

Debug.WriteLine("Response");

StreamReader reader = new StreamReader(sslStream);
while (true)
{  // Print the response line by line to the debug stream for inspection.
    string line = reader.ReadLine();
    if (line == null) break;
    Debug.WriteLine(line);
}

The response that gets written to the response stream contains the specific error text that you're after.
In particular, my problem was that I was putting endlines between url-encoded data pieces. When I took them out, everything worked. You might be able to use a similar technique to connect to your service and read the actual response error text.

A: This solved it for me:
https://gist.github.com/beccasaurus/929007/a8f820b153a1cfdee3d06a9c0a1d7ebfced8bb77
TL;DR:
Problem:
localhost returns expected content, remote IP alters 400 content to "Bad Request"
Solution:
Adding <httpErrors existingResponse="PassThrough"></httpErrors> to web.config/configuration/system.webServer solved this for me; now all servers (local & remote) return the exact same content (generated by me) regardless of the IP address and/or HTTP code I return.


text:
Q: Cannot read property 'clientWidth' of undefined - react js hooks I'm doing a useZoom component so whenever I hover an image the zoom-in will be activated but I have one issue that when I move the mouse into the image I get the error "Cannot read property 'clientWidth' of undefined". I have initially set the value of null, but it seems that is not enough, any suggestion on how to fix this ?

const UseZoom = () => {
  const [state, setState] = useState({
    isZoomOnSide: true,
    showOverlay: false,
    overlayLeft: 0,
    overlayTop: 0,
    zoomInLeft: 0,
    zoomInTop: 0,
    zoomInMaxWidth: 0,
  });

  let overlayNode = useRef(null);
  let imageNode = useRef(null);
  let zoomInImageNode = useRef(null);
  let zoomInWindowNode = useRef(null);

  const onMouseMove = (e) => {
    // console.log("zoomInWindowNode", zoomInWindowNode.current);
    let overlayNode;
    let imageNode;
    let zoomInImageNode;
    let zoomInWindowNode;
    const zoomInWindowWidth = zoomInWindowNode.clientWidth || 1;
    const overlayWidth = overlayNode.clientWidth || 200;
    const imageWidth = imageNode.clientWidth;
    const imageHeight = imageNode.clientHeight;
    const zoomInImageWidth = zoomInImageNode.clientWidth;
    const zoomInImageHeight = zoomInImageNode.clientHeight;
    const offsetLeft = imageNode.offsetLeft;
    const offsetTop = imageNode.offsetTop;
    const overlayLeft = Math.min(
      Math.max(e.clientX - overlayWidth / 2, offsetLeft),
      offsetLeft + imageWidth - overlayWidth
    );
    const overlayTop = Math.min(
      Math.max(e.clientY - overlayWidth / 2, offsetTop),
      offsetTop + imageHeight - overlayWidth
    );
    const zoomInLeft =
      (-(overlayLeft - offsetLeft) / imageWidth) * zoomInImageWidth;
    const zoomInTop =
      (-(overlayTop - offsetTop) / imageHeight) * zoomInImageHeight;
    const zoomInMaxWidth = zoomInWindowWidth / (overlayWidth / imageWidth);
    setState({
      overlayLeft,
      overlayTop,
      zoomInLeft,
      zoomInTop,
      zoomInMaxWidth,
    });
  };

  const toggleOverlay = (showOverlay) => {
    setState({ state, showOverlay: showOverlay });
  };

  const onSwitchButtonClick = (prevState) => {
    setState({ state, isZoomOnSide: !prevState.isZoomOnSide });
  };

  const {
    showOverlay,
    overlayLeft,
    overlayTop,
    zoomInLeft,
    zoomInTop,
    zoomInMaxWidth,
    isZoomOnSide,
  } = state;

  const overlayStyle = {
    left: overlayLeft,
    top: overlayTop,
  };
  const zoomInImageStyle = {
    left: zoomInLeft,
    top: zoomInTop,
  };

  if (zoomInMaxWidth && isZoomOnSide) {
    zoomInImageStyle["max-width"] = zoomInMaxWidth;
  }

  return (

      <button
        className="SwitchButton"
        type="button"
        onClick={onSwitchButtonClick}
      >
        {isZoomOnSide ? "Zoom Outside" : "Zoom Inside"}
      </button>

 toggleOverlay(true)}
        onMouseLeave={() => toggleOverlay(false)}
      >

        {showOverlay && isZoomOnSide && (

        )}
        {showOverlay && !isZoomOnSide && (

        )}

      {showOverlay && isZoomOnSide && (

      )}

  );
};

export default UseZoom;

A: You are declaring a let overlayNode and then immediately trying to access .clientWidth of undefined which would throw this error. You are effectively attemping undefined.clientWidth which throws the error "Cannot read property "X" of undefined"
Also, to access the DOM element in a ref you'd need to use the ref.current property. The ref itself is not the DOM element.
So you need to stop redeclaring the variables in your onMouseMove function (let imageNode, let overlayNode etc) as well as make sure you're checking for the correct ref property .current.


text:
Q: What defines the sign of transistor rating values? Here for example I have attached excerpts from two general purpose PNP transistor datasheets. One of them has negative values, other one positive.
I would like to understand what defines these values to be positive or negative.
P.S. Second one is for 2n3906.

A: The - (or +) sign indicates polarity (voltage) or direction (current).
For voltages you choose a - (negative or reference) and a + (positive) node.
For current you choose a direction.
Either polarity or direction is fine but you must be consistent, so stick with that choice.
Here the two manufacturers chose opposite polarities and current directions. That's fine (makes no difference) as long as they're clear about it.
For NPN transistors I have never seen negative voltage ratings like for some manufacturers do for PNPs. That makes sense because an NPN needs a positive Vbe voltage (Vbase > Vemitter) to make it work in active mode.
For a PNP it is the reverse, all polarities are reversed. To make a PNP work (in active mode) Vbe needs to be negative (Vbase < Vemitter). We could call a PNP's Vbe not Vbe but Veb but that would complicate things in comparison to the NPN. It is much easier to just make Vbe negative and all other voltages (Vce_max etc..) negative as well.
So in my opinion using negative voltage ratings for a PNP is "more correct". However some people may get confused about these negative values and then there is nothing wrong with using positive values and just changing the polarities.


text:
Q: Изменение URL с добавлением параметров Здравствуйте!
Подскажите, как правильно сделать?
У меня был url страницы, который включал в себя 3 параметра, теперь добавился еще один, и я его добавил в url.
Раньше было так:
RewriteRule ^opisanie/([A-Za-z_0-9]+)/([A-Za-z_0-9]+)/([A-Za-z_0-9]+).html?$ aut_lamp.php?m_lamp_type=$1&m_company_name=$2&m_id_article=$3 [NC,L]

А теперь:
RewriteRule ^opisanie/([0-9]+)/([A-Za-z_0-9]+)/([A-Za-z_0-9]+)/([A-Za-z_0-9]+).html?$ aut_lamp.php?m_id=$1m_lamp_type=$2&m_company_name=$3&m_id_article=$4 [NC,L]

Что надо сделать, чтобы уже проиндексированные страницы не потерялись и новые заменили их в поиске?


text:
Q: Keyword global:: when adding reference I've encountered a strange phenomenon today as I added a reference of a project to another project and trying to use an interface of the referenced assembly:
Situation:

*

*The class MySampleApplication is in the project MyApplication.

*The interface IMySampleApplication is in the referenced project MyApplication.Interfaces.

When I do this:
public class MySampleApplication : IMySampleApplication

Resharper adds the following using:
using global::MyApplication.Interfaces;

Question:

Why is it adding the global:: prefix and how can I avoid this?

Thanks in advance

A: You'll have two occurrences of MyApplication somewhere in your code, eg you'll likely have a class called MyApplication in your local project as well as the namespace in the MyApplication project.
The local MyApplication will take precedence over the namespace in your MyApplication project, so MyApplication.Interfaces will not be found. To get around this, the special alias global:: can be used to tell the compiler that in this case MyApplication refers to a base namespace and so MyApplication.Interfaces can then be correctly identified.
As to how to avoid it, that's easy to say, but it may be harder to achieve: rename one of them to remove the name conflict...

A: You probably have another entity called MyApplication in your project which is hiding the namespace.
See: "How to: Use the Global Namespace Alias (C# Programming Guide)"


text:
Q: Enforcing loading a class at program start in java Is there a way to enforcing loading a class after programm start? I have following case: I have a hashmap holding Name and java.lang.Class of plugin classes. in each plugin class I have a static block registring the class
static {
ClassMap.getInstance().register("name",MyPlugin.class);
}

I don't know the name and package of in this example MyPlugin. So I want that this code will executed at programm start. How is this possible?

A: If the class object is in the map, this means that the class has already been loaded i.e. your static block has been executed already.
If on the other hand, you just have the class names (e.g. in a list) you can do his:
for(String classname : yourList){
    // wrap with try / catch
    Class.forName(className);
}

Here is a pretty good overview of what happens at class load time

Update: what you seem to want is a kind of component scanning that will find all you plugin classes. There's no way to do that with plain Java, but you can e.g. use the reflections library to do that. Sample code:
Reflections reflections = new Reflections("com.your.project");
Set<Class<? extends YourBaseClass>> subTypes =
    // and all of these classes are already initialized
    reflections.getSubTypesOf(YourBaseClass.class);


text:
Q: How I can set maximum value at graphael y axis and why? I have several points that I try to represent using a graphael line chart. Almost all of them are below 0.03. However, the chart sets 1 as the maximum and all points are shown to be very down at the chart. When I have even one point over 0.03, graphael sets the maximum value something more than 0.03 and therefore the chart displays correctly. What can I do for the rest cases where all my points are below 0.03? It is really very ungly, and not helpful at all.
Is there a way to set the max value of the y axis automatically?
If you cannot help me, can you please run it, just to tell me if he can run it normally? It wouldn't take much time...
This is what I mean

I noticed that it also might produce very wrong y axis labels...
My code is shown below
var lines = r.linechart(30, 30, 600, 440,[[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71]],[[0.02046,0.00635,0.02813,0.02808,0.02385,0.00729,0.02145,0.01978,0.02683,0.03006,0.03105,0.01211,0.0083,0.0022,0.02172,0.01541,0.01181,0.02418,0.00552,0.02708,0.01011,0.0105,0.0294,0.00132,0.00615,0.02303,0.00065,0.00967,0.00381,0.02167,0.01357,0.0221,0.02512,0.00918,0.01072,0.01083,0.00598,0.00195,0.01716,0.00347,0.03058,0.01815,0.02899,0.01537,0.0241,0.0241,0.00451,0.00088,0.01574,0.00688,0.0143,0.0024,0.03047,0.02876,0.00528,0.00996,0.00865,0.02681,0.02194,0.00082,0.00664,0.01178,0.01596,0.00516,0.0165,0.00895,0.01869,0.03082,0.02318,0.01089,0.00943,0.00986]], {axisxstep : 12,axisystep : 5,nostroke: false, axis: "0 0 1 1", symbol: "circle", smooth: true }).hoverColumn(function () {
    this.tags = r.set();

    for (var i = 0, ii = this.y.length; i < ii; i++) {
        this.tags.push(r.tag(this.x, this.y[i], this.values[i], 160, 10).insertBefore(this).attr([{ fill: "#fff" }, { fill: this.symbols[i].attr("fill") }]));
    }
}, function () {
    this.tags && this.tags.remove();
});


text:
Q: Excel look up and copy over I have two excel spreadsheets.  One is a list of our products(spreadsheet 1) with details, the other is a list of products but with empty fields (spreadsheet 2).
I want to lookup a cell (A1) in spread sheet 2 - find the corresponding value in a row in spreadsheet 1 and then get another cell on the same row and copy it over to the spreadsheet 2.
so search for a value "cars" in one spreadsheet and read off its the number plate in the other spreadsheet.
Is this possible in excel ? I have 1555 rows to lookup and read off for a range of values, i can copy both into one spreadsheet but 2 worksheets

A: Try VLOOKUP()
It does not matter if Your work is in two sheets of the same workbook or two separate excel files.
You use it like this:
You put this formula in the empty cells in the second file
=VLOOKUP(KEY, TABLE_RANGE, COLUMN_INDEX, 0)
KEY is in your example the cell were "car" value is in the second file
TABLE_RANGE is area containing both: KEY equivalent in original data and result You want to copy over. IMPORTANT! first column of range have to be the one that contains KEY values. Also remember to use absolute references ($A$1:$C$55 for example)
COLUMN_INDEX is number indicating column in selected range that You want to use as result
In Your example last parameter have to be 0 (it indicates if Your want exact result or not - it is useful to put 1 in there when You are looking not for exact values but ranges of values)
Than You copy over the formula for all rows You want.
Take a look at this image to visualize how it works and how formula should be used:

(source: microsofttraining.net)


text:
Q: Why does an object's type refer to its interface? (Design Patterns: Elements of Reusable Object-Oriented Software book) Why does object's type refer to its interface? Why the term type is used here? In terms of C++ I am not able to understand it.

Gamma, Erich. Design Patterns: Elements of Reusable Object-Oriented
  Software (Addison-Wesley Professional Computing Series) (Kindle
  Locations 593-596). Pearson Education. Kindle Edition.
An object's class defines how the object is implemented. The class
  defines the object's internal state and the implementation of its
  operations. In contrast, an object's type only refers to its
  interface—the set of requests to which it can respond. An object can
  have many types, and objects of different classes can have the same
  type.

A: An oversimplification...

*

*Interface - a list of things that a class have and the things that it can do... a list of things that answer the "Whats"

*Implementation - answers the question on "How" the "Whats" are accomplished.
Example:
   An interface IPackageMover that does 2 things and 2 classes (types) that actually implements the interface (and also do other things aside from the interface requires)
 // the interface
 public interface IPackageMover
 {
    string GetName();
    void public void MoveTo(Package package, string newAddress);
 }

 // the "type" that has the implementation
 public class JoeThePackageMover : IPackageMover
 {
    public string GetName()
    {
        return "Joe";
    }
    public void MoveTo(Package package, string newAddress)
    {
        PickUp(package);
        Drive(newAddress);
        DropOff(package);
    }
    public void PickUp(Package package)
    {
        // do stuff
    }
    public void Drive(string newAddress)
    {
        // do stuff
    }
    public void DropOff(Package package)
    {
        // do stuff
    }
 }

 // another "type" with the same interface
 public class PassTheBuckPackageMover : IPackageMover
 {
    public string GetName()
    {
        return "What do you want it to be?";
    }
    public void MoveTo(Package package, string newAddress)
    {
        var joe = new JoeThePackageMover();
        joe.MoveTo(package, newAddress);
    }
    public void Chill()
    {
        //do stuff
    }

 }

A:
Why does object's type refer to its interface? Why the term type is used here? In terms of C++ I am not able to understand it.

Objects in OOP are not very different from the real world. For example :

*

*A Car IS-A Vehicle. By this definition, a Car has the ability to transport people/cargo from one place to another.

*A Car is also a Car. By this definition, it has the ability to be driven using a steering wheel.

In the above example, a Car IS-A Car and a Car is also a Vehicle because it can be driven using a steering wheel to move cargo/people from one place to another. In other words, the type of an object in the real world is defined by the things you can do with it (vis-à-vis it's interface.)
If we use the above analogy in programming, Car is a subclass of Vehicle and code that has a Car object can use all functions from Vehicle as well as Car. This would mean that a Car IS-A Vehicle and a Car. In conclusion, the type of object is defined by its interface, i.e the set of operations it supports.


text:
Q: What is the proper method for using invoke to avoid threading errors? I have been recently learning C# and have a problem I just cant seem to wrap my head around. Please forgive me if this is noobish as I am very new to C# but my question is about delegates and invoke.
I have read many many tutorials online and watched many video tutorials about this as well but I am still getting the same error in my code and I just dont seem to grasp the subtleties. As I understand it a delegate is a pointer to a function and can be used to invoke that function from say another thread to update a textbox. I understand creating a delegate, that much I think I am doing right but when I invoke the delegate from a threat I always get the error Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.
The callback appears to be functional as it is calling the function that it is designed to however it does not seem to do it on the correct thread which I thought was the whole point of doing it this way. I know there is the option to set that warning break to false but I would rather learn what I am doing wrong and how to code this type of method properly. I appreciate any help, suggestions or answers you can provide as I am not sure any more of the tutorials are getting me any closer at this point to understanding where I have gone wrong.
My code is very basic and as I am just trying to understand the most basic concepts of properly coding for multithreading. Below is my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Media;
using System.Threading;
using System.Reflection;

namespace WindowsFormsApplication3
{

    //declair delegate name(vars) CORRECT
    public delegate void Textboxdelegate(Int64 MyVar);

    public partial class Form1 : Form
    {

         public Form1()
         {
             InitializeComponent();
         }

         public void button1_Click(object sender, EventArgs e)
         {
             runme();
         }

         public void runme()
         {
             textBox1.Text = "87";
             textupdate(44);

             int target = 0;
             Textboxdelegate TD = new Textboxdelegate(textupdate);
             Number number = new Number(target, TD);
             TD(11);
             Thread thread1 = new Thread(new ThreadStart(number.worker));
             thread1.Start();

         }
        public void textupdate(Int64 cntr)
        {
           textBox1.Text += cntr.ToString();
        }

    }

    class Number
    {

    int _target;
    Textboxdelegate _callbackMethod;

    public Number(int target, Textboxdelegate TDD)
    {
        this._target = target;
        this._callbackMethod = TDD;
    }

    public void worker()
    {

            Int64 counter = 0;
            byte[] lifeforms = new byte[2146435071];

            for (long y = 1; y <= 2146; y++)
            {

                for (long X = 1; X <= 1000000; X++)
                {
                    lifeforms[X * y] = 20;
                }

                counter += 1;
                if(_callbackMethod != null)
                {
                _callbackMethod(counter);
                }

            }

            MessageBox.Show("Done!");
        }

    }
}

A: This crude example should do it for what you want to do:
    //public delegate void Textboxdelegate(Int64 MyVar);

    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        public Action<Int64> Textboxdelegate;
        public void runme()
        {
            textBox1.Text = "87";
            textupdate(44);

            int target = 0;
            Textboxdelegate = textupdate;
            Number number = new Number(target, Textboxdelegate,this);
            Textboxdelegate(11);
            Thread thread1 = new Thread(new ThreadStart(number.worker));
            thread1.Start();

        }
        public void textupdate(Int64 cntr)
        {
            textBox1.Text += cntr.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            runme();
        }

    }

    class Number
    {

        int _target;
        Action<Int64> _callbackMethod;
        Form1 frm;

        public Number(int target, Action<Int64> act,Form1 frm)
        {
            this._target = target;
            this._callbackMethod = act;
            this.frm = frm;
        }

        public void worker()
        {

            Int64 counter = 0;
            byte[] lifeforms = new byte[214643507];

            for (long y = 1; y <= 2146; y++)
            {

                for (long X = 1; X <= 100000; X++)
                {
                    lifeforms[X * y] = 20;
                }

                counter += 1;
                if (_callbackMethod != null)
                {
                    if (frm.InvokeRequired)
                    {
                        frm.Invoke(_callbackMethod,new object[]{counter});
                    }
                    else
                    {
                        _callbackMethod(counter);
                    }
                }

            }

            MessageBox.Show("Done!");
        }

    }

Controls have thread-afinity,meaning they can only be accessed from the thread that created them,and you where accessing them by another thread.Now the Invoke method of the Control class(the base of form and all its controls)will allow you to safelly access them(very summarized explanation).


text:
Q: Laravel 5.4 relationship - using the right type I have 3 tables:
users, user_addrs, orders
The orders table have these fields:
user_id, shipping_addr_id, billing_addr_id
In the UserAddr model I have:
public function order()
{
    return $this->hasMany('App\Order');
}

In the Order model I have:
public function userShippingAddr()
{
    return $this->belongsTo('App\UserAddr', 'shipping_addr_id');
}

public function userBillingAddr()
{
    return $this->belongsTo('App\UserAddr', 'billing_addr_id');
}

Is this the right way to do it or should I use a different relationship type?

A: In the UserAddr has 'id' as primary key than model you should have:
In the UserAddr model you should have:
public function order()
{
    return $this->hasMany('App\Order','shipping_addr_id');
    or
    return $this->hasMany('App\Order','billing_addr_id');

}

In the Order model you should have:
public function userShippingAddr()
{
    return $this->belongsTo('App\UserAddr', 'id','shipping_addr_id');
}

public function userBillingAddr()
{
    return $this->belongsTo('App\UserAddr', 'id', 'billing_addr_id');
}

using return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
read docs here

A: I have not tested this and I'm not sure if it is 100% what you want. But it should give you a good starting point.

1. What do you want?

*

*A user can have many addresses => (users)  - many -> (addresses)

*A order has one user => (orders) - one -> (users)

*A order has one billing address => (orders) - one billing -> (addresses)

*A order has one shipping address => (orders) - one shipping -> (addresses)
2. What tables do you need?

*

*users

*

*id

*...

*orders

*

*id

*users_id

*billing_addresses_id

*shipping_addresses_id

*addresses

*

*id

*zip

*city

*street

*...

*addresses_users

*

*users_id

*addresses_id

*type? (billing|shipping)

3. How should the models look like?
1. A user can have many addresses => (users)  - many -> (addresses)
class Users extends Model {
    // ...
    public function addresses() {
        return $this->belongsToMany('App\Models\Addresses')->withPivot('type');
    }
}

2. A order has one user => (orders) - one -> (users)
class Orders extends Model {
    // ...
    public function user() {
        return $this->belongsTo('App\Models\Users');
    }
}

3. A order has one billing address => (orders) - one billing -> (addresses)
class Orders extends Model {
    // ...
    public function billing_address() {
        return $this->belongsTo('App\Models\Addresses', 'id', 'billing_addresses_id');
    }
}

4. A order has one shipping address => (orders) - one shipping -> (addresses)
class Orders extends Model {
    // ...
    public function shipping_address() {
        return $this->belongsTo('App\Models\Addresses', 'id', 'shipping_addresses_id_addresses_id');
    }
}


text:
Q: Intersection point of two moving objects Suppose we have 2 moving objects along a linear path:
The first object moves at 5 metres/second.
The second object accelerates at 1.5 metres/second.
How would one calculate the point (in time) where both objects have the same position?

A: Distance traveled with constant acceleration is given by
$$
d = v_i t + \frac{1}{2} a t^2
$$
where you have $v_i=0$ for the accelerating object.  The distance traveled at constant velocity is
$$
d = vt
$$
So you are looking for $t$ such that
$$
\frac{1}{2}(1.5) t^2 = (5)t
$$